package com.ruoyi.file.config;


import cn.hutool.core.img.ImgUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import com.ruoyi.common.utils.spring.SpringUtils;
import lombok.AccessLevel;
import lombok.Data;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.ConfigurationProperties;

import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.InputStream;


@Configuration
@ConfigurationProperties(prefix = "ruoyi.file")
@Data
@Slf4j
public class SpringFileStorageProperties extends org.dromara.x.file.storage.spring.SpringFileStorageProperties {

  private Integer maxWidth;
  private Integer maxHeight;
  private String watermark = "classpath:/watermark.png";
  private Integer thWidth;
  private Integer thHeight;
  @Getter
  @Setter(AccessLevel.PRIVATE)
  private BufferedImage watermarkImage;

  /**
   * 初始化在FileRunner中完成
   */
  //  @PostConstruct
  public void init() {
    try {
      if (StrUtil.isBlank(watermark)) {
        log.info("水印图片未配置，不添加水印");
        return;
      }
      if (watermark.contains("://")) {
        InputStream in = HttpUtil.createGet(watermark).execute().bodyStream();
        watermarkImage = ImgUtil.read(in);
        IoUtil.close(in);
        log.info("水印图片加载成功:" + watermark);
      } else {
        File file = new File(watermark);
        if (file.isFile()) {
          watermarkImage = ImgUtil.read(file);
          log.info("水印图片加载成功:" + watermark);
          return;
        }
        Resource resource = SpringUtils.context().getResource(watermark);
        if (resource.exists() && resource.isFile()) {
          watermarkImage = ImgUtil.read(resource.getFile());
          log.info("水印图片加载成功:" + watermark);
        } else {
          log.info("水印图片不存在:" + watermark);
        }

      }

    } catch (Exception e) {
      log.warn("水印图片初始化失败: " + watermark, e);
    }
  }

}
