package com.njcn.product.cnzutai.zutai.service.impl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.reflect.TypeToken;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.njcn.common.pojo.exception.BusinessException;

import com.njcn.influx.pojo.dto.StatisticalDataDTO;
import com.njcn.influx.service.CommonService;
import com.njcn.oss.utils.FileStorageUtil;
import com.njcn.product.cnzutai.zutai.pojo.dto.ZuTaiDTO;
import com.njcn.product.cnzutai.zutai.pojo.enums.CsSystemResponseEnum;
import com.njcn.product.cnzutai.zutai.pojo.vo.CsRtDataVO;
import com.njcn.product.cnzutai.zutai.pojo.vo.DataArrayTreeVO;
import com.njcn.product.cnzutai.zutai.service.CsPagePOService;
import com.njcn.product.cnzutai.zutai.service.ILineTargetService;

import lombok.AllArgsConstructor;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 类的介绍：
 *
 * @author xuyang
 * @version 1.0.0
 * @createTime 2023/6/1 10:11
 */
@Service
@AllArgsConstructor
public class LineTargetServiceImpl implements ILineTargetService {



    private final FileStorageUtil fileStorageUtil;

    private final CsPagePOService csPagePOService;

    private final CommonService commonService;


    @Override
    public List<DataArrayTreeVO> getLineTarget(String lineId) {
//        List<String> setList = new ArrayList<>();
//        String devId = csLedgerFeignClient.findDevByLineId(lineId).getData();
//        //1.获取监测点的安装位置
//        List<CsLinePO> lineList = csLineFeignClient.queryLineById(Collections.singletonList(lineId)).getData();
//        if (CollectionUtils.isEmpty(lineList)){
//            return new ArrayList<DataArrayTreeVO>();
//        }
//        CsLinePO line = csLineFeignClient.queryLineById(Collections.singletonList(lineId)).getData().get(0);
//        String code = dicDataFeignClient.getDicDataById(line.getPosition()).getData().getCode();
//        String modelId = null;
//        List<LineTargetVO> dataSetList = new ArrayList<>();
//        //治理监测点
//        if (Objects.equals(code, DicDataEnum.OUTPUT_SIDE.getCode())){
//            modelId = devModelRelationFeignClient.getModelByType(devId,0).getData();
//            dataSetList = dataSetFeignClient.getDataSet(modelId,0).getData();
//        }
//        //电网侧监测点
//        else if (Objects.equals(code, DicDataEnum.GRID_SIDE.getCode())){
//            modelId = devModelRelationFeignClient.getModelByType(devId,1).getData();
//            dataSetList = dataSetFeignClient.getDataSet(modelId,1).getData();
//        }
//        //负载侧监测点
//        else if (Objects.equals(code, DicDataEnum.LOAD_SIDE.getCode())){
//            modelId = devModelRelationFeignClient.getModelByType(devId,1).getData();
//            dataSetList = dataSetFeignClient.getDataSet(modelId,2).getData();
//        }
//        setList = dataSetList.stream().map(LineTargetVO::getId).collect(Collectors.toList());
//        return dataArrayFeignClient.getDataArray(setList).getData();
        return null;
    }

    @Override
    public List<CsRtDataVO> getLineData(String id) {
        List<CsRtDataVO> result = new ArrayList<>();
        String path = csPagePOService.queryById(id).getPath();
        InputStream inputStream = fileStorageUtil.getFileStream(path);
        ZuTaiDTO zuTaiDto = analysisJson(inputStream);

        zuTaiDto.getJson().forEach(item->{
            if (!CollectionUtils.isEmpty(item.getUidNames())){
                for (int i = 0; i < item.getUidNames().size(); i++) {
                    String temp = item.getUidNames().get(i);
                    String targetTag = null;
                    String phasic = null;
                    String dataType = null;
//                    String[] tmepUidName = temp.split(" / ");
//                    if(tmepUidName.length==2){
//                        targetTag = tmepUidName[0];
//                        phasic = "T";
//                        dataType =  tmepUidName[1];
//                    }else if (tmepUidName.length==3){
//                        targetTag = tmepUidName[0];
//                        phasic = tmepUidName[1];
//                        dataType = tmepUidName[2];
//                    }

                    if (CollectionUtils.isEmpty(item.getUid()) || StringUtils.isEmpty(item.getLineId())){
                        throw new BusinessException(CsSystemResponseEnum.BIND_TARGET_ERROR);
                    }
                    List<String> tempUid = item.getUid().get(i);
                    String s = tempUid.get(tempUid.size() - 1);
                    String[] tempTable = s.replace("$", "").split("#");
                    result.add(getLineRtData(item.getId(),item.getLineId(),tempTable[3],tempTable[0],tempTable[1],tempTable[2].toUpperCase(),temp,item.getUnit().get(i)));
                }

            }


        });
        return result;
    }

