package com.ruoyi.web.controller.api;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.ApiResult;
import com.ruoyi.common.utils.ImgUpload;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.cs.domain.dto.DictParamDTO;
import com.ruoyi.cs.domain.vo.CsResourceDictDataVO;
import com.ruoyi.cs.domain.vo.DictParamVO;
import com.ruoyi.cs.domain.vo.SysDictDataVO;
import com.ruoyi.cs.service.ICsResourceDictDataService;
import com.ruoyi.framework.config.ServerConfig;
import com.ruoyi.system.service.ISysDictDataService;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName ApiCommonController
 * @Description 图片上传接口
 * @Author LCL
 * @Date 2024/03/11
 * @Version 1.0
 **/
@Api("通用接口")
@RestController
@RequestMapping("/api/common")
@ResponseBody
public class ApiCommonController {

    @Resource
    private ServerConfig serverConfig;

    private static final String FILE_DELIMETER = ",";

    @Resource
    private ICsResourceDictDataService resourceDictDataService;

    @Resource
    private ISysDictDataService sysDictDataService;

    /**
     * 单个上传（七牛云）
     *
     * @param file
     * @param request
     * @return
     */
    @PostMapping("/upload")
    @ResponseBody
    @CrossOrigin
    @Log(title = "单个上传（七牛云）", businessType = BusinessType.INSERT)
    public ApiResult upload(MultipartFile file, HttpServletRequest request) {
        String fileName = null;
        try {
            BufferedImage image = ImageIO.read(file.getInputStream());
            if (image != null) {//如果image=null 表示上传的不是图片格式
//			    System.out.println(image.getWidth());//获取图片宽度，单位px
//			    System.out.println(image.getHeight());//获取图片高度，单位px
                fileName = "IMG_" + image.getWidth() + "_" + image.getHeight() + "@";
            } else {
                fileName = "";
            }
            String imagePath = new ImgUpload().upload(file.getBytes(),
                    fileName);
            if (StringUtils.isBlank(imagePath)) {
                return ApiResult.error("上传失败");
            }
            return ApiResult.ok().put("data", imagePath);
        } catch (Exception e) {
            return ApiResult.error();
        }
    }

    /**
     * 通用上传请求（本地单个）
     */
    @PostMapping("/uploadFileLocal")
    @Log(title = "通用上传请求（本地单个）", businessType = BusinessType.INSERT)
    public AjaxResult uploadFileLocal(MultipartFile file) throws Exception {
        try {
            // 上传文件路径
            String filePath = RuoYiConfig.getUploadPath();
            // 上传并返回新文件名称
            String fileName = FileUploadUtils.upload(filePath, file);
            String url = serverConfig.getUrl() + fileName;
            AjaxResult ajax = AjaxResult.success();
            String replace = url.replace("http://chaosuan.xnszz.com", "https://chaosuan.xnszz.com");
            ajax.put("url", replace);
            ajax.put("fileName", fileName);
            ajax.put("newFileName", FileUtils.getName(fileName));
            ajax.put("originalFilename", file.getOriginalFilename());
            return ajax;
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 通用上传请求（本地多个）
     */
    @PostMapping("/uploadFilesLocal")
    @Log(title = "通用上传请求（本地多个）", businessType = BusinessType.INSERT)
    public AjaxResult uploadFilesLocal(List<MultipartFile> files) throws Exception {
        try {
            // 上传文件路径
            String filePath = RuoYiConfig.getUploadPath();
            List<String> urls = new ArrayList<String>();
            List<String> fileNames = new ArrayList<String>();
            List<String> newFileNames = new ArrayList<String>();
            List<String> originalFilenames = new ArrayList<String>();
            for (MultipartFile file : files) {
                // 上传并返回新文件名称
                String fileName = FileUploadUtils.upload(filePath, file);
                String url = serverConfig.getUrl() + fileName;
                urls.add(url);
                fileNames.add(fileName);
                newFileNames.add(FileUtils.getName(fileName));
                originalFilenames.add(file.getOriginalFilename());
            }
            AjaxResult ajax = AjaxResult.success();
            ajax.put("urls", StringUtils.join(urls, FILE_DELIMETER));
            ajax.put("fileNames", StringUtils.join(fileNames, FILE_DELIMETER));
            ajax.put("newFileNames", StringUtils.join(newFileNames, FILE_DELIMETER));
            ajax.put("originalFilenames", StringUtils.join(originalFilenames, FILE_DELIMETER));
            return ajax;
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 获取资源字典参数列表
     * @param param 字典参数
     * @return 结果
     */
    @GetMapping("/getSysDictParamList")
    public AjaxResult getSysDictParamList(DictParamDTO param){
        List<SysDictDataVO> dictParamList = sysDictDataService.selectDictValueForMember(param);
        return AjaxResult.success(dictParamList);
    }

    /**
     * 获取模板组件字典参数列表
     * @param param 字典参数
     * @return 结果
     */
    @GetMapping("/getCSDictParamList")
    public AjaxResult getCSDictParamList(DictParamDTO param){
        List<CsResourceDictDataVO> dictParamList = resourceDictDataService.selectOptions(param);
        return AjaxResult.success(dictParamList);
    }

}
