package com.inkasso.factoring.file.util;

import cn.hutool.core.util.IdUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.alibaba.druid.util.StringUtils;
import com.inkasso.adapter.enums.FileBusinessInterface;
import com.inkasso.config.properties.FileUploadProperties;
import com.inkasso.factoring.file.entity.FileStorageDO;
import com.inkasso.factoring.file.enums.FileTypeEnum;
import jodd.util.StringUtil;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;

public class FileStorageUtil {
  /** 存储磁盘 */
  private static String DISK;
  /** 所有文件存储目录 */
  public static String DIR = "fileResource";
  /** classPath路径 */
  private static String CLASS_PATH;
  /** 资源绝对存储路径 */
  private static String ABSOLUTE_PATH;
  public static FileStorageDO createFileStorage(MultipartFile multipartFile,
                                                FileBusinessInterface fileBusinessEnum) {
    FileStorageDO fileStorageDO = new FileStorageDO();
    String originalFilename = multipartFile.getOriginalFilename();
    String suffix = getSuffix(originalFilename);
    fileStorageDO.setOriginalName(originalFilename);
    fileStorageDO.setType(suffix);
    fileStorageDO.setSize(multipartFile.getSize());
    String newFileName = IdUtil.fastSimpleUUID() + suffix;
    FileUploadProperties bean = SpringUtil.getBean(FileUploadProperties.class);
    fileStorageDO.setPath(fileBusinessEnum.getCode() + File.separator + newFileName);
    File file = new File(bean.getStoragePath() + File.separator + fileBusinessEnum.getCode() + File.separator
        + newFileName);
    fileStorageDO.setAbsolutePath(file.getAbsolutePath());
    fileStorageDO.setBusinessType(fileBusinessEnum.getCode());
    return fileStorageDO;
  }

  public static FileStorageDO createFileStorage2(String name,String suffix,
                                                FileBusinessInterface fileBusinessEnum) {
    FileStorageDO fileStorageDO = new FileStorageDO();
    fileStorageDO.setOriginalName(name+ suffix);
    fileStorageDO.setType(suffix);
    String newFileName = IdUtil.fastSimpleUUID() + suffix;
    FileUploadProperties bean = SpringUtil.getBean(FileUploadProperties.class);
    fileStorageDO.setPath(fileBusinessEnum.getCode() + File.separator + newFileName);
    File file = new File(bean.getStoragePath() + File.separator + fileBusinessEnum.getCode() + File.separator
            + newFileName);
    fileStorageDO.setAbsolutePath(file.getAbsolutePath());
    fileStorageDO.setBusinessType(fileBusinessEnum.getCode());
    return fileStorageDO;
  }

  public static FileStorageDO createFileStorage3(String contractId, FileTypeEnum fileBusinessEnum, String fileName, String suffix) {
    FileStorageDO fileStorageDO = new FileStorageDO();
    fileStorageDO.setOriginalName(fileName);
    fileStorageDO.setType(suffix);
    fileStorageDO.setStorageType("disk");
    String newFileName = fileName + suffix;
    FileUploadProperties bean = SpringUtil.getBean(FileUploadProperties.class);
    fileStorageDO.setPath(fileBusinessEnum.getCode() + File.separator + newFileName);
    File file = new File(bean.getStoragePath()+ File.separator +DIR + File.separator + fileBusinessEnum.getCode() + File.separator
            + newFileName);
    fileStorageDO.setSize(file.length());
    fileStorageDO.setAbsolutePath(file.getAbsolutePath());
    fileStorageDO.setBusinessType(fileBusinessEnum.getCode());
    return fileStorageDO;
  }

  /**
   * 获取文件后缀
   */
  public static String getSuffix(String name) {

    if (!StringUtils.isEmpty(name) && name.indexOf(".") > 0) {
      return name.substring(name.lastIndexOf("."));
    } else {
      return "";
    }
  }

