package com.backendsys.modules.upload.utils;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.convert.Convert;
import com.backendsys.exception.CustException;
import com.backendsys.modules.common.utils.CommonUtil;
import com.backendsys.modules.upload.entity.SysFileResult;
import com.backendsys.modules.upload.enums.StyleEnums;
import com.backendsys.utils.response.Result;
import com.backendsys.utils.response.ResultEnum;
import net.coobird.thumbnailator.Thumbnails;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.util.UriComponentsBuilder;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;

@Component
public class UploadUtil {

    @Value("${file.upload.directory}") // 配置保存文件的目录
    private String FILE_UPLOAD_DIRECTORY;

    @Value("${file.upload.url-prefix}") // 指定文件访问的 URL前缀
    private String FILE_UPLOAD_URL_PREFIX;

    public SysFileResult put(MultipartFile multipartFile) {

        try {
            // 创建保存文件的目录，如果不存在
            File directory = new File(FILE_UPLOAD_DIRECTORY);
            if (!directory.exists()) { directory.mkdirs(); }

            // 获取文件原始名
            String originalFileName = multipartFile.getOriginalFilename();
            // 获取后缀名
            String suffix = originalFileName.substring(originalFileName.lastIndexOf("."));

            // 生成新的文件名 (UUID)
            String newFileName = CommonUtil.generateUUIDFilename(multipartFile);
            String newFileNameThumb = newFileName.replaceAll(suffix, "-thumb" + suffix);

            // 按日期作为文件目录
            String pathDir = new SimpleDateFormat("yyyyMMdd").format(new Date());
            String dateDir = pathDir + File.separator;

            File dateDirectory = new File(FILE_UPLOAD_DIRECTORY + dateDir);
            if (!dateDirectory.exists()) { dateDirectory.mkdirs(); }

            // 确定文件保存的路径
            String sourceFilePath = FILE_UPLOAD_DIRECTORY + dateDir + newFileName;
//            String sourceFilePathThumb = FILE_UPLOAD_DIRECTORY + dateDir + newFileNameThumb;

            System.out.println(sourceFilePath);
//            System.out.println(sourceFilePathThumb);

            File sourceFile = new File(sourceFilePath);
//            File sourceFileThumb = new File(sourceFilePathThumb);

            // 保存文件到本地
            multipartFile.transferTo(sourceFile);
            
            // 创建缩略图
            // .scale(0.5)  // 缩放
            // .outputFormat("png") // 类型
            // .sourceRegion(Positions.TOP_RIGHT, 1800, 1800) // 裁剪
            // .watermark(Positions.BOTTOM_RIGHT, ImageIO.read(new File("watermark.png")), 0.5f)  // 添加水印
            // .outputQuality(0.2) // 质量
            
            // 文件批量操作
            // Thumbnails.of(new File("/images/202401/").listFiles()).size(400, 400).toFiles(Rename.PREFIX_DOT_THUMBNAIL);
            
//            Thumbnails.of(sourceFilePath).size(200, 200).toFile(sourceFilePathThumb);


            // 返回文件的路径 (绝对路径)
            String fileUrl = FILE_UPLOAD_URL_PREFIX + pathDir + "/" + newFileName;
//            String fileThumbUrl = FILE_UPLOAD_URL_PREFIX + pathDir + "/" + newFileNameThumb;

            // 自定义返回结果实体
            SysFileResult result = new SysFileResult();
            result.setDomain(fileUrl);
            result.setKey(sourceFilePath);
            return result;

        } catch (IOException e) {
            throw new CustException(e.getMessage());
        }

    }

    public void delete(String object_key) {
        // 根据传入的文件路径创建 File 对象
        File fileToDelete = new File(object_key);
        // 检查文件是否存在
        if (fileToDelete.exists()) {
            // 删除文件
            if (fileToDelete.delete()) {
                System.out.println("本地文件删除成功 (" + object_key + ")");
            }
        } else {
            System.out.println("本地文件不存在，删除失败 (" + object_key + ")");
        }
    }

    /**
        获取缩略图 URL
        不同的云环境 (target)，缩略图配置也不一样
        -1:本地:
        1:腾讯云: https://cloud.tencent.com/document/product/436/113295
        2:阿里云:
        3:抖音云: https://www.volcengine.com/docs/6349/153626
     */
    public static String getImageThumbUrl(String url, Integer target, Integer width, Integer height) {
        return getImageThumbUrl(url, target, width, height, StyleEnums.THUMB_BACKGROUND.getValue());
    }
    public static String getImageThumbUrl(String url, Integer target, Integer width, Integer height,
                                          String backgroundColor) {
        return getImageThumbUrl(url, target, width, height, backgroundColor, false);
    }
    public static String getImageThumbUrl(String url, Integer target, Integer width, Integer height,
                                          String backgroundColor, Boolean is_importent) {
        if (target == -1) {
            UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url);
            if (width != null) builder.queryParam("w", width);
            if (height != null) builder.queryParam("h", height);
            return builder.toUriString();
//            return url + "?" + "w=" + width + "&h=" + height;
        }
        // 腾讯云 (color值通过base64加密, #f8f8f8)
        if (target == 1) {
            backgroundColor = "#" + backgroundColor;
            String w = (width != null) ? Convert.toStr(width) : "";
            String h = (height != null) ? Convert.toStr(height) : "";
            return url + "?imageMogr2/thumbnail/" + (w != null ? w : "") + "x" + (h != null ? h : "") +
                    (is_importent ? "!" : "") + "/pad/1/color/" + Base64.encode(backgroundColor);
        }
        // 抖音云
        if (target == 3) {
            String w = (width != null) ? (",w_" + width) : "";
            String h = (height != null) ? (",h_" + height) : "";
//            return url + "?x-tos-process=image/resize,w_" + width + ",h_" + height + ",m_pad,color_" + backgroundColor;
            return url + "?x-tos-process=image/resize" + w + h + ",color_" + backgroundColor;
        }
        return url;
    }




}
