package cn.com.capcloud.api.action.service.util;

import cn.com.capcloud.api.action.service.MinioService;
import cn.com.capcloud.ccui.core.common.json.JackJSONObject;
import cn.com.capcloud.ccui.core.common.utils.UUIDUtils;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.joda.time.DateTime;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author LiaoJiaHui
 * @Create 2026/4/27
 */
public class FileUtil {

    public static Map<String,Object> uploadToService(String filePath, HttpServletRequest request) {
        Map<String,Object>  returnMap=new HashMap<>();
        MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest) request;
        List<MultipartFile> files = multipartHttpServletRequest.getFiles("uploadFile");
        String realFileName=files.get(0).getOriginalFilename();
        String suffix=realFileName.substring(realFileName.lastIndexOf(".")+1);
        String realName = realFileName.replace("."+suffix, "");
        DateTime d=new DateTime();
        String fileDir=filePath+d.toString("yyyyMM");
        File folder = new File(fileDir);
        if (!folder.exists()) {
            folder.mkdirs();
        }
        //文件上传组件
        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setHeaderEncoding("UTF-8");
        try {
            for (MultipartFile fileItem : files) {
                // uuid当文件名
                String fileName= UUIDUtils.randomUuidWithoutHyphen();
                returnMap.put("uuid", fileName);
                //io 输入流读文件
                InputStream is = fileItem.getInputStream();
                //利用输出流写入对应的文件夹
                FileOutputStream fout = new FileOutputStream(new File(fileDir + "/" + fileName + "." + suffix));
                //写入数据
                byte[] buffer = new byte[1024];
                int len = 0;
                while ((len = (is.read(buffer))) > -1) {
                    fout.write(buffer, 0, len);
                }
                fout.close();
                is.close();
                returnMap.put("source", "service");
                returnMap.put("realFileName", realFileName);
                returnMap.put("realName", realName);
                returnMap.put("diskFileName", d.toString("yyyyMM")+"/"+fileName + "." + suffix);
                returnMap.put("suffix",  suffix);
                returnMap.put("fileSize",files.get(0).getSize());
                returnMap.put("fileShowSize", readableFileSize(files.get(0).getSize()));
                //判断如果是图片将宽高放到map里
                if(suffix.equalsIgnoreCase("jpg")||suffix.equalsIgnoreCase("png")||suffix.equalsIgnoreCase("jpeg")){
                    returnMap.put("width",  request.getParameter("width"));
                    returnMap.put("height",  request.getParameter("height"));
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return returnMap;
    }

    public static Map<String,Object> uploadToMinio(JackJSONObject retJson, MinioService minioService, HttpServletRequest request) {
        Map<String,Object>  returnMap= null;
        try {
            returnMap = minioService.uploadToMinio(retJson,request);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return returnMap;
    }

    public static String readableFileSize(long size){
        if (size <= 0) {
            return "0";
        }
        final String[] units = new String[]{"B", "KB", "MB", "GB", "TB"};
        int digitGroups = (int) (Math.log10(size) / Math.log10(1024));
        return new DecimalFormat("#,###.##").format(size / Math.pow(1024, digitGroups)) + " " + units[digitGroups];
    }

    /**
     * 判断文件路径是否包含非法字符，防止路径遍历攻击
     */
    public static boolean isInvalidPath(String fileName) {
        return fileName.contains("..");
    }
}
