package com.nmgs.util;

/**
 * 处理水印类
 */
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.*;
import javax.imageio.ImageIO;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.springframework.scheduling.annotation.Async;

@Async
public  class ImageUtils {


    /**
     * 添加水印文字
     * @param imageBase64
     * @param text 水印文字
     * @return
     * @throws Exception
     */
    public static String addImageWaterMark(String imageBase64, String text, String fileName) throws Exception {
       String retStr="";
        Properties props = System.getProperties();
        String os = props.getProperty("os.name").toLowerCase();
        String fileAddress = PathUtil.uploadPath + "/" + PubTools.getCurrentDateYMD();
        ByteArrayInputStream inputStream = null;
        try {
            if (os.startsWith("win")) {
                // fileAddress = PropertiesUtil.getValue("fileAddressWin");
                fileAddress = fileAddress.replace("/", "\\");
            } else {
                //  fileAddress = PropertiesUtil.getValue("fileAddressLinux");
            }
            imageBase64 = imageBase64.replaceAll(" ", "+").replace("\r\n", "");
            byte[] imageBytes = Base64.getDecoder().decode(imageBase64);
            // 构造 BufferedImage 对象
            if (PubTools.isEmpty(imageBytes)) {
                return "-9999";
            }
            inputStream = new ByteArrayInputStream(imageBytes);
            BufferedImage bufferedImage1 = ImageIO.read(inputStream);
            LogUtil.WriteLog_Info("ImageUtils====附件地址urlfileAddress=====" + fileAddress, "FileController");
            if (PubTools.isEmpty(bufferedImage1)) {
                LogUtil.WriteLog_Info("ImageUtils====附件不规范==不走水印处理===", "FileController");
                File fileDir = new File(fileAddress); // 指定上传位置
                if (!fileDir.exists()) {
                    fileDir.mkdirs();
                }
                // 创建文件
                File file = new File(fileAddress, fileName); // 指定上传位置
                //先删除附件
                if (file.exists()) {
                    file.delete();
                }

                // 保存文件
                org.apache.commons.io.FileUtils.writeByteArrayToFile(file, imageBytes);

                //保存到附件服务器上面
                String fileUploadUrl = PropertiesUtil.getValue("fileUploadUrl");
                LogUtil.WriteLog_Info("ImageUtils====附件不规范==不走水印处理======附件上传接口fileUploadUrl=====" + fileUploadUrl, "FileController");
                Map<String, String> map = new HashMap<String, String>();
                JSONArray jsonA = new JSONArray();
                JSONObject mapParam = new JSONObject();
                mapParam.put("fileName", fileName);
                mapParam.put("imageBase64", imageBase64);
                jsonA.add(mapParam);
                map.put("jsonArray", jsonA.toJSONString());
                String s = HttpClientUtil.doPost(fileUploadUrl, map);
                LogUtil.WriteLog_Info("ImageUtils=====附件不规范==不走水印处理===上传结果显示=====" + s, "FileController");
                return imageBase64;
            }
            int w1 = bufferedImage1.getWidth();
            int h1 = bufferedImage1.getHeight();
            // 生成新图片
            BufferedImage destImage = new BufferedImage(w1, h1, BufferedImage.TYPE_INT_RGB);
            Graphics2D graphics2D = destImage.createGraphics();
            destImage = graphics2D.getDeviceConfiguration().createCompatibleImage(w1, h1, Transparency.TRANSLUCENT);
            graphics2D = destImage.createGraphics();
            Color color1Init = graphics2D.getColor();
            //添加白底
            graphics2D.setColor(Color.white);
            graphics2D.fillRect(0, 0, w1, h1);

            //写入字体
            Font font = new Font("宋体", Font.PLAIN,30);
            int markWidth = font.getSize() * text.length();// 字体长度
            if(markWidth >w1){
                markWidth=markWidth/2;
            }
            int markHeight = font.getSize();// 字体高度
           // Color color = new Color(213, 216, 217,128);//写入的颜色
            graphics2D.setColor(Color.gray);
            graphics2D.setFont(font);
            //设置透明度
//        graphics2D.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, 0.5f));
            //设置选择度
            //graphics2D.rotate(10,50,50);
            graphics2D.drawString(text, w1/8, h1/2);
            //合成图片
            //graphics2D.drawImage(backImage, w1/2-50, h1-50-16,null);
            graphics2D.dispose();
            float alpha=0.7f;//透明度，0-1 ，1完全透明
            Color color = new Color(184, 186, 187);//写入的颜色
            Color textColorA = new Color(((float) color.getRed())/255, ((float)color.getGreen())/255, ((float)color.getBlue())/255, alpha);
            int outRGB = textColorA.getRGB();
            //将水印添加到图片中去
            for (int i = 0; i < w1; i++) {
                for (int j = 0; j < h1; j++) {
                    int rgb = destImage .getRGB(i, j);
                    //如果是文字水印的像素点的话
                    if (new Color(rgb).getRGB() != Color.white.getRGB()) {
                        bufferedImage1 .setRGB(i, j, rgb);
                        int bufImgRGB = destImage.getRGB(i, j);
                        if (bufImgRGB>>24==0) {
                            //如果该像素点为全透明，则使用半透明的像素点
                            bufferedImage1 .setRGB(i, j, outRGB);
                        }else {
                            //将原图像素点合成到半透明文字上去
                            Color backColor = new Color(bufImgRGB);
                            float red = textColorA.getRed()*alpha+backColor.getRed()*(1-alpha);
                            float green = textColorA.getGreen()*alpha+backColor.getGreen()*(1-alpha);
                            float blue = textColorA.getBlue()*alpha+backColor.getBlue()*(1-alpha);

                            Color colorCompose = new Color(red/255, green/255, blue/255, 1f);
                            bufferedImage1 .setRGB(i, j, colorCompose.getRGB());
                        }
                    }
                }
            }

            // 将 BufferedImage 转换为 byte 数组
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ImageIO.write(bufferedImage1, "jpg", baos);
            byte[] watermarkedImageBytes = baos.toByteArray();
            retStr = Base64.getEncoder().encodeToString(watermarkedImageBytes);
            // 创建文件，若有则删除在新增
            File file = new File(fileAddress, fileName); // 指定上传位置
            if (file.exists()) {
                file.delete();
            }
            // 保存文件
            org.apache.commons.io.FileUtils.writeByteArrayToFile(file, watermarkedImageBytes);

            //保存到附件服务器上面
            String fileUploadUrl = PropertiesUtil.getValue("fileUploadUrl");
            LogUtil.WriteLog_Info("ImageUtils====附件上传接口fileUploadUrl=====" + fileUploadUrl, "FileController");
            Map<String, String> map = new HashMap<String, String>();
            JSONArray jsonA = new JSONArray();
            JSONObject mapParam = new JSONObject();
            mapParam.put("fileName", fileName);
            mapParam.put("imageBase64", retStr);
            jsonA.add(mapParam);
            map.put("jsonArray", jsonA.toJSONString());
            String[] split = fileUploadUrl.split(",");
            if (split.length > 0) {
                for (String strPath : split) {
                    String s = HttpClientUtil.doPost(strPath, map);
                    LogUtil.WriteLog_Info("ImageUtils====附件上传结果显示END==" + strPath + "===" + s, "FileController");
                }
            }
            return retStr;
        } catch (Exception e) {
            e.printStackTrace();
            return retStr="";
        } finally {
            inputStream.close();
        }
    }

