package tech.glinfo.enbao.common.utils;

import tech.glinfo.enbao.common.utils.StringUtils;
import tech.glinfo.enbao.modules.oss.cloud.OSSFactory;
import org.apache.commons.codec.binary.Base64;
import org.apache.http.entity.ContentType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Decoder;

import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;

@Component
public class WaterMark {

    protected Logger logger = LoggerFactory.getLogger(getClass());

    public final static String DATE_TIME_PATTERN = "yyyy-MM-dd HH:mm:ss";
//    public static String watermarkUrl="/opt/temp/location.png";
    /*public static String sourceImg="/opt/temp/110.jpg"; //源图片地址
    public static String targetImg="/opt/temp/111.jpg"; //新存储的地址*/


    @Value("${upload.watermarkUrl}")
    private String watermarkUrl;

    @Value("${upload.sourceImg}")
    private String sourceImg;

    @Value("${upload.targetImg}")
    private String targetImg;

    public static void main(String[] args) throws IOException {
        Font font = new Font("微软雅黑", Font.BOLD, 30);//字体

        Color color=new Color(255,255,255,255);
        System.out.println(getImgStr());
//        StringBuilder sb = new StringBuilder();
//        addWatermark("ii");
        //        markImgMark(watermarkUrl,sourceImg,targetImg);

    }