    /**
     * 解析json文件
     */
    public ZuTaiDTO analysisJson(InputStream inputStream)  {

        ObjectMapper mapper = new ObjectMapper();

        String text = new BufferedReader(
                new InputStreamReader(inputStream, StandardCharsets.UTF_8))
                .lines()
                .collect(Collectors.joining("\n"));


        ZuTaiDTO config = null;
        try {
            config = mapper.readValue(text, ZuTaiDTO.class);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }

        return config;
    }

    /**
     * 通过orm框架获取数据
     * @param id            图元Id
     * @param lineId        监测点Id
     * @param tableName     表名称
     * @param columnName    字段名称
     * @param phasic        相别
     * @param dataType      数据类型
     * @param target        数据名称
     * @return
     */
    public CsRtDataVO getLineRtData(String id,String lineId, String tableName, String columnName, String phasic, String dataType, String target,String uint) {
        CsRtDataVO csRtDataVO = new CsRtDataVO();
        StatisticalDataDTO statisticalDataDTO = commonService.getLineRtData(lineId,tableName,columnName,phasic,dataType);
        if(Objects.isNull(statisticalDataDTO)){
            statisticalDataDTO = new StatisticalDataDTO();
            statisticalDataDTO.setLineId(lineId);
            statisticalDataDTO.setPhaseType(phasic);
            statisticalDataDTO.setValueType(dataType);
            statisticalDataDTO.setValue(3.1415926);
        } else {
            statisticalDataDTO.setValue(BigDecimal.valueOf(statisticalDataDTO.getValue()).setScale(4, RoundingMode.HALF_UP).doubleValue());
        }
        String targetTag = null;
        String targetPhasic = null;
        String targetDataType = null;

        String[] tmepUidName = target.split(" / ");
        if(tmepUidName.length==2){
            targetTag = tmepUidName[0];
            targetDataType = getDataType(tmepUidName[1]) ;
        }else if (tmepUidName.length==3){
            targetTag = tmepUidName[0];
            targetPhasic = tmepUidName[1];
            targetDataType =getDataType(tmepUidName[2]) ;
        } else if (tmepUidName.length==4) {
            targetTag = tmepUidName[1];
            targetPhasic = tmepUidName[2];
            targetDataType =getDataType(tmepUidName[3]) ;
        }
        statisticalDataDTO.setStatisticalName((Objects.isNull(targetPhasic)?"":targetPhasic+"相_")+targetTag+"_"+targetDataType);
        statisticalDataDTO.setTarget(columnName + "$" + phasic + "$" + dataType);
        BeanUtils.copyProperties(statisticalDataDTO,csRtDataVO);
        csRtDataVO.setId(id);
        csRtDataVO.setUnit(uint);
        return csRtDataVO;
    }

