package com.sunxung.factoring.component.util;

import cn.hutool.core.util.IdUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.alibaba.druid.util.StringUtils;
import com.sunxung.factoring.component.config.FileUploadProperties;
import com.sunxung.factoring.component.enums.FileBusinessInterface;
import com.sunxung.factoring.entity.sys.FileStorageDO;
import org.springframework.web.multipart.MultipartFile;

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

public class FileStorageUtil {

  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);
    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 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 = 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 = ImageIO.read(is);
      result[0] = src.getWidth(null); // 得到源图宽
      result[1] = src.getHeight(null); // 得到源图高
      is.close();
    } catch (Exception e) {
      e.printStackTrace();
    }
    return result;
  }

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