    /**
     * 为图片添加图片水印
     * @param watermarkUrl 原图
     * @param source 水印图片
     * @param output 制作完成的图片
     * @return
     * @throws IOException
     */
    public String markImgMark(String watermarkUrl, String source, String output) throws IOException {
        String result = "添加图片水印出错";
        File file = new File(source);
        Image img = ImageIO.read(file);
        int width = img.getWidth(null);//水印宽度
        int height = img.getHeight(null);//水印高
        BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics2D g = bi.createGraphics();
        g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
        g.drawImage(img.getScaledInstance(width, height, Image.SCALE_SMOOTH), 0, 0, null);
        ImageIcon imgIcon = new ImageIcon(watermarkUrl);
        Image con = imgIcon.getImage();
        float clarity = 1f;//透明度
        g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, clarity));
        g.drawImage(con, width-10, height-10, null);//水印的位置
        g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER));
        g.dispose();
        File sf = new File(output);
        ImageIO.write(bi, "jpg", sf); // 保存图片
        logger.info("添加图片水印成功");
        return result;
    }

    /** 设置文字水印
     * @throws IOException
     */
    public String addWatermark(String imgStr, String location) throws IOException {
        String imgFilePath = Base64ToImage(imgStr);

        return setWaterMark(location, imgFilePath);

    }

    private String setWaterMark(String location, String imgFilePath) throws IOException {
        int fontSize = 80;

        Font font = new Font("微软雅黑", Font.BOLD, fontSize);//字体

        Color color=new Color(255,255,255,255);

        File srcImgFile = new File(imgFilePath);
        Image srcImg = ImageIO.read(srcImgFile);
        int srcImgWidth = srcImg.getWidth(null);
        int srcImgHeight = srcImg.getHeight(null);
        BufferedImage bufImg = new BufferedImage(srcImgWidth, srcImgHeight, BufferedImage.TYPE_INT_RGB);
        Graphics2D g = bufImg.createGraphics();
        g.drawImage(srcImg, 0, 0, srcImgWidth, srcImgHeight, null);
        g.setColor(color);
        g.setFont(font);
        String watermark = format(new Date(), DATE_TIME_PATTERN);
        int w = 0;
        while (true){
            int w1 = g.getFontMetrics(g.getFont()).charsWidth(watermark.toCharArray(), 0, watermark.length()) + 60;
            if (StringUtils.isNotBlank(location)) {
                int w2 = g.getFontMetrics(g.getFont()).charsWidth(location.toCharArray(), 0, location.length()) + 60;
                w = w2 > w1 ? w2 : w1;
            }else {
                w = w1;

            }
            if(w > srcImgWidth) {
                fontSize -= 2;
                font = new Font("微软雅黑", Font.BOLD, fontSize);//字体
                g.setFont(font);
                continue;
            }
            logger.info("最后字体大小：" + fontSize);
            break;
        }

//        ImageIcon imgIcon = new ImageIcon(watermarkUrl);
//        Image con = imgIcon.getImage();
//        float clarity = 1f;//透明度
//        g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, clarity));
//        g.drawImage(con, 2, srcImgHeight-80, null);//水印的位置
//        g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER));

        //设置水印的坐标
//        int x = srcImgWidth - (g.getFontMetrics(g.getFont()).charsWidth(watermark.toCharArray(), 0, watermark.length())+20);
        int height = g.getFontMetrics(g.getFont()).getHeight();
//        logger.info("height:" + height);
        int y = srcImgHeight - 15;
        g.drawString(watermark, 10, y);  //加水印
        if (StringUtils.isNotBlank(location)) {
            watermark = location;
//        x = srcImgWidth - (g.getFontMetrics(g.getFont()).charsWidth(watermark.toCharArray(), 0, watermark.length())+20);
            g.drawString(watermark, 10, y-height);  //加水印
        }
        g.dispose();
        // 输出图片
        FileOutputStream outImgStream = null;
        String path =targetImg + File.separator + StringUtils.getUUID() + ".jpg";

        try {
            outImgStream = new FileOutputStream(path);
            ImageIO.write(bufImg, "jpg", outImgStream);

            logger.info(path);
            File file = new File(path);
            InputStream inputStream = new FileInputStream(file);
            MultipartFile multipartFile = new MockMultipartFile(file.getName(), file.getName(),
                    ContentType.APPLICATION_OCTET_STREAM.toString(), inputStream);

            String suffix = multipartFile.getOriginalFilename().substring(multipartFile.getOriginalFilename().lastIndexOf("."));
            String url = OSSFactory.build().uploadSuffix(multipartFile.getBytes(), suffix);
            return url;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            logger.info("添加水印完成");
            try {
                outImgStream.flush();
                outImgStream.close();
                //删除原本图片
                File file = new File(imgFilePath);
                if (file.exists()) {
                    file.delete();
                }

                //删除原本图片
                File file1 = new File(path);
                if (file1.exists()) {
                    file1.delete();
                }

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    /** 设置文字水印
     * @throws IOException
     */
    public String addWatermark1(String imgUrl, String location) throws IOException {

        String imgFilePath = sourceImg + File.separator + StringUtils.getUUID() + ".png";
        //下载到本地
        ImageUtils.downloadPicture(imgUrl, imgFilePath);

        return setWaterMark(location, imgFilePath);
    }

    public String format(Date date, String pattern) {
        if(date != null){
            SimpleDateFormat df = new SimpleDateFormat(pattern);
            return df.format(date);
        }
        return null;
    }
    /**
     * base64字符串转换成图片
     * @param imgStr        base64字符串
     * @return
     *
     */
    public String Base64ToImage(String imgStr) { // 对字节数组字符串进行Base64解码并生成图片
        String imgFilePath = sourceImg + File.separator + StringUtils.getUUID() + ".png";
        BASE64Decoder decoder = new BASE64Decoder();
        OutputStream out = null;
        try {
            String baseValue = imgStr.replaceAll(" ", "+");
            // 解密
            byte[] b = decoder.decodeBuffer(baseValue.replace("data:image/png;base64,", ""));
            // 处理数据
            for (int i = 0; i < b.length; ++i) {
                if (b[i] < 0) {
                    b[i] += 256;
                }
            }

            out = new FileOutputStream(imgFilePath);
            out.write(b);
            out.flush();
            return imgFilePath;
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        } finally {
            if(out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }

    public static String getImgStr() {
        // 将图片文件转化为字节数组字符串，并对其进行Base64编码处理

        InputStream in = null;
        byte[] data = null;
        // 读取图片字节数组
        try {
            in = new FileInputStream("C:\\Users\\29283\\Downloads\\7a3f8aa1ab886281462e428af617faa5.jpg");
            data = new byte[in.available()];
            in.read(data);
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new String(Base64.encodeBase64(data));
    }

}
