package com.yfd.platform.modules.deviceapi;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.yfd.platform.config.HttpServerConfig;
import com.yfd.platform.constant.SystemCode;
import com.yfd.platform.utils.HttpRESTfulUtils;
import com.yfd.platform.utils.SpringContextHolder;
import lombok.extern.slf4j.Slf4j;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *
 * @Date: 2023/5/22 17:01
 * @Description:
 */

@Slf4j
public class CameraUtil {

    public static void main(String[] args) {

    }

    /**********************************
     * 用途说明: 调用sdk设置图片温度
     * 参数说明 requestId
     * 参数说明 objectId
     * 参数说明 filePath
     * 参数说明 manufacturer
     * 参数说明 ip
     * 参数说明 port
     * 参数说明 username
     * 参数说明 password
     * 返回值说明: com.alibaba.fastjson.JSONObject
     ***********************************/
    public static JSONObject callPicAnalyse(String requestId, String objectId, String filePath, String manufacturer,
                                            String ip, short port, String username, String password,
                                            String outsideAngle, String csvFilePath) throws IOException {
        // 获取spring bean 中 HttpServerConfig 类实例
        HttpServerConfig config =
                SpringContextHolder.getBean(HttpServerConfig.class);
        // 获取spring bean 中 HttpRESTfulUtils 类实例
        HttpRESTfulUtils httpUtil =
                SpringContextHolder.getBean(HttpRESTfulUtils.class);
        // 拼接图片路径
        String imgPath = config.getSnapFilePath() + URLDecoder.decode(filePath, "utf-8");
        String temperature = getTemperature(manufacturer, ip, port, username, password, outsideAngle, csvFilePath,
                filePath);
        // 温度字体
        Font font = new Font("宋体", Font.BOLD, 35);
        // 温度字体颜色
        Color color = new Color(255, 255, 255);
        CameraUtil.addWaterMark(imgPath, imgPath, temperature, color, font);
        JSONObject jsonObject = new JSONObject();
        JSONObject jsonObject1 = new JSONObject();
        jsonObject.put("requestId", requestId);
        List<Map<String, Object>> mapList = new ArrayList<>();
        Map<String, Object> map = new HashMap<>();
        map.put("objectId", objectId);
        List<Map<String, Object>> mapList1 = new ArrayList<>();
        Map<String, Object> map1 = new HashMap<>();
        map1.put("type", "infrared");
        map1.put("value", temperature);
        if (StrUtil.isBlank(temperature)) {
            jsonObject1.put("code", "201");
            map1.put("code", "2001");
        } else {
            jsonObject1.put("code", "200");
            map1.put("code", "2000");
            map1.put("conf", temperature);
            String imageurl = String.format("http://%s:%s/snapfile?filename=%s", config.getPatrolIp(),
                    config.getPatrolPort(), filePath);
            if (StrUtil.isNotEmpty(config.getPatrolAppname())) {
                imageurl = String.format("http://%s:%s/%s/snapfile?filename=%s", config.getPatrolIp(),
                        config.getPatrolPort(), config.getPatrolAppname(), filePath);
            }
            map1.put("resImagePath", imageurl);
        }
        map1.put("desc", "红外温度测量");
        cn.hutool.json.JSONObject dataPos = JSONUtil.parseObj(outsideAngle);
        JSONArray pos = dataPos.getJSONArray("pos");
        JSONArray posArray = new JSONArray();
        if (pos.size() == 4 && "rectangle".equals(dataPos.getStr("type"))) {
            // 左下角
            cn.hutool.json.JSONObject ojb1 = pos.getJSONObject(0);
            Integer x1 = ojb1.get("x", Integer.class);
            Integer y1 = ojb1.get("y", Integer.class);
            ojb1.putOpt("x", x1);
            ojb1.putOpt("y", y1);
            // 右上角
            cn.hutool.json.JSONObject ojb2 = pos.getJSONObject(2);
            Integer x2 = ojb2.get("x", Integer.class);
            Integer y2 = ojb2.get("y", Integer.class);
            ojb2.putOpt("x", x2);
            ojb2.putOpt("y", y2);
            posArray.add(ojb1);
            log.info(ojb1.toString());
            posArray.add(ojb2);
            log.info(ojb2.toString());
        }
        if (pos.size() == 1 && "point".equals(dataPos.getStr("type"))) {
            // 点坐标
            cn.hutool.json.JSONObject ojb = pos.getJSONObject(0);
            Integer x1 = ojb.get("x", Integer.class);
            Integer y1 = ojb.get("y", Integer.class);
            ojb.putOpt("x", x1);
            ojb.putOpt("y", y1);
            posArray.add(ojb);
        }
        JSONArray dataArray = new JSONArray();
        JSONObject dataJson = new JSONObject();
        dataJson.put("coors", posArray);
        dataArray.add(dataJson);
        map1.put("pos", dataArray);
        mapList1.add(map1);
        map.put("results", mapList1);
        mapList.add(map);
        jsonObject.put("resultList", mapList);
        String api = "picAnalyseRetNotify";
        if (StrUtil.isNotBlank(config.getPatrolAppname())) {
            api = "riis-system/picAnalyseRetNotify";
        }
        httpUtil.sendHttpPost("json", config.getPatrolIp(), config.getPatrolPort(), "", api,
                jsonObject, null);
        return jsonObject1;
    }

