package cn.ezhizao.common.utils;

import cn.ezhizao.common.utils.bean.ImgWaterMarker;
import cn.ezhizao.common.utils.bean.TextWaterMarker;
import cn.ezhizao.common.utils.bean.WaterMarker;
import cn.hutool.core.img.Img;
import cn.hutool.core.img.ImgUtil;
import cn.hutool.core.io.FileUtil;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Async;

import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.URL;

;


/**
 * 名片水印合成 相关静态方法
 * @author 朱汕
 */
@Configuration
public class WaterMakerUtils {

    /**图片添加水印*/
    @Async
    public String imageCombine(WaterMarker waterMarker){
        // 先加水印图 1 头像  2 小程序码  3 地图
        // 先加一个空的文字水印 复制一张底图出来
        ImgUtil.pressText(
                FileUtil.file(waterMarker.getBackgroundImgUrl()),
                FileUtil.file(waterMarker.getPhysicalPath()),
                " ", Color.WHITE,
                new Font("黑体", Font.BOLD, 100),
                0,
                0,
                0.0f
        );
        waterMarker.setBackgroundImgUrl(waterMarker.getPhysicalPath());
        java.util.List<ImgWaterMarker> images = waterMarker.getImages();
        java.util.List<TextWaterMarker> texts = waterMarker.getTexts();
        // 图片水印
        if(!images.isEmpty()){
            images.forEach(l->{
                try {
                    if(l.getIsLocal()&&l.getIsScale()){
                        ImgUtil.scale(
                                FileUtil.file(l.getImgUrl()),
                                FileUtil.file(l.getImgUrl()),
                                //缩放比例
                                l.getScaleRate()
                        );
                    }
                    System.out.println(l.getImgUrl());
                    ImgUtil.pressImage(
                        FileUtil.file(waterMarker.getBackgroundImgUrl()),
                        FileUtil.file(waterMarker.getPhysicalPath()),
                        l.getIsLocal()?ImgUtil.read(FileUtil.file(l.getImgUrl())): ImageIO.read(new URL(l.getImgUrl())), // 水印图片
                        l.getX(), // x坐标修正值。 默认在中间，偏移量相对于中间偏移
                        l.getY(), // y坐标修正值。 默认在中间，偏移量相对于中间偏移
                        l.getTransparency()
                    );
                } catch (IOException e) {
                    e.printStackTrace();
                }
            });
        }
        if(!texts.isEmpty()){
            for (TextWaterMarker text:texts) {
                drawText(text,FileUtil.file(waterMarker.getPhysicalPath()),text.getContent(),text.getX(),text.getY());
            }
        }
        return waterMarker.getRelativePath();
    }

    /**
     *   自动换行的递归方法
     */
    private void drawText(TextWaterMarker text,File desImage,String textContent,int x,int y){
        int textH = getTextHeight(text.getFont(),textContent);
        int textW = getTextWidth(text.getFont(),textContent);
        Img img = Img.from(ImgUtil.read(desImage)).setPositionBaseCentre(false);
        Integer maxWidth = text.getMaxWidth();
        String tempText = textContent;
        if(maxWidth!=null) {
            if (textW > maxWidth) {
                float n = textW / (float)maxWidth;
                int subPos = (int) (tempText.length() / n);
                String drawText = tempText.substring(0, subPos);
                Image imageFile = img.pressText(drawText, text.getColor(),text.getFont(), x, y,text.getTransparency()).getImg();
                ImgUtil.write(imageFile, desImage);
                y += textH + 5;
                tempText = tempText.substring(subPos);
                drawText(text, desImage, tempText, x, y);
            }else {
                Image imageFile = img.pressText(tempText, text.getColor(),text.getFont(), x, y,text.getTransparency()).getImg();
                ImgUtil.write(imageFile, desImage);
            }
        }else{
            Image imageFile = img.pressText(tempText, text.getColor(),text.getFont(), x, y,text.getTransparency()).getImg();
            ImgUtil.write(imageFile, desImage);
        }
    }



    public static int getTextWidth(Font font,String text){
        JLabel label = new JLabel(text);
        label.setFont(font);
        FontMetrics metrics = label.getFontMetrics(label.getFont());
        return metrics.stringWidth(label.getText());
    }
    public static int getTextHeight(Font font,String text){
        JLabel label = new JLabel(text);
        label.setFont(font);
        FontMetrics metrics = label.getFontMetrics(label.getFont());
        return metrics.getHeight();
    }

    public static int getImgWidth(String path){
        // 图片文件的路径
        File imageFile = new File(path);
        BufferedImage bufferedImage = null;
        try {
            return ImageIO.read(imageFile).getHeight();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

}
