package com.njcn.event.file.component;

import cn.hutool.core.img.ImgUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.CharsetUtil;
import com.njcn.common.pojo.exception.BusinessException;
import com.njcn.common.utils.FileUtil;
import com.njcn.echarts.pojo.constant.PicCommonData;
import com.njcn.echarts.util.DrawPicUtil;
import com.njcn.event.file.pojo.bo.WaveDataDetail;
import com.njcn.event.file.pojo.dto.WaveDataDTO;
import com.njcn.event.file.pojo.enums.WaveFileResponseEnum;
import com.njcn.oss.constant.OssPath;
import com.njcn.oss.utils.FileStorageUtil;
import lombok.NoArgsConstructor;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import sun.awt.image.BufferedImageGraphicsConfig;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;
import java.util.List;

/**
 * @author hongawen
 * @version 1.0.0
 * @date 2023年09月21日 09:18
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class WavePicComponent {

    private final DrawPicUtil drawPicUtil;

    private final FileStorageUtil fileStorageUtil;


    /***
     * 绘制瞬时波形图治理
     * @author hongawen
     * @date 2023/9/21 15:32
     * @return String 文件地址
     */
    public String generateInstantImageZl(List<WaveDataDetail> waveDataDetails) {
        String firstPic = null, secondPic = null, thirdPic = null, forthPic = null;
        for (WaveDataDetail waveDataDetail : waveDataDetails) {
            if (waveDataDetail.getChannelName().toUpperCase().startsWith("SU")) {
                firstPic = drawPicUtil.drawWavePic("电压-电网侧", waveDataDetail.getInstantData().getAValue(),
                        waveDataDetail.getInstantData().getBValue(), waveDataDetail.getInstantData().getCValue(),
                        waveDataDetail.getUnit(), waveDataDetail.getInstantData().getMax(), waveDataDetail.getInstantData().getMin(),
                        waveDataDetail.getA(), waveDataDetail.getB(), waveDataDetail.getC(),
                        waveDataDetail.getColors(), waveDataDetail.getIsOpen()
                );
            } else if (waveDataDetail.getChannelName().toUpperCase().startsWith("SI")) {
                thirdPic = drawPicUtil.drawWavePic("电流-电网侧", waveDataDetail.getInstantData().getAValue(),
                        waveDataDetail.getInstantData().getBValue(), waveDataDetail.getInstantData().getCValue(),
                        waveDataDetail.getUnit(), waveDataDetail.getInstantData().getMax(), waveDataDetail.getInstantData().getMin(),
                        waveDataDetail.getA(), waveDataDetail.getB(), waveDataDetail.getC(),
                        waveDataDetail.getColors(), waveDataDetail.getIsOpen()
                );
            } else if (waveDataDetail.getChannelName().toUpperCase().startsWith("LU")) {
                secondPic = drawPicUtil.drawWavePic("电压-负载侧", waveDataDetail.getInstantData().getAValue(),
                        waveDataDetail.getInstantData().getBValue(), waveDataDetail.getInstantData().getCValue(),
                        waveDataDetail.getUnit(), waveDataDetail.getInstantData().getMax(), waveDataDetail.getInstantData().getMin(),
                        waveDataDetail.getA(), waveDataDetail.getB(), waveDataDetail.getC(),
                        waveDataDetail.getColors(), waveDataDetail.getIsOpen()
                );
            } else {
                forthPic = drawPicUtil.drawWavePic("电流-负载侧", waveDataDetail.getInstantData().getAValue(),
                        waveDataDetail.getInstantData().getBValue(), waveDataDetail.getInstantData().getCValue(),
                        waveDataDetail.getUnit(), waveDataDetail.getInstantData().getMax(), waveDataDetail.getInstantData().getMin(),
                        waveDataDetail.getA(), waveDataDetail.getB(), waveDataDetail.getC(),
                        waveDataDetail.getColors(), waveDataDetail.getIsOpen()
                );
            }
        }
        return composeImageZl(firstPic, secondPic, thirdPic, forthPic);
    }

    /***
     * 绘制RMS波形图治理
     * @author hongawen
     * @date 2023/9/21 15:32
     * @return String 文件地址
     */
    public String generateRmsImageZl(List<WaveDataDetail> waveDataDetails) {
        String firstPic = null, secondPic = null, thirdPic = null, forthPic = null;
        for (WaveDataDetail waveDataDetail : waveDataDetails) {
            if (waveDataDetail.getChannelName().toUpperCase().startsWith("SU")) {
                firstPic = drawPicUtil.drawWavePic("电压-电网侧", waveDataDetail.getRmsData().getAValue(),
                        waveDataDetail.getRmsData().getBValue(), waveDataDetail.getRmsData().getCValue(),
                        waveDataDetail.getUnit(), waveDataDetail.getRmsData().getMax(), waveDataDetail.getRmsData().getMin(),
                        waveDataDetail.getA(), waveDataDetail.getB(), waveDataDetail.getC(),
                        waveDataDetail.getColors(), waveDataDetail.getIsOpen()
                );
            } else if (waveDataDetail.getChannelName().toUpperCase().startsWith("SI")) {
                thirdPic = drawPicUtil.drawWavePic("电流-电网侧", waveDataDetail.getRmsData().getAValue(),
                        waveDataDetail.getRmsData().getBValue(), waveDataDetail.getRmsData().getCValue(),
                        waveDataDetail.getUnit(), waveDataDetail.getRmsData().getMax(), waveDataDetail.getRmsData().getMin(),
                        waveDataDetail.getA(), waveDataDetail.getB(), waveDataDetail.getC(),
                        waveDataDetail.getColors(), waveDataDetail.getIsOpen()
                );
            } else if (waveDataDetail.getChannelName().toUpperCase().startsWith("LU")) {
                secondPic = drawPicUtil.drawWavePic("电压-负载侧", waveDataDetail.getRmsData().getAValue(),
                        waveDataDetail.getRmsData().getBValue(), waveDataDetail.getRmsData().getCValue(),
                        waveDataDetail.getUnit(), waveDataDetail.getRmsData().getMax(), waveDataDetail.getRmsData().getMin(),
                        waveDataDetail.getA(), waveDataDetail.getB(), waveDataDetail.getC(),
                        waveDataDetail.getColors(), waveDataDetail.getIsOpen()
                );
            } else {
                forthPic = drawPicUtil.drawWavePic("电流-负载侧", waveDataDetail.getRmsData().getAValue(),
                        waveDataDetail.getRmsData().getBValue(), waveDataDetail.getRmsData().getCValue(),
                        waveDataDetail.getUnit(), waveDataDetail.getRmsData().getMax(), waveDataDetail.getRmsData().getMin(),
                        waveDataDetail.getA(), waveDataDetail.getB(), waveDataDetail.getC(),
                        waveDataDetail.getColors(), waveDataDetail.getIsOpen()
                );
            }
        }
        return composeImageZl(firstPic, secondPic, thirdPic, forthPic);
    }

    /***
     * 合并4个原图
     * @author hongawen
     * @date 2023/9/28 14:45
     * @return String
     */
    private String composeImageZl(String firstPic, String secondPic, String thirdPic, String forthPic) {
        try {
            //第一张图片 base64截取删除前缀data:image/png;base64,
            BufferedImage imageOne = ImgUtil.toBufferedImage(ImgUtil.toImage(firstPic.substring(22)), ImgUtil.IMAGE_TYPE_PNG);
            int width = imageOne.getWidth();
            int height = imageOne.getHeight();
            int[] imageArrayOne = new int[width * height];
            imageArrayOne = imageOne.getRGB(0, 0, width, height, imageArrayOne, 0, width);
            //第二张图片 base64截取删除前缀data:image/png;base64,
            BufferedImage imageTwo = ImgUtil.toBufferedImage(ImgUtil.toImage(secondPic.substring(22)), ImgUtil.IMAGE_TYPE_PNG);
            int[] ImageArrayTwo = new int[width * height];
            ImageArrayTwo = imageTwo.getRGB(0, 0, width, height, ImageArrayTwo, 0, width);
            //第三张图片 base64截取删除前缀data:image/png;base64,
            BufferedImage imageThree = ImgUtil.toBufferedImage(ImgUtil.toImage(thirdPic.substring(22)), ImgUtil.IMAGE_TYPE_PNG);
            int[] ImageArrayThree = new int[width * height];
            ImageArrayThree = imageThree.getRGB(0, 0, width, height, ImageArrayThree, 0, width);
            //第四张图片 base64截取删除前缀data:image/png;base64,
            BufferedImage imageForth = ImgUtil.toBufferedImage(ImgUtil.toImage(forthPic.substring(22)), ImgUtil.IMAGE_TYPE_PNG);
            int[] ImageArrayForth = new int[width * height];
            ImageArrayForth = imageForth.getRGB(0, 0, width, height, ImageArrayForth, 0, width);
            //新图片
            BufferedImage imageNew = new BufferedImage(width, height * 4, BufferedImage.TYPE_INT_RGB);
            BufferedImageGraphicsConfig config = BufferedImageGraphicsConfig.getConfig(imageNew);
            imageNew = config.createCompatibleImage(width, height * 4, Transparency.TRANSLUCENT);
            imageNew.setRGB(0, 0, width, height, imageArrayOne, 0, width);
            imageNew.setRGB(0, height, width, height, ImageArrayTwo, 0, width);
            imageNew.setRGB(0, height * 2, width, height, ImageArrayThree, 0, width);
            imageNew.setRGB(0, height * 3, width, height, ImageArrayForth, 0, width);
            String resultImg = ImgUtil.toBase64(imageNew, ImgUtil.IMAGE_TYPE_PNG);
            byte[] bytes = Base64.getDecoder().decode(resultImg);
            return fileStorageUtil.uploadStream(new ByteArrayInputStream(bytes), OssPath.EVENT_WAVE_PIC, FileUtil.generateFileName("png"));
        } catch (Exception e) {
            throw new BusinessException(WaveFileResponseEnum.COMPOSE_PIC_ERROR);
        }
    }


    /***
     * 绘制瞬时波形图
     * @author hongawen
     * @date 2023/9/21 15:32
     * @return String 文件地址
     */
    public String generateImageShun(WaveDataDTO waveDataDTO, List<WaveDataDetail> waveDataDetails) {
        String picPath = null;
        String time = waveDataDTO.getTime();
        String title = "监测点名称：" + waveDataDTO.getMonitorName() + " 发生时刻：" + time;
        WaveDataDetail waveDataDetail = waveDataDetails.get(0);
        String firstPic = drawPicUtil.drawWavePic(title, waveDataDetail.getInstantData().getAValue(),
                waveDataDetail.getInstantData().getBValue(), waveDataDetail.getInstantData().getCValue(),
                waveDataDetail.getUnit(), waveDataDetail.getInstantData().getMax(), waveDataDetail.getInstantData().getMin(),
                waveDataDetail.getA(), waveDataDetail.getB(), waveDataDetail.getC(),
                waveDataDetail.getColors(), waveDataDetail.getIsOpen()
        );
        String secondPic;
        if (waveDataDetails.size() == 1) {
            //将图片上传到minioss
            if (firstPic.contains(PicCommonData.PNG_PREFIX)) {
                firstPic = firstPic.replace(PicCommonData.PNG_PREFIX, "");
            }
            byte[] bytes = Base64.getDecoder().decode(firstPic);
            picPath = fileStorageUtil.uploadStream(new ByteArrayInputStream(bytes), OssPath.EVENT_WAVE_PIC, FileUtil.generateFileName("png"));
        } else if (waveDataDetails.size() == 2) {
            //绘制第二个电压瞬时波形图
            waveDataDetail = waveDataDetails.get(1);
            secondPic = drawPicUtil.drawWavePic("", waveDataDetail.getInstantData().getAValue(),
                    waveDataDetail.getInstantData().getBValue(), waveDataDetail.getInstantData().getCValue(),
                    waveDataDetail.getUnit(), waveDataDetail.getInstantData().getMax(), waveDataDetail.getInstantData().getMin(),
                    waveDataDetail.getA(), waveDataDetail.getB(), waveDataDetail.getC(),
                    waveDataDetail.getColors(), waveDataDetail.getIsOpen()
            );
            picPath = composeImage(firstPic, secondPic);
        }
        return picPath;
    }

    /***
     * 绘制RMS波形图
     * @author hongawen
     * @date 2023/9/21 15:32
     * @return String 文件地址
     */
    public String generateImageRms(WaveDataDTO waveDataDTO, List<WaveDataDetail> waveDataDetails) {
        String picPath = null;
        String time = waveDataDTO.getTime();
        String title = "监测点名称：" + waveDataDTO.getMonitorName() + " 发生时刻：" + time;
        WaveDataDetail waveDataDetail = waveDataDetails.get(0);
        String firstPic = drawPicUtil.drawWavePic(title, waveDataDetail.getRmsData().getAValue(),
                waveDataDetail.getRmsData().getBValue(), waveDataDetail.getRmsData().getCValue(),
                waveDataDetail.getUnit(), waveDataDetail.getRmsData().getMax(), waveDataDetail.getRmsData().getMin(),
                waveDataDetail.getA(), waveDataDetail.getB(), waveDataDetail.getC(),
                waveDataDetail.getColors(), waveDataDetail.getIsOpen()
        );
        String secondPic;
        if (waveDataDetails.size() == 1) {
            //将图片上传到minioss
            if (firstPic.contains(PicCommonData.PNG_PREFIX)) {
                firstPic = firstPic.replace(PicCommonData.PNG_PREFIX, "");
            }
            byte[] bytes = Base64.getDecoder().decode(firstPic);
            picPath = fileStorageUtil.uploadStream(new ByteArrayInputStream(bytes), OssPath.EVENT_WAVE_PIC, FileUtil.generateFileName("png"));
        } else if (waveDataDetails.size() == 2) {
            //绘制第二个电压瞬时波形图
            waveDataDetail = waveDataDetails.get(1);
            secondPic = drawPicUtil.drawWavePic("", waveDataDetail.getRmsData().getAValue(),
                    waveDataDetail.getRmsData().getBValue(), waveDataDetail.getRmsData().getCValue(),
                    waveDataDetail.getUnit(), waveDataDetail.getRmsData().getMax(), waveDataDetail.getRmsData().getMin(),
                    waveDataDetail.getA(), waveDataDetail.getB(), waveDataDetail.getC(),
                    waveDataDetail.getColors(), waveDataDetail.getIsOpen()
            );
            picPath = composeImage(firstPic, secondPic);
        }
        return picPath;
    }

    /***
     * 合成图片
     * @author hongawen
     * @date 2023/9/21 15:33
     * @param firstPic 第一张图
     * @param secondPic 第二张图
     * @return String
     */
    private String composeImage(String firstPic, String secondPic) {
        try {
            //第一张图片 base64截取删除前缀data:image/png;base64,
            BufferedImage imageOne = ImgUtil.toBufferedImage(ImgUtil.toImage(firstPic.substring(22)), ImgUtil.IMAGE_TYPE_PNG);
            int width = imageOne.getWidth();
            int height = imageOne.getHeight();
            int[] imageArrayOne = new int[width * height];
            imageArrayOne = imageOne.getRGB(0, 0, width, height, imageArrayOne, 0, width);
            //第二张图片 base64截取删除前缀data:image/png;base64,
            BufferedImage imageTwo = ImgUtil.toBufferedImage(ImgUtil.toImage(secondPic.substring(22)), ImgUtil.IMAGE_TYPE_PNG);
            int width2 = imageTwo.getWidth();
            int height2 = imageTwo.getHeight();
            int[] ImageArrayTwo = new int[width2 * height2];
            ImageArrayTwo = imageTwo.getRGB(0, 0, width, height, ImageArrayTwo, 0, width);
            //新图片
            BufferedImage imageNew = new BufferedImage(width, height * 2, BufferedImage.TYPE_INT_RGB);
            BufferedImageGraphicsConfig config = BufferedImageGraphicsConfig.getConfig(imageNew);
            imageNew = config.createCompatibleImage(width, height * 2, Transparency.TRANSLUCENT);
            imageNew.setRGB(0, 0, width, height, imageArrayOne, 0, width);
            imageNew.setRGB(0, height, width, height, ImageArrayTwo, 0, width);
            String resultImg = ImgUtil.toBase64(imageNew, ImgUtil.IMAGE_TYPE_PNG);
            byte[] bytes = Base64.getDecoder().decode(resultImg);
            return fileStorageUtil.uploadStream(new ByteArrayInputStream(bytes), OssPath.EVENT_WAVE_PIC, FileUtil.generateFileName("png"));
        } catch (Exception e) {
            throw new BusinessException(WaveFileResponseEnum.COMPOSE_PIC_ERROR);
        }
    }

    /**
     * app越限指标图
     * @param title
     * @param values
     * @param limitName
     * @param limit
     * @return
     */
    public String generateSteadyTargetImage(String title, Map<String ,List<List<Object>>> values, String limitName, List<List<Object>> limit) {
        String firstPic = drawPicUtil.drawSteadyTargetPic(title,values,limitName,limit);
        if (firstPic.contains(PicCommonData.PNG_PREFIX)) {
            firstPic = firstPic.replace(PicCommonData.PNG_PREFIX, "");
        }
        byte[] bytes = Base64.getDecoder().decode(firstPic);
        return fileStorageUtil.uploadStream(new ByteArrayInputStream(bytes), OssPath.EVENT_WAVE_PIC, FileUtil.generateFileName("png"));
    }
}