    public static String getTemperature(String manufacturer, String ip, short port, String username, String password,
                                        String outsideAngle, String csvFilePath, String filePath) {

        // 根据生产厂家判断对应方法
        if ("dahua".equals(manufacturer)) {
            //            return getDaHuaTemperature(ip, port, username, password, outsideAngle);
            return "";
        } else if ("yushi".equals(manufacturer)) {
            return "";
        } else if ("haikang".equals(manufacturer) || "Hikvision".equals(manufacturer)) {
            log.info("进入getTemperature");
            return "";
        } else if ("dali".equals(manufacturer)) {
            return getDaLiTemperature(ip, port, username, password, outsideAngle, csvFilePath);
        } else {
            //throw new RuntimeException("暂时没有该生产厂家");
            return "";
        }
    }

    /**********************************
     * 用途说明: 大立热成像温度获取
     * 参数说明 ip 摄像机ip
     * 参数说明 port 摄像机端口
     * 参数说明 username 用户名
     * 参数说明 password 密码
     * 参数说明 region 测温区域
     * 返回值说明: java.lang.String
     ***********************************/
    private static String getDaLiTemperature(String ip, short port, String username, String password,
                                             String outsideAngle, String csvFilePath) {

        // 获取spring bean 中 HttpRESTfulUtils 类实例
        HttpRESTfulUtils httpUtil = SpringContextHolder.getBean(HttpRESTfulUtils.class);
        cn.hutool.json.JSONObject jsonObject = JSONUtil.parseObj(outsideAngle);
        String type = jsonObject.getStr("type");
        JSONArray pos = jsonObject.getJSONArray("pos");
        cn.hutool.json.JSONObject posObject1 = pos.getJSONObject(0);
        File srcImgFile = new File(csvFilePath);
        //文件转化为图片
        Image srcImg = null;
        try {
            srcImg = ImageIO.read(srcImgFile);
        } catch (IOException e) {
            log.error(e.getMessage());;
        }
        if (srcImg == null) {
            return "";
        }
        //获取图片的宽
        int srcImgWidth = srcImg.getWidth(null);
        //获取图片的高
        int srcImgHeight = srcImg.getHeight(null);
        // 获取图片比例
        int width = srcImgWidth / 640;
        int height = srcImgHeight / 480;
        int x1 = Convert.convert(Integer.class, posObject1.getStr("x")) == 0 ? 0 : Convert.convert(Integer.class,
                posObject1.getStr("x")) / width;
        int y1 = Convert.convert(Integer.class, posObject1.getStr("y")) == 0 ? 0 : Convert.convert(Integer.class,
                posObject1.getStr("y")) / height;
        if ("point".equals(type)) {
            // 点测温
            String api = "cgi-bin/system?Module=DMMeasure&Type=Point&Index=0&Enable=On&StartX=" + x1 + "&StartY=" + y1;
            // 设置点测温区域
            JSONObject pointData = httpUtil.sendHttpPostStr(ip, port + "", api, null, null);
            String code = pointData.getString("code");
            if (!SystemCode.SUCCESS_STATUS_CODE.getCode().equals(code)) {
                return null;
            }
            String selectApi = "cgi-bin/system?Module=DMTtl";
            JSONObject tempData = httpUtil.sendHttpGetStr(ip, port + "", selectApi, null);
            String data = tempData.getString("data");
            String[] split = data.split("&");
            for (String dataStr : split) {
                if (!dataStr.startsWith("Point=")) {
                    continue;
                }
                String removePrefix = StrUtil.removePrefix(dataStr, "Point=");
                // 找到第一个 "@" 的位置
                int endIndex = removePrefix.indexOf("@");
                if (endIndex != -1) {
                    // 截取 "Point=" 后面并且第一个 "@" 前面的部分
                    String substring = removePrefix.substring(0, endIndex);
                    String[] split1 = substring.split("\\|");
                    String result = "";
                    if (split1.length == 3) {
                        result = split1[1] + "," + split1[1];
                    }
                    return result;
                } else {
                    return "";
                }
            }
        } else {
            // 框测温
            // 去除左上角和右下角坐标
            cn.hutool.json.JSONObject posObject2 = pos.getJSONObject(2);
            int x2 = Convert.convert(Integer.class, posObject2.getStr("x")) == 0 ? 0 : Convert.convert(Integer.class,
                    posObject2.getStr("x")) / width;
            int y2 = Convert.convert(Integer.class, posObject2.getStr("y")) == 0 ? 0 : Convert.convert(Integer.class,
                    posObject2.getStr("y")) / height;
            String api =
                    "cgi-bin/system?Module=DMMeasure&Type=Area&Index=0&Enable=On&StartX=" + x1 + "&StartY=" + y1 +
                            "&EndX=" + x2 + "&EndY=" + y2;
            // 设置框测温区域
            JSONObject areaData = httpUtil.sendHttpPostStr(ip, port + "", api, null, null);
            String code = areaData.getString("code");
            if (!SystemCode.SUCCESS_STATUS_CODE.getCode().equals(code)) {
                return null;
            }
            String selectApi = "cgi-bin/system?Module=DMTtl";
            JSONObject tempData = httpUtil.sendHttpGetStr(ip, port + "", selectApi, null);
            String data = tempData.getString("data");
            String[] split = data.split("&");
            for (String dataStr : split) {
                if (!dataStr.startsWith("Area=")) {
                    continue;
                }
                String removePrefix = StrUtil.removePrefix(dataStr, "Area=");
                // 找到第一个 "@" 的位置
                int endIndex = removePrefix.indexOf("@");
                if (endIndex != -1) {
                    // 截取 "Point=" 后面并且第一个 "@" 前面的部分
                    String substring = removePrefix.substring(0, endIndex);
                    String[] split1 = substring.split("\\|");
                    String result = "";
                    if (split1.length == 4) {
                        String index0 = split1[1];
                        String[] split2 = index0.split(",");
                        result = split2[0] + "," + split2[1];
                    }
                    return result;
                } else {
                    return "";
                }
            }
        }
        return null;
    }