    /**
     * 获取字符长度，一个汉字作为 1 个字符, 一个英文字母作为 0.5 个字符
     *
     * @param text
     * @return 字符长度，如：text="中文",返回 2；text="test",返回 2；text="中文ABC",返回 4.
     */
    public static int getLength(String text) {
        int textLength = text.length();
        int length = textLength;
        for (int i = 0; i < textLength; i++) {
            if (String.valueOf(text.charAt(i)).getBytes().length > 1) {
                length++;
            }
        }
        return (length % 2 == 0) ? length / 2 : length / 2 + 1;
    }

    public static int delFile(String fileNameParam, boolean isXunhuan) {
        Properties props = System.getProperties();
        String os = props.getProperty("os.name").toLowerCase();
        String fileAddressLocal = "";
        String pathAfter = "";
        String fileName = "";
        if (fileNameParam.contains("/")) {
            String[] split = fileNameParam.split("/");
            if (split.length > 1) {
                pathAfter = split[0];
                fileName = split[1];
            }
        }
        if (!PubTools.isNull(pathAfter)) {
            fileAddressLocal = PathUtil.uploadPath + "/" + pathAfter;
        } else {
            fileAddressLocal = PathUtil.uploadPath;
        }
        if (os.startsWith("win")) {
            //fileAddressLocal = PropertiesUtil.getValue("fileAddressWin");
            fileAddressLocal = fileAddressLocal.replace("/", "\\");
        } else {
            // fileAddressLocal = PropertiesUtil.getValue("fileAddressLinux");
        }
        LogUtil.WriteLog_Info("ImageUtils本地文件地址=====fileAddressLocal====" + fileAddressLocal, "FileController");
        File file = new File(fileAddressLocal, fileName); // 指定上传位置
        if (file.exists()) {
            file.delete();
        }
        if (isXunhuan) {
            String fileDelAddress = PropertiesUtil.getValue("fileDelUrl");
            LogUtil.WriteLog_Info("ImageUtil远程删除文件地址=====fileAddressLocal====" + fileDelAddress, "FileController");
            Map<String, String> map = new HashMap<String, String>();
            map.put("fileName", fileNameParam);
            map.put("canDel", "N");
            String[] split = fileDelAddress.split(",");
            if (split.length > 0) {
                for (String strPath : split) {
                    String s = HttpClientUtil.doPost(strPath, map);
                    LogUtil.WriteLog_Info("ImageUtil远程删除文件地址==" + strPath + "===执行结果====" + s, "FileController");
                }
            }
        }
        return 1;
    }

    public static String byteToBase64(byte[] b) {
        try {
            return Base64.getEncoder().encodeToString(b);
        } catch (Exception e) {
            e.printStackTrace();
            LogUtil.WriteLog_Info("ImageUtil===file转base64==执行结果====" + e.getMessage(), "FileUploadController");
            return "";
        }
    }

    /**
     * imgFile 图片本地存储路径
     */
    public static String getImgFileToBase64(String imgFile) {
        //将图片文件转化为字节数组字符串，并对其进行Base64编码处理
        InputStream inputStream = null;
        byte[] buffer = null;
        //读取图片字节数组
        try {
            inputStream = new FileInputStream(imgFile);
            int count = 0;
            while (count == 0) {
                count = inputStream.available();
            }
            buffer = new byte[count];
            inputStream.read(buffer);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (inputStream != null) {
                try {
                    // 关闭inputStream流
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        // 对字节数组Base64编码
        return Base64.getEncoder().encodeToString(buffer);
    }
}