package com.sifang.modules.customer.utils;

import com.sifang.modules.sys.common.utils.IdGen;
import org.springframework.core.io.ClassPathResource;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.URL;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLDecoder;
import javax.imageio.ImageIO;
/**
 * 合并图片
 */
public class MergeImageUtil {


    /**
     * 给图片指定位置打马赛克
     *
     * @param x 图片要打码区域左上角的横坐标
     * @param y 图片要打码区域左上角的纵坐标
     * @param width 图片要打码区域的宽度
     * @param height 图片要打码区域的高度
     * @param mosaicSize 马赛克尺寸，即每个矩形的长宽
     */
    public static boolean mosaic(File input, File out,
                                 int x, int y,  int mosaicSize) throws IOException {
        //读取该图片
        BufferedImage bi = ImageIO.read(input);
        //复制一份画布，在新画布上作画，因为要用到原来画布的颜色信息
        BufferedImage spinImage = new BufferedImage(bi.getWidth(),
                bi.getHeight(), BufferedImage.TYPE_INT_RGB);
        //马赛克块大小 不能大于图片宽度和高度
        if (mosaicSize > bi.getWidth() || mosaicSize > bi.getHeight() || mosaicSize <= 0) {
            System.err.println("马赛克尺寸设置不正确");
            return false;
        }
        int width=bi.getWidth()-100;
        int height=bi.getHeight()-100;
        //2. 设置各方向绘制的马赛克块个数
        int xcount = width / mosaicSize; // x方向绘制个数
        int ycount = height / mosaicSize; // y方向绘制个数
        if ((width % mosaicSize) != 0) {
            xcount++;
        }
        if ((height % mosaicSize) != 0) {
            ycount++;
        }
        //3. 绘制马赛克(在指定范围内绘制矩形并填充颜色)
        Graphics gs = spinImage.getGraphics();
        //将老画布内容画到新画布上
        gs.drawImage(bi, 0, 0, null);
        int xTmp = x;
        int yTmp = y;
        for (int i = 0; i < xcount; i++) {
            for (int j = 0; j < ycount; j++) {
                //马赛克矩形大小
                int mwidth = mosaicSize;
                int mheight = mosaicSize;
                if (i == xcount - 1) {   //横向最后一个比较特殊，可能不够一个size
                    mwidth = width - xTmp;
                }
                if (j == ycount - 1) {  //同理
                    mheight = height - yTmp;
                }
                //矩形颜色取中心像素点RGB值
                int centerX = xTmp;
                int centerY = yTmp;
                if (mwidth % 2 == 0) {
                    centerX += mwidth / 2;
                } else {
                    centerX += (mwidth - 1) / 2;
                }
                if (mheight % 2 == 0) {
                    centerY += mheight / 2;
                } else {
                    centerY += (mheight - 1) / 2;
                }
                Color color = new Color(bi.getRGB(centerX, centerY));
                gs.setColor(color);
                gs.fillRect(xTmp, yTmp, mwidth, mheight);
                yTmp += mosaicSize;// 计算下一个矩形的y坐标
            }
            yTmp = y;// 还原y坐标
            xTmp += mosaicSize;// 计算x坐标
        }
        gs.dispose();
        ImageIO.write(spinImage, "jpg", out); // 保存图片
        return true;
    }


    /**
     * 水印编码: 将内容编码成Base64
     *
     * @param str
     * @return
     */
    private static String encode(String str){
        byte[] encode = java.util.Base64.getEncoder().encode(str.getBytes());
        try {
            // 1.将结果中的加号（+）替换成短划线（-）  2.将结果中的正斜线（/）替换成下划线（_）  3.将结果中尾部的等号（=）省略
            return new String(encode, "UTF-8").replace("+","-").replace("/","_");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return str;
    }
    private static final String FILE_PATH_TEMPLATE = System.getProperty("java.io.tmpdir") + "/tempdf/%s";
    public static void main(String[] args) {
       // File input = new File("D:\\20230523151752.jpg");
       // File out = new File("D:\\e325344asass.jpg");
     //   File watermarkImage = new File("https://sky-energy.oss-cn-beijing.aliyuncs.com/prohibit_delete/masaike.png");
        String fileName = "https://sky-energy.oss-cn-beijing.aliyuncs.com/energy_img/%E8%BA%AB%E4%BB%BD%E8%AF%81%E6%AD%A3%E9%9D%A2.jpg";
        try {
            fileName = URLDecoder.decode(fileName,"utf-8");
            URL url = new URL(fileName);

            System.out.println(url);

            String extName = "jpg";
            String filenewUrl = "D\\"+"iweioereiii."+extName;
            File out = new File("D:\\4334444.jpg");
            URL watermarkImage = new URL("https://sky-energy.oss-cn-beijing.aliyuncs.com/prohibit_delete/masaike.png");
            MergeImageUtil.addWatermark(url,out,watermarkImage);

        }catch (Exception e){
            e.printStackTrace();
        }
      // addWatermark(input, out, watermarkImage);
    }
    public static void addWatermark(URL input, File out, URL watermarkImage) {
        // 读取添加水印的图片
        BufferedImage image = null;
        try {
            image = ImageIO.read(input);
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 获取图片的宽度和高度
        int width = image.getWidth();
        int height = image.getHeight();

        // 创建一个图片缓存对象
        BufferedImage newImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        // 获取图片的画笔
        Graphics2D g = newImage.createGraphics();
        // 将原图片绘制到缓存图片上
        g.drawImage(image, 0, 0, width, height, null);
        // 读取水印图片
        BufferedImage watermark = null;
        try {
            watermark = ImageIO.read(watermarkImage);
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 获取水印图片的宽度和高度
        int wmWidth = 0;
        int wmHeight = 0;
        int x;
        int y;
        if(width>height){
            //横图
            wmWidth =width/2;
            wmHeight = height-50;
            x=width/4;
            y=height/4;
        }else{
            wmWidth =width;
            wmHeight = height/2;
            x=width/4;
            y=height/4;
        }
        // 设置水印图片的透明度
        g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, 0.97f));
        // 绘制水印图片
        g.drawImage(watermark, x, y, wmWidth, wmHeight , null);
        // 释放图形上下文使用的系统资源
        g.dispose();

        // 保存带水印的图片
        try {
            ImageIO.write(newImage, "png", out);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
