package com.mvc.utils;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.common.BitMatrix;
import com.mvc.netty.dealconstant.PicHeaderInfo;
import com.mvc.netty.dealconstant.ResourcePath;
import com.mvc.netty.dealconstant.ResourceTag;
import com.mvc.service.PackLogMana;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.env.Environment;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Base64;
import java.util.List;

public class ImageUtil {
    // 常见图片文件扩展名列表
    private static final List<String> IMAGE_EXTENSIONS = Arrays.asList("jpg", "jpeg", "png", "gif", "bmp", "webp");

    /**
     * 图片拼接
     *
     * @param path1 图片1路径
     * @param path2 图片2路径
     * @param type  1 横向拼接， 2 纵向拼接
     *              （注意：必须两张图片长宽一致）
     */
    public static void mergeImage(String path1, String path2, int type, String targetFile) throws IOException {
        List<String> list = new ArrayList<>();
        File[] files = new File[2];
        files[0] = new File(path1);
        files[1] = new File(path2);
        mergeImage(files, type, targetFile);
    }

    /**
     * 多张图片合并
     *
     * @param files
     * @param type
     * @param targetFile
     * @throws IOException
     */
    public static void mergeImage(File[] files, int type, String targetFile) {
        try {
            int len = files.length;
            BufferedImage[] images = new BufferedImage[len];
            for (int i = 0; i < len; i++) {
                images[i] = ImageIO.read(files[i]);
            }

            int[][] ImageArrays = new int[len][];

            for (int i = 0; i < len; i++) {
                int width = images[i].getWidth();
                int height = images[i].getHeight();
                ImageArrays[i] = new int[width * height];
                ImageArrays[i] = images[i].getRGB(0, 0, width, height, ImageArrays[i], 0, width);
            }
            int newHeight = 0;
            int newWidth = 0;
            for (int i = 0; i < images.length; i++) {
                // 横向
                if (type == 1) {
                    newHeight = newHeight > images[i].getHeight() ? newHeight : images[i].getHeight();
                    newWidth += images[i].getWidth();
                } else if (type == 2) {// 纵向
                    newWidth = newWidth > images[i].getWidth() ? newWidth : images[i].getWidth();
                    newHeight += images[i].getHeight();
                }
            }
            if (type == 1 && newWidth < 1) {
                return;
            }
            if (type == 2 && newHeight < 1) {
                return;
            }
            // 生成新图片

            BufferedImage imageNew = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_RGB);
            int height_i = 0;
            int width_i = 0;
            for (int i = 0; i < images.length; i++) {
                if (type == 1) {
                    imageNew.setRGB(width_i, 0, images[i].getWidth(), newHeight, ImageArrays[i], 0,
                            images[i].getWidth());
                    width_i += images[i].getWidth();
                } else if (type == 2) {
                    imageNew.setRGB(0, height_i, newWidth, images[i].getHeight(), ImageArrays[i], 0, newWidth);
                    height_i += images[i].getHeight();
                }
            }
            //输出想要的图片
            ImageIO.write(imageNew, targetFile.split("\\.")[1], new File(targetFile));

        } catch (Exception e) {
        }
    }

    /**
     * 是否图片格式
     *
     * @param fileName
     * @return
     */
    public static boolean isImageByExtension(String fileName) {
        if (StringUtils.isEmpty(fileName)) return false;
        int dotIndex = fileName.lastIndexOf(".");
        if (dotIndex == -1 || dotIndex == fileName.length() - 1) {
            return false; // 没有后缀或仅为"."，认为不是图片
        }

        String extension = fileName.substring(dotIndex + 1).toLowerCase();
        return IMAGE_EXTENSIONS.contains(extension);
    }

    /**
     * 旋转图片
     *
     * @param filePath 文件完整路径
     * @param angel    旋转角度
     * @param destPath 输出文件完整路径(含文件名),不传则覆盖原图
     * @return
     */
    public static void rotatingImage(String filePath, int angel, String... destPath) {
        try {
            String extension = FileUtil.getFileExtension(filePath).replaceAll("\\.", "");
            File image = new File(filePath);
            File desFile = destPath == null || destPath.length == 0 ? image : new File(destPath[0]);
            BufferedImage src = ImageIO.read(image);
            BufferedImage des = rotatingImage(src, angel);
            ImageIO.write(des, extension, desFile);

            src = null;
            des = null;
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    /**
     * 对图片进行旋转
     *
     * @param src   被旋转图片
     * @param angel 旋转角度
     * @return 旋转后的图片
     */
    public static BufferedImage rotatingImage(Image src, int angel) {
        int src_width = src.getWidth(null);
        int src_height = src.getHeight(null);
        // 计算旋转后图片的尺寸
        Rectangle rect_des = CalcRotatedSize(new Rectangle(new Dimension(
                src_width, src_height)), angel);
        BufferedImage res = null;
        res = new BufferedImage(rect_des.width, rect_des.height,
                BufferedImage.TYPE_INT_RGB);
        Graphics2D g2 = res.createGraphics();
        // 进行转换
        g2.translate((rect_des.width - src_width) / 2,
                (rect_des.height - src_height) / 2);
        g2.rotate(Math.toRadians(angel), src_width / 2, src_height / 2);

        g2.drawImage(src, null, null);

        return res;
    }

    /**
     * 计算旋转后的图片
     *
     * @param src   被旋转的图片
     * @param angel 旋转角度
     * @return 旋转后的图片
     */
    public static Rectangle CalcRotatedSize(Rectangle src, int angel) {
        // 如果旋转的角度大于90度做相应的转换
        if (angel >= 90) {
            if (angel / 90 % 2 == 1) {
                int temp = src.height;
                src.height = src.width;
                src.width = temp;
            }
            angel = angel % 90;
        }

        double r = Math.sqrt(src.height * src.height + src.width * src.width) / 2;
        double len = 2 * Math.sin(Math.toRadians(angel) / 2) * r;
        double angel_alpha = (Math.PI - Math.toRadians(angel)) / 2;
        double angel_dalta_width = Math.atan((double) src.height / src.width);
        double angel_dalta_height = Math.atan((double) src.width / src.height);

        int len_dalta_width = (int) (len * Math.cos(Math.PI - angel_alpha
                - angel_dalta_width));
        int len_dalta_height = (int) (len * Math.cos(Math.PI - angel_alpha
                - angel_dalta_height));
        int des_width = src.width + len_dalta_width * 2;
        int des_height = src.height + len_dalta_height * 2;
        return new Rectangle(new Dimension(des_width, des_height));
    }

    /**
     * 将网络地址转换为本地地址
     * @param url
     * @return
     */
    public static String convertImageUrlToLocalPath(String url,String tar) {
        if (url.contains("http")) {
            int index = url.indexOf("//");
            if (index > -1) {
                url = url.substring(index + 2);
                index = url.indexOf("/");
                url = url.substring(index);
                url = url.replaceAll(ResourcePath.Image.getPath(), tar);
                return url;
            }
        }
        return url;
    }

    /**
     * 将Base64字符串存储为图片文件
     *
     * @param base64String Base64编码的字符串
     * @param filePath     图片保存路径
     * @throws IOException 如果文件操作发生错误
     */
    public static void saveBase64ImageToFile(String base64String, String filePath) throws IOException {
        // 解码Base64字符串为字节数组
        byte[] imageBytes = Base64.getDecoder().decode(base64String);

        // 将字节数组写入文件
        try (FileOutputStream fos = new FileOutputStream(filePath)) {
            fos.write(imageBytes);
        }
    }

    /**
     * 拼接图片头信息
     * @param imageBytes
     * @param picbianhao
     * @param imgWidth
     * @param imgHeight
     * @return
     */
    public static byte[] prependImageHeader(byte[] imageBytes,String picbianhao,int imgWidth, int imgHeight){
        //图片头编号
        picbianhao = StringUtils.leftPad(picbianhao, 2, '0') ;
        char[] headchararr = PicHeaderInfo.gethearbyindex(picbianhao);
        byte[] headbytearr = NumberUtil.charsToBytes(headchararr);

        byte[] high = NumberUtil.intTo2bytes(imgHeight);
        byte[] width = NumberUtil.intTo2bytes(imgWidth);

        if (picbianhao.equals("aa")) {
            //彩色头更换高度宽度
            headbytearr[561] = high[0];
            headbytearr[562] = high[1];
            headbytearr[563] = width[0];
            headbytearr[564] = width[1];
        } else if (picbianhao.indexOf("a") >= 0 || picbianhao.indexOf("b") >= 0 || picbianhao.indexOf("c") >= 0 || picbianhao.indexOf("d") >= 0 || picbianhao.indexOf("e") >= 0) {
            //灰色头更换高度宽度
            headbytearr[496] = high[0];
            headbytearr[497] = high[1];
            headbytearr[498] = width[0];
            headbytearr[499] = width[1];
        } else {
            //彩色头更换高度宽度
            headbytearr[561] = high[0];
            headbytearr[562] = high[1];
            headbytearr[563] = width[0];
            headbytearr[564] = width[1];
        }

        byte[] result = new byte[imageBytes.length + headbytearr.length];
        System.arraycopy(headbytearr, 0, result, 0, headbytearr.length);
        System.arraycopy(imageBytes, 0, result, headbytearr.length, imageBytes.length);
        return result;
    }

    public static BufferedImage generateQRCode(int qrSize,String text) throws Exception {
        BitMatrix matrix = new MultiFormatWriter().encode(text, BarcodeFormat.QR_CODE, qrSize, qrSize);
        BufferedImage image = new BufferedImage(qrSize, qrSize, BufferedImage.TYPE_INT_RGB);
        for (int x = 0; x < qrSize; x++) {
            for (int y = 0; y < qrSize; y++) {
                image.setRGB(x, y, matrix.get(x, y) ? 0x000000 : 0xFFFFFF); // 黑色和白色
            }
        }
        return image;
    }

    public static void main(String[] args) throws IOException {
        File image = new File("e:/shangchuan/1.jpg");

        BufferedImage src = ImageIO.read(image);
        //顺时针旋转90度
        BufferedImage des1 = rotatingImage(src, 180);
        ImageIO.write(des1, "jpg", new File("e:/shangchuan/1.jpg"));
        //顺时针旋转180度
//        BufferedImage des2 = rotatingImage(src, 180);
//        ImageIO.write(des2, "jpg", new File("c:/180.jpg"));
//        //顺时针旋转270度
//        BufferedImage des3 = rotatingImage(src, 270);
//        ImageIO.write(des3, "jpg", new File("c:/270.jpg"));
    }
}