  /**
   * 采用指定宽度、高度或压缩比例 的方式对图片进行压缩
   *
   * @param imgSrc 源图片地址
   * @param imgDist 目标图片地址
   * @param widthDist 压缩后图片宽度（当rate==null时，必传）
   * @param heightDist 压缩后图片高度（当rate==null时，必传）
   * @param rate 压缩比例
   */
  public static void compressImg(String imgSrc, String imgDist, int widthDist, int heightDist, Float rate) {
    FileOutputStream out = null;
    try {
      File srcfile = new File(imgSrc);
      // 检查文件是否存在
      if (!srcfile.exists()) {
        return;
      }
      // 如果rate不为空说明是按比例压缩
      if (rate != null && rate > 0) {
        // 获取文件高度和宽度
        int[] results = getImgWidth(srcfile);
        if (results == null || results[0] == 0 || results[1] == 0) {
          return;
        } else {
          widthDist = (int) (results[0] * rate);
          heightDist = (int) (results[1] * rate);
        }
      }
      // 开始读取文件并进行压缩
      Image srcImg = javax.imageio.ImageIO.read(srcfile);
      BufferedImage newImg = new BufferedImage((int) widthDist, (int) heightDist, BufferedImage.TYPE_INT_RGB);
      newImg.getGraphics().drawImage(srcImg.getScaledInstance(widthDist, heightDist, Image.SCALE_SMOOTH), 0, 0,
              null);
      out = new FileOutputStream(imgDist);
      ImageIO.write(newImg, imgDist.substring(imgDist.lastIndexOf(".") + 1), out);
    } catch (IOException ex) {
      ex.printStackTrace();
    }finally {
      if (out != null){
        try {
          out.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    }
  }

  /**
   * 获取图片宽度
   *
   * @param file 图片文件
   * @return 宽度
   */
  public static int[] getImgWidth(File file) {
    InputStream is = null;
    BufferedImage src = null;
    int result[] = {
            0, 0
    };
    try {
      is = new FileInputStream(file);
      src = javax.imageio.ImageIO.read(is);
      result[0] = src.getWidth(null); // 得到源图宽
      result[1] = src.getHeight(null); // 得到源图高
      is.close();
    } catch (Exception e) {
      e.printStackTrace();
    }
    return result;
  }


  /**
   * 获取资源绝对存储路径
   *
   * @param fileName 文件名称
   * @param suffix 文件后缀
   * @param moduleType 文件所属模块枚举实例
   * @return
   */
  public static String getAbsolutePath(String fileName, String suffix, FileTypeEnum moduleType) {
    return getAbsoluteDir() + getFilePath(fileName, suffix, moduleType);
  }

  /**
   * 获取文件路径
   *
   * @param fileName 文件名称
   * @param suffix 文件后缀
   * @param moduleType 文件所属模块枚举实例
   * @return
   */
  public static String getFilePath(String fileName, String suffix, FileTypeEnum moduleType) {
    StringBuilder sb = new StringBuilder("/");
    sb.append(DIR).append("/").append(moduleType.getCode());
    sb.append(getDatePath()).append(fileName).append(suffix);
    return sb.toString();
  }
  /** 获取以日期格式的文件路径 */
  public static String getDatePath() {
    return "/";
  }

  /** 获取资源绝对存储目录 */
  public static String getAbsoluteDir() {
    if (StringUtil.isEmpty(ABSOLUTE_PATH)) {
      FileUploadProperties bean = SpringUtil.getBean(FileUploadProperties.class);
      File file = new File(bean.getStoragePath());
      ABSOLUTE_PATH = file.getAbsolutePath();
    }
    return ABSOLUTE_PATH;
  }


//  public static void main(String[] args) {
//    System.out.println("=========="+IdUtil.randomUUID());
//    System.out.println("=========="+IdUtil.fastSimpleUUID());
//    System.out.println("=========="+IdUtil.fastUUID());
//  }
}