    public String getDataType(String statItem){
        String valueTypeName = "";
        switch (statItem) {
            case "max":
                valueTypeName = "最大值";
                break;
            case "min":
                valueTypeName = "最小值";
                break;
            case "avg":
                valueTypeName = "平均值";
                break;
            case "cp95":
                valueTypeName = "cp95值";
                break;
            default:
                break;
        }
        return valueTypeName;
    }
    public static void main(String[] args) {
        ObjectMapper mapper = new ObjectMapper();
        String temp ="{\n" +
                "  \"canvasCfg\": {\n" +
                "    \"width\": 1920,\n" +
                "    \"height\": 1080,\n" +
                "    \"scale\": 1,\n" +
                "    \"color\": \"\",\n" +
                "    \"img\": \"\",\n" +
                "    \"guide\": true,\n" +
                "    \"adsorp\": true,\n" +
                "    \"adsorp_diff\": 5,\n" +
                "    \"transform_origin\": {\n" +
                "      \"x\": 0,\n" +
                "      \"y\": 0\n" +
                "    },\n" +
                "    \"drag_offset\": {\n" +
                "      \"x\": 0,\n" +
                "      \"y\": 0\n" +
                "    }\n" +
                "  },\n" +
                "  \"gridCfg\": {\n" +
                "    \"enabled\": true,\n" +
                "    \"align\": true,\n" +
                "    \"size\": 10\n" +
                "  },\n" +
                "  \"json\": [\n" +
                "    {\n" +
                "      \"id\": \"c53cccb8c65201c192d8c57fbdb4d993-fGe6GgykpF\",\n" +
                "      \"title\": \"传输设备\",\n" +
                "      \"keyId\": \"\",\n" +
                "      \"type\": \"svg\",\n" +
                "      \"binfo\": {\n" +
                "        \"left\": 380,\n" +
                "        \"top\": 120,\n" +
                "        \"width\": 50,\n" +
                "        \"height\": 50,\n" +
                "        \"angle\": 0\n" +
                "      },\n" +
                "      \"resize\": true,\n" +
                "      \"rotate\": true,\n" +
                "      \"lock\": false,\n" +
                "      \"active\": false,\n" +
                "      \"hide\": false,\n" +
                "      \"props\": {\n" +
                "        \"fill\": \"#FF0000\"\n" +
                "      },\n" +
                "      \"tag\": \"c53cccb8c65201c192d8c57fbdb4d993\",\n" +
                "      \"common_animations\": {\n" +
                "        \"val\": \"\",\n" +
                "        \"delay\": \"delay-0s\",\n" +
                "        \"speed\": \"slow\",\n" +
                "        \"repeat\": \"infinite\"\n" +
                "      },\n" +
                "      \"use_proportional_scaling\": true,\n" +
                "      \"events\": [],\n" +
                "      \"lineId\": \"782d0aa0bfbe47b83f54f9b31b2d6c9a\",\n" +
                "      \"lineList\": [\n" +
                "        \"52e34eb68eeb13fa515737048772d204\",\n" +
                "        \"d02b5cc062e6a0e0bcb784c2df6b2e98\",\n" +
                "        \"158445294c3f9b4507b6b19df403e467\",\n" +
                "        \"782d0aa0bfbe47b83f54f9b31b2d6c9a\"\n" +
                "      ],\n" +
                "      \"lineName\": \"无锡供电公司 / 110kV下甸桥变 / PQ-COM_7 / 10kV母线_胜境11C线\",\n" +
                "      \"UID\": [\n" +
                "        [\n" +
                "          \"rms\",\n" +
                "          \"B\",\n" +
                "          \"$rms#B#max#data_v#NO$\"\n" +
                "        ],\n" +
                "        [\n" +
                "          \"rms\",\n" +
                "          \"B\",\n" +
                "          \"$rms#B#min#data_v#NO$\"\n" +
                "        ],\n" +
                "        [\n" +
                "          \"rms\",\n" +
                "          \"B\",\n" +
                "          \"$rms#B#avg#data_v#NO$\"\n" +
                "        ],\n" +
                "        [\n" +
                "          \"rms\",\n" +
                "          \"C\",\n" +
                "          \"$rms#C#max#data_v#NO$\"\n" +
                "        ],\n" +
                "        [\n" +
                "          \"rms\",\n" +
                "          \"C\",\n" +
                "          \"$rms#C#min#data_v#NO$\"\n" +
                "        ],\n" +
                "        [\n" +
                "          \"rms\",\n" +
                "          \"C\",\n" +
                "          \"$rms#C#avg#data_v#NO$\"\n" +
                "        ],\n" +
                "        [\n" +
                "          \"rms\",\n" +
                "          \"C\",\n" +
                "          \"$rms#C#cp95#data_v#NO$\"\n" +
                "        ]\n" +
                "      ],\n" +
                "      \"UIDName\": [\n" +
                "        \"相电压总有效值 / B / max\",\n" +
                "        \"相电压总有效值 / B / min\",\n" +
                "        \"相电压总有效值 / B / avg\",\n" +
                "        \"相电压总有效值 / C / max\",\n" +
                "        \"相电压总有效值 / C / min\",\n" +
                "        \"相电压总有效值 / C / avg\",\n" +
                "        \"相电压总有效值 / C / cp95\"\n" +
                "      ]\n" +
                "    },\n" +
                "    {\n" +
                "      \"id\": \"d09fd211e9908c5fea5cc38c9447e268-mVLhsvkxPK\",\n" +
                "      \"title\": \"断路器\",\n" +
                "      \"keyId\": \"\",\n" +
                "      \"type\": \"svg\",\n" +
                "      \"binfo\": {\n" +
                "        \"left\": 610,\n" +
                "        \"top\": 270,\n" +
                "        \"width\": 50,\n" +
                "        \"height\": 50,\n" +
                "        \"angle\": 0\n" +
                "      },\n" +
                "      \"resize\": true,\n" +
                "      \"rotate\": true,\n" +
                "      \"lock\": false,\n" +
                "      \"active\": false,\n" +
                "      \"hide\": false,\n" +
                "      \"props\": {\n" +
                "        \"fill\": \"#FF0000\"\n" +
                "      },\n" +
                "      \"tag\": \"d09fd211e9908c5fea5cc38c9447e268\",\n" +
                "      \"common_animations\": {\n" +
                "        \"val\": \"\",\n" +
                "        \"delay\": \"delay-0s\",\n" +
                "        \"speed\": \"slow\",\n" +
                "        \"repeat\": \"infinite\"\n" +
                "      },\n" +
                "      \"use_proportional_scaling\": true,\n" +
                "      \"events\": [],\n" +
                "      \"lineId\": \"14a81218e58fa62465d232ff22eba30e\",\n" +
                "      \"lineList\": [\n" +
                "        \"52e34eb68eeb13fa515737048772d204\",\n" +
                "        \"d02b5cc062e6a0e0bcb784c2df6b2e98\",\n" +
                "        \"591f9f6ad50db9e2dfb3f467682f7789\",\n" +
                "        \"14a81218e58fa62465d232ff22eba30e\"\n" +
                "      ],\n" +
                "      \"lineName\": \"无锡供电公司 / 110kV下甸桥变 / PQCOM_3 / 10kV母线_东方12E线\",\n" +
                "      \"UID\": [\n" +
                "        [\n" +
                "          \"p\",\n" +
                "          \"p_2\",\n" +
                "          \"A\",\n" +
                "          \"$p_2#A#max#data_harmpower_p#NO$\"\n" +
                "        ],\n" +
                "        [\n" +
                "          \"p\",\n" +
                "          \"p_2\",\n" +
                "          \"A\",\n" +
                "          \"$p_2#A#min#data_harmpower_p#NO$\"\n" +
                "        ]\n" +
                "        \n" +
                "      ],\n" +
                "      \"UIDName\": [\n" +
                "        \"有功功率 / 2次有功功率 / A / max\",\n" +
                "        \"有功功率 / 2次有功功率 / A / min\"\n" +
                "        \n" +
                "      ]\n" +
                "    },\n" +
                "    {\n" +
                "      \"id\": \"ea37cb9e81e7dfd44babc986c3547a04-oJTFPUPGC3\",\n" +
                "      \"title\": \"电灯\",\n" +
                "      \"keyId\": \"\",\n" +
                "      \"type\": \"svg\",\n" +
                "      \"binfo\": {\n" +
                "        \"left\": 270,\n" +
                "        \"top\": 460,\n" +
                "        \"width\": 50,\n" +
                "        \"height\": 50,\n" +
                "        \"angle\": 0\n" +
                "      },\n" +
                "      \"resize\": true,\n" +
                "      \"rotate\": true,\n" +
                "      \"lock\": false,\n" +
                "      \"active\": false,\n" +
                "      \"hide\": false,\n" +
                "      \"props\": {\n" +
                "        \"fill\": \"#FF0000\"\n" +
                "      },\n" +
                "      \"tag\": \"ea37cb9e81e7dfd44babc986c3547a04\",\n" +
                "      \"common_animations\": {\n" +
                "        \"val\": \"\",\n" +
                "        \"delay\": \"delay-0s\",\n" +
                "        \"speed\": \"slow\",\n" +
                "        \"repeat\": \"infinite\"\n" +
                "      },\n" +
                "      \"use_proportional_scaling\": true,\n" +
                "      \"events\": [],\n" +
                "      \"lineId\": \"14a81218e58fa62465d232ff22eba30e\",\n" +
                "      \"lineList\": [\n" +
                "        \"52e34eb68eeb13fa515737048772d204\",\n" +
                "        \"d02b5cc062e6a0e0bcb784c2df6b2e98\",\n" +
                "        \"591f9f6ad50db9e2dfb3f467682f7789\",\n" +
                "        \"14a81218e58fa62465d232ff22eba30e\"\n" +
                "      ],\n" +
                "      \"lineName\": \"无锡供电公司 / 110kV下甸桥变 / PQCOM_3 / 10kV母线_东方12E线\",\n" +
                "      \"UID\": [\n" +
                "        [\n" +
                "          \"v_neg\",\n" +
                "          \"$v_neg#max#data_v#NO$\"\n" +
                "        ],\n" +
                "        [\n" +
                "          \"v_neg\",\n" +
                "          \"$v_neg#min#data_v#NO$\"\n" +
                "        ],\n" +
                "        [\n" +
                "          \"v_neg\",\n" +
                "          \"$v_neg#cp95#data_v#NO$\"\n" +
                "        ],\n" +
                "        [\n" +
                "          \"v_neg\",\n" +
                "          \"$v_neg#avg#data_v#NO$\"\n" +
                "        ]\n" +
                "      ],\n" +
                "      \"UIDName\": [\n" +
                "        \"电压负序分量 / max\",\n" +
                "        \"电压负序分量 / min\",\n" +
                "        \"电压负序分量 / avg\",\n" +
                "        \"电压负序分量 / cp95\"\n" +
                "      ]\n" +
                "    }\n" +
                "  ]\n" +
                "}";
        ZuTaiDTO config = null;
        try {
            config = mapper.readValue(temp, ZuTaiDTO.class);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }


    }
}



