package org.dromara.web.controller;


import lombok.RequiredArgsConstructor;
import org.dromara.common.core.config.BoManConfig;
import org.dromara.common.core.config.ServerConfig;
import org.dromara.common.core.domain.R;
import org.dromara.common.core.utils.ImageSizeUtil;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.core.utils.file.FileUploadUtils;
import org.dromara.common.core.utils.file.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 通用请求处理
 *
 * @author ruoyi
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/common")
public class CommonController
{
    private static final Logger log = LoggerFactory.getLogger(CommonController.class);


    private final ServerConfig serverConfig;

    private static final String FILE_DELIMETER = ",";


    /**
     * 通用上传请求（单个）
     */
    @PostMapping("/upload")
    public R<Map<String,String>> uploadFile(MultipartFile file) throws Exception
    {
        try
        {
            String originalFilename = file.getOriginalFilename();
            String fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
            //压缩图片 "bmp", "gif", "jpg", "jpeg", "png",
            if(".png".equalsIgnoreCase(fileExtension) || ".bmp".equalsIgnoreCase(fileExtension)  || ".gif".equalsIgnoreCase(fileExtension) || ".jpeg".equalsIgnoreCase(fileExtension)){
                file = ImageSizeUtil.compressImg(file);
            }

            // 上传文件路径
            String filePath = BoManConfig.getUploadPath();
            // 上传并返回新文件名称
            String fileName = FileUploadUtils.upload(filePath, file);
            String url = serverConfig.getUrl() + fileName;
            Map<String, String> map = new HashMap<>();
            //服务器路径
            String urlOnline = filePath + fileName.replace("/profile/upload", "");
            map.put("url", url);
            map.put("urlOnline", urlOnline);
            map.put("fileName", fileName);
            map.put("newFileName", FileUtils.getName(fileName));
            map.put("originalFilename", file.getOriginalFilename());
            return R.ok(map);
        }
        catch (Exception e)
        {
            return R.fail(e.getMessage());
        }
    }

    /**
     * 通用上传请求（多个）
     */
    @PostMapping("/uploads")
    public R<Map<String,String>> uploadFiles(List<MultipartFile> files) throws Exception
    {
        try
        {
            // 上传文件路径
            String filePath = BoManConfig.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());
            }
            Map<String, String> map = new HashMap<>();
            map.put("urls", StringUtils.join(urls, FILE_DELIMETER));
            map.put("fileNames", StringUtils.join(fileNames, FILE_DELIMETER));
            map.put("newFileNames", StringUtils.join(newFileNames, FILE_DELIMETER));
            map.put("originalFilenames", StringUtils.join(originalFilenames, FILE_DELIMETER));
            return R.ok(map);
        }
        catch (Exception e)
        {
            return R.fail(e.getMessage());
        }
    }
}
