package com.inspect.partrolresult.domain;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.nacos.shaded.com.google.gson.*;
import com.inspect.analysis.domain.AnalyseResItem;
import com.inspect.analysis.domain.AnalyseResPoint;
import com.inspect.analysis.domain.AnalyseResult;
import com.inspect.analysis.service.RetryableRequest;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

@Setter
@Getter
@EqualsAndHashCode(of = "requestId")
@Slf4j
public class AnalyseRequest implements RetryableRequest, Serializable {
    private List<AnalyseReqItem> objectList;
    private String requestHostIp;
    private String requestHostPort;
    private String requestId;
    private String algorithmPath;
    private String taskPatrolId;
    private String sftpHostIp;
    private String sftpHostPort;
    private String sftpUsername;
    private String sftpPassword;
    private boolean isFilter;
    private String[] typeList;
    private String algorithmType;
    private int totalNumber;
    private int retryCount;
    private String requestUrl;
    private String redissonTime;
    private String value;
    private String unit;
    private String valueUnit;
    private String valueType;
    private String coordinatePixel;
    private String drafter;

    public AnalyseRequest() {

    }

    /**
     * 兼容数聚智造接口
     * 新增 imagePathList 对应 imageUrlList
     * 新增 annotations对象 algo.analyse.sgcc/id 对应 taskPatrolId
     * 新增 annotations对象 task.analyse.sgcc/total 对应 totalNumber
     */
    public static String convertJson(boolean isFilter, String originalJson) {
        Gson gson = new GsonBuilder().setPrettyPrinting().create();
        JsonObject root = JsonParser.parseString(originalJson).getAsJsonObject();

        // 1. 创建一个新的根对象，并把原 root 的所有字段都复制过去（除了 objectList）
        JsonObject newRoot = new JsonObject();

        // 遍历 root 的所有 entry，复制除 objectList 外的所有字段
        for (String key : root.keySet()) {
            if (!"objectList".equals(key)) {
                if (key.equals("typeList") && isFilter) {
                    JsonArray typeList = new JsonArray();
                    typeList.add("tx_pb");
                    newRoot.add(key, typeList);
                } else {
                    newRoot.add(key, root.get(key).deepCopy()); // deepCopy 防止引用问题
                }
            }
        }

        // 2. 处理 objectList（这是我们真正需要修改的部分）
        JsonArray originalObjectList = root.getAsJsonArray("objectList");
        JsonArray newObjectList = new JsonArray();

        for (JsonElement elem : originalObjectList) {
            JsonObject obj = elem.getAsJsonObject().deepCopy(); // 复制一份，避免修改原数据

            // 处理 imageUrlList -> imagePathList
            if (obj.has("imageUrlList")) {
                JsonArray imageUrlList = obj.getAsJsonArray("imageUrlList");
                obj.add("imagePathList", imageUrlList.deepCopy());
            }

            if (obj.has("typeList") && isFilter) {
                JsonArray typeList = new JsonArray();
                typeList.add("tx_pb");
                obj.add("typeList", typeList);
            }

            // 添加 annotations
            JsonObject annotations = new JsonObject();
            // 从根对象取值（即使根对象有很多字段，也只用这两个）
            if (root.has("taskPatrolId")) {
                annotations.addProperty("algo.analyse.sgcc/id", root.get("taskPatrolId").getAsString());
            }
            if (root.has("totalNumber")) {
                annotations.addProperty("task.analyse.sgcc/total", root.get("totalNumber").getAsString());
            }
            obj.add("annotations", annotations);

            newObjectList.add(obj);
        }

        // 3. 把处理好的 objectList 放进新根对象
        newRoot.add("objectList", newObjectList);

        // 4. 转成漂亮的 JSON 字符串
        return gson.toJson(newRoot);
    }

    @Override
    public int getRetryCount() {
        return retryCount;
    }

    @Override
    public void setRetryCount(int retryCount) {
        this.retryCount = retryCount;
    }

    public AnalyseRequest clone() {
        return JSONObject.parseObject(JSONObject.toJSONString(this), AnalyseRequest.class);
    }

    public String toErrorResultStr() {
        AnalyseResult analyseResult = new AnalyseResult();
        analyseResult.setRequestId(this.requestId);
        analyseResult.setCompensate(true);
        analyseResult.setFilter(this.isFilter ? "1" : "0");
        analyseResult.setTaskPatrolId(this.getTaskPatrolId());
        List<AnalyseResItem> list = new ArrayList<>();
        analyseResult.setResultsList(list);

        for (AnalyseReqItem analyseReqItem : this.objectList) {
            AnalyseResItem analyseResItem = new AnalyseResItem();
            list.add(analyseResItem);
            analyseResItem.setObjectId(analyseReqItem.getObjectId());
            List<AnalyseResPoint> results = new ArrayList<>();
            analyseResItem.setResults(results);
            for (String type : analyseReqItem.getTypeList()) {
                AnalyseResPoint analyseResPoint = new AnalyseResPoint();
                analyseResPoint.setCode("2000");
                analyseResPoint.setType(type);
                analyseResPoint.setDesc("-");
                analyseResPoint.setResImageUrl(analyseReqItem.getImageUrlList()[0]);
                analyseResPoint.setValue("-1");
                results.add(analyseResPoint);
            }
        }

        return JSONObject.toJSONString(analyseResult);
    }

    public String toInfraredResultStr() {
        AnalyseResult analyseResult = new AnalyseResult();
        analyseResult.setRequestId(this.requestId);
        analyseResult.setCompensate(true);
        analyseResult.setFilter(this.isFilter ? "1" : "0");
        analyseResult.setTaskPatrolId(this.getTaskPatrolId());
        List<AnalyseResItem> list = new ArrayList<>();
        analyseResult.setResultsList(list);

        for (AnalyseReqItem analyseReqItem : this.objectList) {
            AnalyseResItem analyseResItem = new AnalyseResItem();
            list.add(analyseResItem);
            analyseResItem.setObjectId(analyseReqItem.getObjectId());
            List<AnalyseResPoint> results = new ArrayList<>();
            analyseResItem.setResults(results);
            for (String type : analyseReqItem.getTypeList()) {
                AnalyseResPoint analyseResPoint = new AnalyseResPoint();
                analyseResPoint.setCode("2000");
                analyseResPoint.setType(type);
                analyseResPoint.setDesc("-");
                analyseResPoint.setResImageUrl(analyseReqItem.getImageUrlList()[0]);
                analyseResPoint.setValue(this.value);
                results.add(analyseResPoint);
            }
        }

        return JSONObject.toJSONString(analyseResult);
    }

    @Override
    public String toString() {
        String jsonStr = JSONObject.toJSONString(this);
        if ("SJZZ".equals(this.drafter)) {
            log.info("数聚智造请求格式构造中");
            return convertJson(this.isFilter, jsonStr);
        }
        return jsonStr;
    }
}