    public static String getStorageStatus(String manufacturer, String ip, short port, String username,
                                          String password) {

        // 根据生产厂家判断对应方法
        if ("dahua".equals(manufacturer)) {
            //throw new RuntimeException("暂时没有 “大华” SDK");
            return "";
        } else if ("yushi".equals(manufacturer)) {
            //throw new RuntimeException("暂时没有 “宇视” SDK");
            return "";
        } else if ("haikang".equals(manufacturer) || "Hikvision".equals(manufacturer)) {
           log.info("进入getStorageStatus");
            return "";
        } else {
            //throw new RuntimeException("暂时没有该生产厂家");
            return "";
        }
    }

    public static void addWaterMark(String srcImgPath, String tarImgPath, String waterMarkContent,
                                    Color markContentColor,
                                    Font font) {

        try {
            // 读取原图片信息
            File srcImgFile = new File(srcImgPath);//得到文件
            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(markContentColor); //根据图片的背景设置水印颜色
            g.setFont(font);              //设置字体

            String[] split = waterMarkContent.split(",");
            String max = "max:" + split[0] + "°C";
            String min = "min:" + split[1] + "°C";
            int height = srcImgHeight / 5;
            //设置水印的坐标
            int x1 = srcImgWidth - 2 * getWatermarkLength(max, g);
            int x2 = srcImgWidth - 2 * getWatermarkLength(min, g);
            int y1 = srcImgHeight - height * 4;
            int y2 = srcImgHeight - height;
            //            int x = srcImgWidth - 2 * getWatermarkLength(content, g);
            //            int y = srcImgHeight - getWatermarkLength(content, g);
            //画出水印
            //            g.drawString(content, x, y);
            g.drawString(max, x1, y1);
            g.drawString(min, x2, y2);
            g.dispose();
            // 输出图片
            FileOutputStream outImgStream = new FileOutputStream(tarImgPath);
            ImageIO.write(bufImg, "jpg", outImgStream);
            log.info("-------------------添加温度完成-------------------");
            outImgStream.flush();
            outImgStream.close();

        } catch (Exception e) {
            // TODO: handle exception
        }
    }

    public static int getWatermarkLength(String waterMarkContent, Graphics2D g) {
        return g.getFontMetrics(g.getFont()).charsWidth(waterMarkContent.toCharArray(), 0, waterMarkContent.length());
    }

}
