package com.yeejoin.amos.boot.module.jxiop.biz.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yeejoin.amos.boot.biz.common.controller.BaseController;
import com.yeejoin.amos.boot.biz.common.utils.DateUtils;
import com.yeejoin.amos.boot.module.jxiop.api.entity.StationBasic;
import com.yeejoin.amos.boot.module.jxiop.api.feign.RiskWarningFeign;
import com.yeejoin.amos.boot.module.jxiop.api.mapper.StationBasicMapper;
import com.yeejoin.amos.boot.module.jxiop.biz.dto.FullViewRecallDataDTO;
import com.yeejoin.amos.boot.module.jxiop.biz.dto.FullViewRecallInfoDTO;
import com.yeejoin.amos.boot.module.jxiop.biz.entity.*;
import com.yeejoin.amos.boot.module.jxiop.biz.mapper2.*;
import com.yeejoin.amos.boot.module.jxiop.biz.service.IPermissionService;
import com.yeejoin.amos.boot.module.jxiop.biz.service.impl.CommonServiceImpl;
import com.yeejoin.amos.boot.module.jxiop.biz.service.impl.IdxBizFanWarningRuleSetServiceImpl;
import com.yeejoin.amos.boot.module.jxiop.biz.service.impl.IdxBizPvWarningRuleSetServiceImpl;
import com.yeejoin.amos.boot.module.jxiop.biz.tdMapper2.FanHealthIndexDayMapper;
import com.yeejoin.amos.boot.module.jxiop.biz.tdMapper2.FanHealthIndexMapper;
import com.yeejoin.amos.boot.module.jxiop.biz.tdMapper2.FanWaringRecordMapper;
import com.yeejoin.amos.boot.module.jxiop.biz.tdengine.FanHealthIndexDay;
import com.yeejoin.amos.boot.module.jxiop.biz.tdmapper.IndicatorDataMapper;
import com.yeejoin.amos.component.feign.model.FeignClientResult;
import com.yeejoin.amos.feign.privilege.Privilege;
import com.yeejoin.amos.feign.privilege.model.CompanyModel;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.typroject.tyboot.core.foundation.enumeration.UserType;
import org.typroject.tyboot.core.restful.doc.TycloudOperation;
import org.typroject.tyboot.core.restful.utils.ResponseHelper;
import org.typroject.tyboot.core.restful.utils.ResponseModel;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.ParseException;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@Api(tags = "智能分析 - 大屏API")
@RequestMapping(value = "/feiqiBigScreenAnalyse")
public class BigScreenAnalyseController extends BaseController {

    @Autowired
    IdxBizFanHealthIndexMapper idxBizFanHealthIndexMapper;

    @Autowired
    IdxBizFanWarningRecordMapper idxBizFanWarningRecordMapper;

    @Autowired
    IdxBizPvHealthLevelMapper idxBizPvHealthLevelMapper;

    @Autowired
    FanWaringRecordMapper fanWaringRecordMapper;

    @Autowired
    StationBasicMapper stationBasicMapper;

    @Autowired
    CommonServiceImpl commonServiceImpl;

    @Autowired
    IdxBizFanHealthLevelMapper idxBizFanHealthLevelMapper;

    @Autowired
    IndicatorDataMapper indicatorDataMapper;

    @Autowired
    RiskWarningFeign riskWarningFeign;
    @Autowired
    IPermissionService permissionService;


    @Autowired
    private IdxBizFanWarningRuleSetServiceImpl idxBizFanWarningRuleSetService;

    @Autowired
    private IdxBizPvWarningRuleSetServiceImpl idxBizPvWarningRuleSetService;

    @TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
    @ApiOperation(httpMethod = "GET", value = "场站设备健康状态指数与趋势 - 仪表盘", notes = "场站设备健康状态指数与趋势 - 仪表盘")
    @GetMapping(value = "/getHealthScoreInfo")
    public ResponseModel<Map<String, Integer>> getHealthScoreInfo(@RequestParam(required = false) String areaCode,
                                                                  @RequestParam(required = false) String stationCode,
                                                                  @RequestParam (required = false) String tableName) {
        HashMap<String, Integer> stringBigDecimalHashMap = new HashMap<>();
        if (CharSequenceUtil.isNotEmpty(stationCode)) {
            StationBasic stationBasic = stationBasicMapper.selectById(stationCode);
            stationCode = stationBasic.getFanGatewayId();
            stringBigDecimalHashMap.put("value", Integer.valueOf(idxBizFanHealthIndexMapper.getHealthScoreInfoByStation(stationCode, tableName).toString().replace(".0", "")));
        return ResponseHelper.buildResponse(stringBigDecimalHashMap);
        }
        stringBigDecimalHashMap.put("value", Integer.valueOf(idxBizFanHealthIndexMapper.getHealthScoreInfo(areaCode, stationCode).toString().replace(".0", "")));
        return ResponseHelper.buildResponse(stringBigDecimalHashMap);
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
    @ApiOperation(httpMethod = "GET", value = "场站设备健康状态指数与趋势 - 折线图", notes = "场站设备健康状态指数与趋势 - 折线图")
    @GetMapping(value = "/getHealthListInfo")
    public ResponseModel<Map<String, Object>> getHealthListInfo(@RequestParam(required = false) String areaCode, @RequestParam(required = false) String stationCode) {
        List<String> gatewayIds = this.getGatewayIds();
        if (StrUtil.isNotEmpty(stationCode)) {
            StationBasic stationBasic = stationBasicMapper.selectById(stationCode);
            stationCode = stationBasic.getFanGatewayId();
        }

        HashMap<String, Object> resultMap = new HashMap<>();
        List<Map<String, Object>> healthListInfo = idxBizFanHealthIndexMapper.getHealthListInfo(areaCode, stationCode, gatewayIds);
        List<String> time = new ArrayList<>();
        List<String> valueList = new ArrayList<>();
        healthListInfo.forEach(item -> {
            time.add(item.get("date").toString());
            valueList.add(item.get("avgHealthIndex").toString().replace(".0", ""));
        });
        List<Map<String, Object>> arrayList = new ArrayList<>();
        HashMap<String, Object> stringStringHashMap = new HashMap<>();
        stringStringHashMap.put("data", valueList);
        arrayList.add(stringStringHashMap);
        resultMap.put("axisData", time);
        resultMap.put("seriesData", arrayList);
        return ResponseHelper.buildResponse(resultMap);
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
    @ApiOperation(httpMethod = "GET", value = "全域各片区设备预警情况(条) ", notes = "全域各片区设备预警情况(条) ")
    @GetMapping(value = "/getAllEquipAlarmInfo")
    public ResponseModel<Map<String, Object>> getAllEquipAlarmInfo(@RequestParam(required = false) String tableName) throws Exception {
        Map<String, Object> resultMap = new HashMap<>();
        List<Map<String, Object>> allEquipAlarmInfo = idxBizFanHealthIndexMapper.getAllEquipAlarmInfo(tableName);
        HashMap<String, Integer> wxMap = new HashMap<>();
        HashMap<String, Integer> zyMap = new HashMap<>();
        HashMap<String, Integer> jgMap = new HashMap<>();
        allEquipAlarmInfo.forEach(item -> {
            if ("危险".equals(item.get("warningName"))) {
                wxMap.put(item.get("area").toString(), Integer.parseInt(item.get("num").toString()));
            } else if ("注意".equals(item.get("warningName"))) {
                zyMap.put(item.get("area").toString(), Integer.parseInt(item.get("num").toString()));
            } else if ("警告".equals(item.get("warningName"))) {
                jgMap.put(item.get("area").toString(), Integer.parseInt(item.get("num").toString()));
            }
        });
        List<Integer> wxList = new ArrayList<>();
        List<Integer> zyList = new ArrayList<>();
        List<Integer> jgList = new ArrayList<>();
        List<String> list = new ArrayList<>();



        FeignClientResult<List<CompanyModel>> listFeignClientResult = Privilege.companyClient.queryAgencyList("AREA");

        List<CompanyModel> companyModels = new ArrayList<>();

        if (!ObjectUtils.isEmpty(listFeignClientResult)) {
            if (listFeignClientResult.getStatus() == 200) {
                companyModels = listFeignClientResult.getResult();
            } else {
                throw new RuntimeException(listFeignClientResult.getMessage());
            }
        }

        List<String> collect = companyModels.stream().map(t -> t.getCompanyName()).collect(Collectors.toList());
        if ("idx_biz_fan_warning_record".equals(tableName)) {
            list = collect;
//            list = Arrays.asList("华中片区", "西北片区", "西南片区", "华南片区", "华东片区", "东北片区", "华北片区");
        } else {
            list = collect;
            Collections.reverse(list);
//            list = Arrays.asList("华北片区", "东北片区", "华东片区", "华南片区", "西南片区", "西北片区", "华中片区");
        }
        list.forEach(item -> {
            wxList.add(wxMap.getOrDefault(item, 0));
            zyList.add(zyMap.getOrDefault(item, 0));
            jgList.add(jgMap.getOrDefault(item, 0));
        });

        HashMap<String, Object> wxMapResult = new HashMap<>();
        wxMapResult.put("data", wxList);
        wxMapResult.put("name", "危险");
        HashMap<String, Object> zyMapResult = new HashMap<>();
        zyMapResult.put("data", zyList);
        zyMapResult.put("name", "注意");
        HashMap<String, Object> jgMapResult = new HashMap<>();
        jgMapResult.put("data", jgList);
        jgMapResult.put("name", "警告");

        List<Map<String, Object>> hashMaps = Arrays.asList(wxMapResult, zyMapResult, jgMapResult);
        resultMap.put("axisData", list);
        resultMap.put("seriesData", hashMaps);
        return ResponseHelper.buildResponse(resultMap);
    }


    @TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
    @ApiOperation(httpMethod = "GET", value = "全域各片区设备健康状态指数 ", notes = "全域各片区设备健康状态指数 ")
    @GetMapping(value = "/getHealthInfoByArea")
    public ResponseModel<Map<String, Object>> getHealthInfoByArea() throws Exception {
        Map<String, Object> resultMap = new HashMap<>();
        List<Map<String, Object>> healthListInfo = idxBizFanHealthIndexMapper.getHealthInfoByArea();
        Map<String, Object> collect = healthListInfo.stream().collect(Collectors.toMap(t -> t.get("area").toString(), t -> t.get("healthIndex")));
//        List<String> list = Arrays.asList("华中片区", "西北片区", "西南片区", "华南片区", "华东片区", "东北片区", "华北片区");

        List<String> list = new ArrayList<>();

        FeignClientResult<List<CompanyModel>> listFeignClientResult = Privilege.companyClient.queryAgencyList("AREA");

        List<CompanyModel> companyModels = new ArrayList<>();

        if (!ObjectUtils.isEmpty(listFeignClientResult)) {
            if (listFeignClientResult.getStatus() == 200) {
                companyModels = listFeignClientResult.getResult();
            } else {
                throw new RuntimeException(listFeignClientResult.getMessage());
            }
        }
        list = companyModels.stream().map(CompanyModel::getCompanyName).collect(Collectors.toList());
        List<Object> seriesData = new ArrayList<>();
        list.forEach(item -> seriesData.add(collect.getOrDefault(item, 100.0)));
        resultMap.put("axisData", list);
        resultMap.put("seriesData", seriesData);
        return ResponseHelper.buildResponse(resultMap);
    }


    @TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
    @ApiOperation(httpMethod = "GET", value = "全域各场站设备实时预警处置信息", notes = "全域各场站设备实时预警处置信息")
    @GetMapping(value = "/getEquipWarningInfoByPage")
    public ResponseModel<IPage<IdxBizFanWarningRecord>> getEquipWarningInfoByPage(@RequestParam(value = "arae", required = false) String arae,
                                                                                  @RequestParam(value = "station", required = false) String station,
                                                                                  @RequestParam(value = "stationType", required = false) String stationType,
                                                                                  @RequestParam(value = "current", required = false) Integer current,
                                                                                  @RequestParam(value = "size", required = false) Integer size,
                                                                                  @RequestParam(value = "warningName", required = false) String warningName,
                                                                                  @RequestParam(value = "stationId", required = false) String stationId,
                                                                                  @RequestParam(value = "startDate", required = false) String startDate,
                                                                                  @RequestParam(value = "endDate", required = false) String endDate) {


        if (StrUtil.isNotEmpty(stationId)) {
            StationBasic stationBasic = stationBasicMapper.selectById(stationId);
            stationId = stationBasic.getFanGatewayId();
        }
        Integer count = idxBizFanWarningRecordMapper.getEquipWarningInfoByPageCount(arae, station, stationType, warningName, stationId, startDate, endDate);
        List<IdxBizFanWarningRecord> idxBizFanWarningRecordIPage = idxBizFanWarningRecordMapper.getEquipWarningInfoByPage(arae, station, stationType, (current - 1) * size, size, warningName, stationId, startDate, endDate);
        Page<IdxBizFanWarningRecord> idxBizFanWarningRecordPage = new Page<>(current, size);
        idxBizFanWarningRecordPage.setRecords(idxBizFanWarningRecordIPage);
        idxBizFanWarningRecordPage.setTotal(count);
        return ResponseHelper.buildResponse(idxBizFanWarningRecordPage);
    }


    @TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
    @ApiOperation(httpMethod = "GET", value = "各场站设备预警情况(条) ", notes = "各场站设备预警情况(条) ")
    @GetMapping(value = "/getAllEquipAlarmInfoByStation")
    public ResponseModel<Map<String, Object>> getAllEquipAlarmInfoByStation() {
        Map<String, Object> resultMap = new HashMap<>();
        List<Map<String, Object>> allEquipAlarmInfo = idxBizFanHealthIndexMapper.getAllEquipAlarmInfoByStation();
        HashMap<String, Integer> wxMap = new HashMap<>();
        HashMap<String, Integer> zyMap = new HashMap<>();
        HashMap<String, Integer> jgMap = new HashMap<>();
        LinkedHashSet<String> list = new LinkedHashSet<>();
        allEquipAlarmInfo.forEach(item -> {
            if ("危险".equals(item.get("warningName"))) {
                wxMap.put(item.get("station").toString(), Integer.parseInt(item.get("num").toString()));
            } else if ("注意".equals(item.get("warningName"))) {
                zyMap.put(item.get("station").toString(), Integer.parseInt(item.get("num").toString()));
            } else if ("警告".equals(item.get("warningName"))) {
                jgMap.put(item.get("station").toString(), Integer.parseInt(item.get("num").toString()));
            }
            list.add(item.get("station").toString());
        });
        List<Integer> wxList = new ArrayList<>();
        List<Integer> zyList = new ArrayList<>();
        List<Integer> jgList = new ArrayList<>();
//        List<StationBasic> stationBasics = stationBasicMapper.selectList(null);
//        List<String> list = stationBasics.stream().map(StationBasic::getStationName).collect(Collectors.toList());
        list.forEach(item -> {
            wxList.add(wxMap.getOrDefault(item, 0));
            zyList.add(zyMap.getOrDefault(item, 0));
            jgList.add(jgMap.getOrDefault(item, 0));
        });

        HashMap<String, Object> wxMapResult = new HashMap<>();
        wxMapResult.put("data", wxList);
        wxMapResult.put("name", "危险");
        HashMap<String, Object> zyMapResult = new HashMap<>();
        zyMapResult.put("data", zyList);
        zyMapResult.put("name", "注意");
        HashMap<String, Object> jgMapResult = new HashMap<>();
        jgMapResult.put("data", jgList);
        jgMapResult.put("name", "警告");

        List<Map<String, Object>> hashMaps = Arrays.asList(wxMapResult, zyMapResult, jgMapResult);
        resultMap.put("axisData", list);
        resultMap.put("seriesData", hashMaps);
        return ResponseHelper.buildResponse(resultMap);
    }


    @TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
    @ApiOperation(httpMethod = "GET", value = "各场站健康状态指数 ", notes = "各场站健康状态指数 ")
    @GetMapping(value = "/getHealthInfoByStation")
    public ResponseModel<Map<String, Object>> getHealthInfoByArea(@RequestParam(required = false) String areaCode) {
        Map<String, Object> resultMap = new HashMap<>();
        List<Map<String, Object>> healthListInfo = idxBizFanHealthIndexMapper.getHealthInfoByStation(areaCode);
//        Map<String, BigDecimal> collect = healthListInfo.stream().collect(Collectors.toMap(t -> t.get("station").toString(), t -> new BigDecimal(t.get("healthIndex").toString())));
//        List<StationBasic> stationBasics = stationBasicMapper.selectList(new LambdaQueryWrapper<StationBasic>().like(StationBasic::getAreaName, areaCode));
//        List<String> list = stationBasics.stream().map(StationBasic::getStationName).collect(Collectors.toList());
//        List<Object> seriesData = new ArrayList<>();
//        list.forEach(item -> seriesData.add(collect.getOrDefault(item, new BigDecimal("100"))));
        List<String> list = new ArrayList<>();
        List<Object> seriesData = new ArrayList<>();
        healthListInfo.forEach(item -> {
            list.add(item.get("station").toString());
            seriesData.add(item.get("healthIndex").toString().replace(".0", ""));
        });
        resultMap.put("axisData", list);
        resultMap.put("seriesData", seriesData);
        return ResponseHelper.buildResponse(resultMap);
    }



    @TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
    @ApiOperation(value = "场站预警信息统计图 - 雷达图", httpMethod = "GET")
    @GetMapping("/equipWarningRadarMap")
    public ResponseModel<Map<String, Object>> assessIndexRadarMap(@RequestParam(required = false, value = "stationCode") String stationCode) {
        if (StrUtil.isNotEmpty(stationCode)) {
            StationBasic stationBasic = stationBasicMapper.selectById(stationCode);
            stationCode = stationBasic.getFanGatewayId();
        }
        List<Map<String, Object>> list = idxBizFanHealthIndexMapper.equipWarningRadarMap(stationCode);
        Map<String, Integer> warningNumMap = list.stream().collect(Collectors.toMap(t -> t.get("warningName").toString(), t -> Integer.parseInt(t.get("num").toString())));
        List<String> warningList = Arrays.asList("危险", "注意", "警告");
        List<Integer> data = new ArrayList<>();

        List<List<Integer>> resultData = new ArrayList<>();

        List<Map<String, Object>> resultList = new ArrayList<>();
        warningList.forEach(item -> {
            HashMap<String, Object> map = new HashMap<>();
            map.put("text", item);
            resultList.add(map);
            data.add(warningNumMap.getOrDefault(item, 0));
        });
        resultData.add(data);

        HashMap<String, Object> resultMap = new HashMap<>();
        resultMap.put("radar", resultList);
        resultMap.put("array", resultData);
        return ResponseHelper.buildResponse(resultMap);

//        HashMap<String, Object> resultMap = new HashMap<>();
//        List<String> data = new ArrayList<>();
//        list.forEach(item -> {
//            HashMap<String, Object> map = new HashMap<>();
//            map.put("text", item.get("warningName"));
//            resultList.add(map);
//            data.add(item.get("num").toString());
//        });
//
    }


    @TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
    @ApiOperation(httpMethod = "GET", value = "片区设备预警统计分析 - 右下角柱状图 ", notes = "片区设备预警统计分析 - 右下角柱状图  ")
    @GetMapping(value = "/getAllEquipAlarmInfoAnalysis")
    public ResponseModel<Map<String, Object>> getAllEquipAlarmInfoAnalysis(@RequestParam(required = false) String stationType,
                                                                           @RequestParam(required = false) String areaCode) {
        Map<String, Object> resultMap = new HashMap<>();
        List<Map<String, Object>> allEquipAlarmInfo = new ArrayList<>();
        if (CharSequenceUtil.isNotEmpty(stationType)) {

            if ("fan".equals(stationType)) {
                allEquipAlarmInfo = idxBizFanHealthIndexMapper.getAllEquipAlarmInfoAnalysisByStationType("idx_biz_fan_warning_record", areaCode, "风电");
            } else if ("pv".equals(stationType)) {
                allEquipAlarmInfo = idxBizFanHealthIndexMapper.getAllEquipAlarmInfoAnalysisByStationType("idx_biz_pv_warning_record", areaCode, "光伏");
            }
        } else {
            allEquipAlarmInfo = idxBizFanHealthIndexMapper.getAllEquipAlarmInfoAnalysisByArea(areaCode);
        }
        HashMap<String, Integer> wxMap = new HashMap<>();
        HashMap<String, Integer> zyMap = new HashMap<>();
        HashMap<String, Integer> jgMap = new HashMap<>();
        allEquipAlarmInfo.forEach(item -> {
            if ("危险".equals(item.get("warningName"))) {
                wxMap.put(item.get("pointName").toString(), Integer.parseInt(item.get("num").toString()));
            } else if ("注意".equals(item.get("warningName"))) {
                zyMap.put(item.get("pointName").toString(), Integer.parseInt(item.get("num").toString()));
            } else if ("警告".equals(item.get("warningName"))) {
                jgMap.put(item.get("pointName").toString(), Integer.parseInt(item.get("num").toString()));
            }
        });
        List<Integer> wxList = new ArrayList<>();
        List<Integer> zyList = new ArrayList<>();
        List<Integer> jgList = new ArrayList<>();

        List<String> list = allEquipAlarmInfo.stream().map(t -> t.get("pointName").toString()).distinct().collect(Collectors.toList());

        list.forEach(item -> {
            wxList.add(wxMap.getOrDefault(item, 0));
            zyList.add(zyMap.getOrDefault(item, 0));
            jgList.add(jgMap.getOrDefault(item, 0));
        });

        HashMap<String, Object> wxMapResult = new HashMap<>();
        wxMapResult.put("data", wxList);
        wxMapResult.put("name", "危险");
        HashMap<String, Object> zyMapResult = new HashMap<>();
        zyMapResult.put("data", zyList);
        zyMapResult.put("name", "注意");
        HashMap<String, Object> jgMapResult = new HashMap<>();
        jgMapResult.put("data", jgList);
        jgMapResult.put("name", "警告");

        List<Map<String, Object>> hashMaps = Arrays.asList(wxMapResult, zyMapResult, jgMapResult);
        resultMap.put("axisData", list);
        resultMap.put("seriesData", hashMaps);
        return ResponseHelper.buildResponse(resultMap);
    }



    @TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "风站 左侧风机信息列表")
    @GetMapping("/getFanInfoByPage")
    public ResponseModel<Page<Map<String, Object>>> getFanInfoByPage(@RequestParam(value = "stationId", required = false) String stationId) {
        StationBasic stationBasic = stationBasicMapper.selectById(stationId);
        List<Map<String, Object>> equipmentList = idxBizFanHealthIndexMapper.getFanInfoByPage(stationBasic.getFanGatewayId(),stationBasic.getBoosterGatewayId());

        List<Map<String, Object>> healthInfoList = idxBizFanHealthIndexMapper.getFanHealthInfoList(stationBasic.getFanGatewayId(),stationBasic.getBoosterGatewayId());
        Map<Object, Double> equipmentHealthIndexMap = healthInfoList.stream().collect(Collectors.toMap(t -> t.get("equipmentName"), t -> Double.parseDouble(t.get("avgHealthIndex").toString())));

        equipmentList.forEach(item -> {
            Double equipmentHealthScore = equipmentHealthIndexMap.getOrDefault(item.get("equipmentName"), 100.0);
            if (100.0 == equipmentHealthScore) {
                item.put("warningName", "安全");
            } else {
                LambdaQueryWrapper<IdxBizFanHealthLevel> query = new LambdaQueryWrapper<>();
                query.eq(IdxBizFanHealthLevel::getAnalysisObjType, "设备");
                query.eq(IdxBizFanHealthLevel::getStatus, item.get("station"));
                query.lt(IdxBizFanHealthLevel::getGroupLowerLimit, equipmentHealthScore);
                query.ge(IdxBizFanHealthLevel::getGroupUpperLimit, equipmentHealthScore);
                IdxBizFanHealthLevel idxBizFanHealthLevel = idxBizFanHealthLevelMapper.selectOne(query);
                item.put("warningName", idxBizFanHealthLevel.getHealthLevel());
            }
            item.put("healthIndex", equipmentHealthScore);
//            String equipmentName = CharSequenceUtil.replace(item.get("equipmentName").toString(), "集电Ⅳ线#", "");
//            String replace = CharSequenceUtil.replace(equipmentName, "集电Ⅲ线#", "");
//            String replace1 = CharSequenceUtil.replace(replace, "集电Ⅱ线#", "");
//            String replace2 = CharSequenceUtil.replace(replace1, "集电Ⅰ线#", "");
//            String replace3 = CharSequenceUtil.replace(replace2, "风机", "");

            String equipmentName = item.get("equipmentName").toString();
            String str1 = equipmentName.substring(0, equipmentName.indexOf("#"));
            String str2 = equipmentName.substring(str1.length()+1, equipmentName.length());
            String str3 = CharSequenceUtil.replace(str2, "风机", "");

            item.put("equipmentNameSimple", str3);
        });

        Page<Map<String, Object>> mapPage = new Page<>();
        mapPage.setSize(equipmentList.size());
        mapPage.setTotal(equipmentList.size());
        mapPage.setCurrent(1);
        mapPage.setRecords(equipmentList);
        return ResponseHelper.buildResponse(mapPage);
    }




    @TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "风站 风机子系统状态指数  柱状图")
    @GetMapping("/getSubSystemInfo")
    public ResponseModel<Map<String, Object>> getSubSystemInfo(@RequestParam(value = "equipmentName", required = false) String equipmentName,
                                                               @RequestParam(value = "stationId", required = false) String stationId) {

        StationBasic stationBasic = stationBasicMapper.selectById(stationId);
        Map<String, Object> resultMap = new HashMap<>();
        List<Map<String, Object>> healthListInfo = idxBizFanHealthIndexMapper.getSubSystemInfo(equipmentName, stationBasic.getFanGatewayId(),stationBasic.getBoosterGatewayId());
        Map<Object, Integer> equipmentHealthIndexMap = healthListInfo.stream().collect(Collectors.toMap(t -> t.get("subSystem"), t -> Integer.valueOf(t.get("healthIndex").toString().replace(".0", ""))));

        List<Object> seriesData = new ArrayList<>();
        List<Object> axisData = new ArrayList<>();

        List<Map<String, Object>> equipmentList = idxBizFanHealthIndexMapper.getSumSystemListByEquipment(stationBasic.getFanGatewayId(), equipmentName,stationBasic.getBoosterGatewayId());
        equipmentList.forEach(item -> {
            Integer equipmentHealthScore = equipmentHealthIndexMap.getOrDefault(item.get("subSystem"), 100);
            seriesData.add(equipmentHealthScore);
            axisData.add(item.get("subSystem"));
        });
        resultMap.put("axisData", axisData);
        resultMap.put("seriesData", seriesData);
        return ResponseHelper.buildResponse(resultMap);
    }


@Autowired
private FanHealthIndexMapper fanHealthIndexMapper;
    @TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "该子系统各指标预警 - 风站中间 下方列表")
    @GetMapping("/getSubSystemPointInfo")
    public ResponseModel<Page<Map<String, Object>>> getSubSystemPointInfo(
            @RequestParam(value = "subSystem", required = false) String subSystem,
            @RequestParam(value = "stationId", required = false) String stationId,
            @RequestParam(value = "equipmentName", required = false) String equipmentName) throws UnsupportedEncodingException {
        subSystem = java.net.URLDecoder.decode(subSystem, "UTF-8");
        StationBasic stationBasic = stationBasicMapper.selectById(stationId);
        equipmentName = StrUtil.isNotEmpty(equipmentName) ? "%" + equipmentName + "风机%" : equipmentName;
//        List<Map<String, Object>> healthListInfo = idxBizFanHealthIndexMapper.getHealthInfoBySubSystem(subSystem, stationBasic.getFanGatewayId());
        List<Map<String, Object>> healthListInfo = fanHealthIndexMapper.getWarningInfoBySubSystemTd(subSystem,
                stationBasic.getFanGatewayId(), equipmentName);
        Map<Object, String> equipmentHealthIndexMap = healthListInfo.stream()
                .collect(Collectors.toMap(t -> t.get("pointname"), t -> t.get("warningname").toString()));
        List<Map<String, Object>> pointNameList = idxBizFanHealthIndexMapper
                .getPointNameListBySumSystem(stationBasic.getFanGatewayId(), subSystem, equipmentName,stationBasic.getBoosterGatewayId());
        pointNameList.forEach(item -> {
            String warningName = equipmentHealthIndexMap.getOrDefault(item.get("pointName"), "安全");
            int sort = 4;
            item.put("warningName", warningName);
            item.put("status", warningName);
            if ("注意".equals(warningName)) {
                sort = 3;
            } else if ("警告".equals(warningName)) {
                sort = 2;
            } else if ("危险".equals(warningName)) {
                sort = 1;
            }
            item.put("sort", sort);
        });
        pointNameList.sort(Comparator.comparing(o -> o.get("sort").toString()));
        Page<Map<String, Object>> mapPage = new Page<>();
        mapPage.setSize(pointNameList.size());
        mapPage.setTotal(pointNameList.size());
        mapPage.setCurrent(1);
        mapPage.setRecords(pointNameList);
        return ResponseHelper.buildResponse(mapPage);
    }





    @TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "光伏 左侧风机信息列表")
    @GetMapping("/getPvInfoByPage")
    public ResponseModel<Page<Map<String, Object>>> getPvInfoByPage(@RequestParam(value = "stationId", required = false) String stationId) {
        StationBasic stationBasic = stationBasicMapper.selectById(stationId);
        List<Map<String, Object>> equipmentList = idxBizFanHealthIndexMapper.getPvInfoByPage(stationBasic.getFanGatewayId(),stationBasic.getBoosterGatewayId());

        List<Map<String, Object>> healthInfoList = idxBizFanHealthIndexMapper.getPvHealthInfoList(stationBasic.getFanGatewayId(),stationBasic.getBoosterGatewayId());
        Map<Object, Double> equipmentHealthIndexMap = healthInfoList.stream().collect(Collectors.toMap(t -> t.get("subarray"), t -> Double.parseDouble(t.get("avgHealthIndex").toString())));

        equipmentList.forEach(item -> {
            Double equipmentHealthScore = equipmentHealthIndexMap.getOrDefault(item.get("subarray"), 100.0);
            if (100.0 == equipmentHealthScore) {
                item.put("warningName", "安全");
            } else {
                LambdaQueryWrapper<IdxBizPvHealthLevel> query = new LambdaQueryWrapper<>();
                query.eq(IdxBizPvHealthLevel::getAnalysisObjType, "设备");
                query.eq(IdxBizPvHealthLevel::getStatus, item.get("station").toString());
                query.lt(IdxBizPvHealthLevel::getGroupLowerLimit, equipmentHealthScore);
                query.ge(IdxBizPvHealthLevel::getGroupUpperLimit, equipmentHealthScore);
                IdxBizPvHealthLevel idxBizPvHealthLevel = idxBizPvHealthLevelMapper.selectOne(query);
                item.put("warningName", idxBizPvHealthLevel.getHealthLevel());
            }
            item.put("healthIndex", equipmentHealthScore);
            String subarray = CharSequenceUtil.replace(item.get("subarray").toString(), "#", "");
            item.put("subarray", subarray);
        });

        Page<Map<String, Object>> mapPage = new Page<>();
        mapPage.setSize(equipmentList.size());
        mapPage.setTotal(equipmentList.size());
        mapPage.setCurrent(1);
        mapPage.setRecords(equipmentList);
        return ResponseHelper.buildResponse(mapPage);
    }




    @TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "光伏 子阵下各设备状态指数  柱状图")
    @GetMapping("/getPvSubSystemInfo")
    public ResponseModel<Map<String, Object>> getPvSubSystemInfo(@RequestParam(value = "subarray", required = false) String subarray,
                                                                 @RequestParam(value = "stationId", required = false) String stationId) {

        StationBasic stationBasic = stationBasicMapper.selectById(stationId);
        Map<String, Object> resultMap = new HashMap<>();
        List<Map<String, Object>> healthListInfo = idxBizFanHealthIndexMapper.getPvSubSystemInfo(subarray, stationBasic.getFanGatewayId(),stationBasic.getBoosterGatewayId());
        Map<Object, Object> equipmentHealthIndexMap = healthListInfo.stream().collect(Collectors.toMap(t -> t.get("equipmentName"), t -> t.get("avgHealthIndex").toString().replace(".0", "")));

        List<Object> seriesData = new ArrayList<>();
        List<Object> axisData = new ArrayList<>();

        List<Map<String, Object>> equipmentList = idxBizFanHealthIndexMapper.getPvSumSystemListByEquipment(stationBasic.getFanGatewayId(), subarray,stationBasic.getBoosterGatewayId());
        equipmentList.forEach(item -> {
            Object equipmentHealthScore = equipmentHealthIndexMap.getOrDefault(item.get("equipmentName"), 100);
            seriesData.add(equipmentHealthScore);
            axisData.add(item.get("equipmentName"));
        });
        resultMap.put("axisData", axisData);
        resultMap.put("seriesData", seriesData);
        return ResponseHelper.buildResponse(resultMap);
    }

    @TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "光伏 该装备下各指标预警 - 风站中间 下方列表")
    @GetMapping("/getPvSubSystemPointInfo")
    public ResponseModel<Page<Map<String, Object>>> getPvSubSystemPointInfo(@RequestParam(value = "equipmentName", required = false) String equipmentName,
                                                                            @RequestParam(value = "stationId", required = false) String stationId) {

        StationBasic stationBasic = stationBasicMapper.selectById(stationId);
        List<Map<String, Object>> healthListInfo = idxBizFanHealthIndexMapper.getPvHealthInfoBySubSystem(equipmentName, stationBasic.getFanGatewayId(),stationBasic.getBoosterGatewayId());

        Map<Object, Double> equipmentHealthIndexMap = healthListInfo.stream().collect(Collectors.toMap(t -> t.get("pointName"), t -> Double.parseDouble(t.get("healthIndex").toString())));

        List<Map<String, Object>> pointNameList = idxBizFanHealthIndexMapper.getPvPointNameListBySumSystem(stationBasic.getFanGatewayId(), equipmentName,stationBasic.getBoosterGatewayId());

        pointNameList.forEach(item -> {
            Double equipmentHealthScore = equipmentHealthIndexMap.getOrDefault(item.get("pointName"), 100.0);
            if (100.0 == equipmentHealthScore) {
                item.put("warningName", "安全");
                item.put("status", "安全");
            } else {
                LambdaQueryWrapper<IdxBizFanHealthLevel> query = new LambdaQueryWrapper<>();
                query.eq(IdxBizFanHealthLevel::getAnalysisObjType, "设备");
                query.eq(IdxBizFanHealthLevel::getStatus, stationBasic.getStationName());
                query.le(IdxBizFanHealthLevel::getGroupLowerLimit, equipmentHealthScore);
                query.ge(IdxBizFanHealthLevel::getGroupUpperLimit, equipmentHealthScore);
                IdxBizFanHealthLevel idxBizFanHealthLevel = idxBizFanHealthLevelMapper.selectOne(query);
                if (ObjectUtils.isEmpty(idxBizFanHealthLevel)) {
                    item.put("warningName", "安全");
                    item.put("status", "安全");
                } else {
                    item.put("warningName", idxBizFanHealthLevel.getHealthLevel());
                    item.put("status", idxBizFanHealthLevel.getHealthLevel());
                }
            }
            int sort = 4;
            if ("注意".equals(item.get("warningName"))) {
                sort = 3;
            } else if ("警告".equals(item.get("warningName"))) {
                sort = 2;
            } else if ("危险".equals(item.get("warningName"))) {
                sort = 1;
            }
            item.put("sort", sort);
            item.put("healthIndex", equipmentHealthScore);
        });
        pointNameList.sort(Comparator.comparing(o -> o.get("sort").toString()));
        Page<Map<String, Object>> mapPage = new Page<>();
        mapPage.setSize(pointNameList.size());
        mapPage.setTotal(pointNameList.size());
        mapPage.setCurrent(1);
        mapPage.setRecords(pointNameList);

        return ResponseHelper.buildResponse(mapPage);
    }




@Autowired
private FanHealthIndexDayMapper fanHealthIndexDayMapper;
    @TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "风站/光伏 右下实时趋势")
    @GetMapping("/getTrendInfoByAddress")
    public ResponseModel<Map<String, Object>> getTrendInfoByAddress(@RequestParam(value = "indexAddress", required = false) String indexAddress,
                                                                    @RequestParam(value = "stationId", required = false) String stationId) {

        StationBasic stationBasic = stationBasicMapper.selectById(stationId);
        Date currentDayStartTime = DateUtils.getCurrentDayStartTime(DateUtils.dateAddDays(new Date(), - 15));
        Date currentDayEndTime = DateUtils.getCurrentDayEndTime(new Date());
        String startTime = DateUtils.convertDateToString(currentDayStartTime, DateUtils.DATE_TIME_PATTERN);
        String endTime = DateUtils.convertDateToString(currentDayEndTime, DateUtils.DATE_TIME_PATTERN);

        List<FanHealthIndexDay> list = new ArrayList<>();
        LambdaQueryWrapper<FanHealthIndexDay> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(FanHealthIndexDay::getIndexAddress, indexAddress);
        lambdaQueryWrapper.eq(FanHealthIndexDay::getGatewayId, stationBasic.getFanGatewayId());
        lambdaQueryWrapper.eq(FanHealthIndexDay::getAnalysisObjType, "测点");
        lambdaQueryWrapper.le(FanHealthIndexDay::getRecDate, endTime);
        lambdaQueryWrapper.ge(FanHealthIndexDay::getRecDate, startTime);

        List<FanHealthIndexDay> fanHealthIndexDayList = fanHealthIndexDayMapper.selectList(lambdaQueryWrapper);
//        List<IndicatorData> indicatorData = indicatorDataMapper.selectDataByAddressAndtime(indexAddress, startTime, endTime, stationBasic.getFanGatewayId());

        HashMap<String, Object> resultMap = new HashMap<>();
        List<String> time = new ArrayList<>();
        List<Object> valueList = new ArrayList<>();
        fanHealthIndexDayList.forEach(item -> {
            time.add(item.getRecDate());
            valueList.add(item.getHealthIndex());
        });
        List<Map<String, Object>> arrayList = new ArrayList<>();
        HashMap<String, Object> stringStringHashMap = new HashMap<>();
        stringStringHashMap.put("data", valueList);
        arrayList.add(stringStringHashMap);
        resultMap.put("axisData", time);
        resultMap.put("seriesData", arrayList);

        return ResponseHelper.buildResponse(resultMap);
    }


    @TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "根据测点ID查询测点名称")
    @GetMapping("/getMapStringByString")
    public ResponseModel<Map<String, Object>> getMapStringByString(@RequestParam(value = "indexAddress", required = false) String indexAddress,
                                                                   @RequestParam(value = "tableName", required = true) String tableName,
                                                                   @RequestParam(value = "stationId", required = true) String stationId,
                                                                   @RequestParam(value = "tableName2", required = false) String tableName2) {
        StationBasic stationBasic = stationBasicMapper.selectById(stationId);
        String nameByIndexAddress = idxBizFanHealthIndexMapper.getPointNameByIndexAddress(indexAddress, tableName, stationBasic.getFanGatewayId());

        int num = idxBizFanHealthIndexMapper.getIsWarningByPointId(indexAddress, stationBasic.getFanGatewayId(), tableName2,stationBasic.getBoosterGatewayId());

        HashMap<String, Object> resultMap = new HashMap<>();
        resultMap.put("text", nameByIndexAddress);
        resultMap.put("warningNum", num);
        return ResponseHelper.buildResponse(resultMap);
    }

    @TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "风站/光伏 右下诊断分析")
    @GetMapping("/getRiskHandleByVarDesc")
    public ResponseModel<Map<String, String>> getRiskHandleByVarDesc(@RequestParam(value = "varDesc", required = false) String varDesc,
                                                                     @RequestParam(value = "tableName", required = true) String tableName,
                                                                     @RequestParam(value = "stationId") String stationId) {

        StationBasic stationBasic = stationBasicMapper.selectById(stationId);
        varDesc = idxBizFanHealthIndexMapper.getPointNameByIndexAddress(varDesc, tableName, stationBasic.getFanGatewayId());
        FeignClientResult<List<String>> sevenEntityMcb = null;
        try {
            sevenEntityMcb = riskWarningFeign.getRiskHandleByVarDesc(varDesc);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (ObjectUtils.isEmpty(sevenEntityMcb) || sevenEntityMcb.getStatus() != 200) {
            HashMap<String, String> stringStringHashMap = new HashMap<>();
            stringStringHashMap.put("content", "");
            return ResponseHelper.buildResponse(stringStringHashMap);
        }
        StringBuilder resultString = new StringBuilder();
        List<String> result = sevenEntityMcb.getResult();
        for (String s : result) {
            resultString.append(s);
        }
        HashMap<String, String> stringStringHashMap = new HashMap<>();
        stringStringHashMap.put("content", resultString.toString());
        return ResponseHelper.buildResponse(stringStringHashMap);
    }


    private IdxBizFanHealthLevel getHealthLevelByScore(List<IdxBizFanHealthLevel> healthLevelInfoList, String station, String type, Double score) {

        IdxBizFanHealthLevel resultDto = new IdxBizFanHealthLevel();

        String stationType = "风电站";
        List<IdxBizFanHealthLevel> collect = healthLevelInfoList.stream().filter(item -> item.getAnalysisObjType().contains(station)).collect(Collectors.toList());
        for (IdxBizFanHealthLevel item : collect) {
            if (!item.getAnalysisObjType().contains("子系统")) {
                stationType = "光伏站";
            }
        }

        for (IdxBizFanHealthLevel item : collect) {
            if (type.equals("设备") && stationType.equals("风电站") && item.getAnalysisObjType().contains(type) && score >= item.getGroupLowerLimit() && score <= item.getGroupUpperLimit() ) {
                resultDto =  item;
                break;
            }
            if (type.equals("子系统") && stationType.equals("风电站") && item.getAnalysisObjType().contains(type) && score >= item.getGroupLowerLimit() && score <= item.getGroupUpperLimit() ) {
                resultDto =  item;
                break;
            }
            if (type.equals("测点") && item.getAnalysisObjType().contains(type) && score >= item.getGroupLowerLimit() && score <= item.getGroupUpperLimit() ) {
                resultDto =  item;
                break;
            }

            if (type.equals("设备") && stationType.equals("光伏站") && item.getAnalysisObjType().contains("子阵") && score >= item.getGroupLowerLimit() && score <= item.getGroupUpperLimit() ) {
                resultDto =  item;
                break;
            }

            if (type.equals("子系统") && stationType.equals("光伏站") && item.getAnalysisObjType().contains("设备") && score >= item.getGroupLowerLimit() && score <= item.getGroupUpperLimit() ) {
                resultDto =  item;
                break;
            }
        }

        return resultDto;
    }

    @TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "全景诊断回溯")
    @GetMapping("/getFullViewRecall")
    public ResponseModel<Map<String, Object>> getFullViewRecall() {
        HashMap<String, Object> resultMapFinally = new HashMap<>();
        List<String> gatewayIds = this.getGatewayIds();
        List<Map<String, Object>> stationIndexInfo = idxBizFanHealthIndexMapper.getStationIndexInfo();
        Map<String, Double> stationHealthIndexMap = stationIndexInfo.stream().collect(Collectors.toMap(t -> t.get("station").toString(), t -> Double.parseDouble(t.get("healthIndex").toString())));


        List<Map<String, Object>> equipmentIndexInfo = idxBizFanHealthIndexMapper.getEquipmentIndexInfo();
        Map<String, Double> equipmentIndexInfoMap = equipmentIndexInfo.stream().collect(Collectors.toMap(t -> t.get("equipmentName").toString(), t -> Double.parseDouble(t.get("healthIndex").toString())));


        List<Map<String, Object>> subSystemIndexInfo = idxBizFanHealthIndexMapper.getSubSystemIndexInfo();
        Map<String, Double> subSystemIndexInfoMap = subSystemIndexInfo.stream().collect(Collectors.toMap(t -> t.get("subSystem").toString(), t -> Double.parseDouble(t.get("healthIndex").toString())));


        List<Map<String, Object>> pointNameIndexInfo = idxBizFanHealthIndexMapper.getPointNameIndexInfo();
        Map<String, Double> pointNameIndexInfoMap = pointNameIndexInfo.stream().collect(Collectors.toMap(t -> t.get("gatewayIndexAddress").toString(), t -> Double.parseDouble(t.get("healthIndex").toString())));


        List<IdxBizFanHealthLevel> healthLevelInfoList = idxBizFanHealthIndexMapper.getHealthLevelInfoList(gatewayIds);

        List<FullViewRecallDataDTO> list = idxBizFanHealthIndexMapper.getFullViewRecall(null);
        Map<String, Map<String, Map<String, Map<String, Map<String, List<FullViewRecallDataDTO>>>>>> resultMap = list.stream()
                .collect(Collectors.groupingBy(FullViewRecallDataDTO::getArea,
                        Collectors.groupingBy(FullViewRecallDataDTO::getStation,
                                Collectors.groupingBy(FullViewRecallDataDTO::getEquipmentName,
                                        Collectors.groupingBy(FullViewRecallDataDTO::getSubSystem,
                                                Collectors.groupingBy(FullViewRecallDataDTO::getPointName))))));
        int areaInt = 1;
        int pointNameInt = 1;
        int stationInt = 1;
        int equipmentInt = 1;
        int subSystemInt = 1;
        List<FullViewRecallInfoDTO> fullViewRecallList = new ArrayList<>();
        List<Map<String, String>> resultMapFromToList = new ArrayList<>();
        Double healthScoreInfo = idxBizFanHealthIndexMapper.getHealthScoreInfo(null, null).doubleValue();

        LambdaQueryWrapper<IdxBizFanHealthLevel> query = new LambdaQueryWrapper<>();
        query.isNull(IdxBizFanHealthLevel::getStatus);
        query.eq(IdxBizFanHealthLevel::getAnalysisObjType, "全域");
        query.lt(IdxBizFanHealthLevel::getGroupLowerLimit, healthScoreInfo);
        query.ge(IdxBizFanHealthLevel::getGroupUpperLimit, healthScoreInfo);
        IdxBizFanHealthLevel idxBizFanHealthLevel = idxBizFanHealthLevelMapper.selectOne(query);

        FullViewRecallInfoDTO allMapDto = new FullViewRecallInfoDTO();
        allMapDto.setKey("0");
        allMapDto.setName("全域设备健康状态指数");
        allMapDto.setLoc("0 2000");
        allMapDto.setScoreRange("");
        allMapDto.setStatus(idxBizFanHealthLevel.getHealthLevel());
        allMapDto.setScore(healthScoreInfo);
        allMapDto.setIsRoot(true);
        allMapDto.setCategory("category");
        fullViewRecallList.add(allMapDto);

        for (Map.Entry<String, Map<String, Map<String, Map<String, Map<String, List<FullViewRecallDataDTO>>>>>> areaMap : resultMap.entrySet()) {
            Double areaLowScore = null;
            Double areaHighScore = null;

            Double areaHealthScoreInfo = idxBizFanHealthIndexMapper.getHealthScoreInfo(areaMap.getKey(), null).doubleValue();

            LambdaQueryWrapper<IdxBizFanHealthLevel> areaQuery = new LambdaQueryWrapper<>();
            areaQuery.isNull(IdxBizFanHealthLevel::getStatus);
            areaQuery.eq(IdxBizFanHealthLevel::getAnalysisObjType, "片区");
            areaQuery.lt(IdxBizFanHealthLevel::getGroupLowerLimit, areaHealthScoreInfo);
            areaQuery.ge(IdxBizFanHealthLevel::getGroupUpperLimit, areaHealthScoreInfo);
            IdxBizFanHealthLevel areaIdxBizFanHealthLevel = idxBizFanHealthLevelMapper.selectOne(areaQuery);

            FullViewRecallInfoDTO areaMapDto = new FullViewRecallInfoDTO();
            areaMapDto.setKey("0-" + areaInt);
            areaMapDto.setName(areaMap.getKey());
            areaMapDto.setLoc(350 + " " + (1410 + areaInt * 20));
            areaMapDto.setStatus(areaIdxBizFanHealthLevel.getHealthLevel());
            areaMapDto.setScore(areaHealthScoreInfo);
            HashMap<String, String> areaMapFromTo = new HashMap<>();
            areaMapFromTo.put("from", "0");
            areaMapFromTo.put("to", areaMapDto.getKey());
            resultMapFromToList.add(areaMapFromTo);
            areaInt++;
            for (Map.Entry<String, Map<String, Map<String, Map<String, List<FullViewRecallDataDTO>>>>> stationMap : areaMap.getValue().entrySet()) {
                Double stationLowScore = null;
                Double stationHighScore = null;
                if (areaLowScore == null && areaHighScore == null) {
                    areaLowScore = stationHealthIndexMap.getOrDefault(stationMap.getKey(), 100.0);
                    areaHighScore = stationHealthIndexMap.getOrDefault(stationMap.getKey(), 100.0);
                } else {
                    if (stationHealthIndexMap.getOrDefault(stationMap.getKey(), 100.0) < areaLowScore) {
                        areaLowScore = stationHealthIndexMap.getOrDefault(stationMap.getKey(), 100.0);
                    }
                    if (stationHealthIndexMap.getOrDefault(stationMap.getKey(), 100.0) > areaHighScore) {
                        areaHighScore = stationHealthIndexMap.getOrDefault(stationMap.getKey(), 100.0);
                    }
                }

                FullViewRecallInfoDTO stationDto = new FullViewRecallInfoDTO();
                stationDto.setKey(areaMapDto.getKey() + "-" + stationInt);
                stationDto.setName(stationMap.getKey());
                stationDto.setLoc(680 + " " + (1000 + 900 * (stationInt - 1)));

                stationDto.setStatus("");
                stationDto.setScore(stationHealthIndexMap.getOrDefault(stationMap.getKey(), 100.0));
                LambdaQueryWrapper<IdxBizFanHealthLevel> stationQuery = new LambdaQueryWrapper<>();
                stationQuery.like(IdxBizFanHealthLevel::getStatus, stationMap.getKey());
                stationQuery.eq(IdxBizFanHealthLevel::getAnalysisObjType, "场站");
                stationQuery.lt(IdxBizFanHealthLevel::getGroupLowerLimit, areaHealthScoreInfo);
                stationQuery.ge(IdxBizFanHealthLevel::getGroupUpperLimit, areaHealthScoreInfo);
                IdxBizFanHealthLevel stationLevel = idxBizFanHealthLevelMapper.selectOne(stationQuery);
                stationDto.setStatus(ObjectUtils.isNotEmpty(stationLevel) ? stationLevel.getHealthLevel() : "");
                if (ObjectUtils.isEmpty(stationLevel)) {
                    LambdaQueryWrapper<IdxBizPvHealthLevel> stationPvQuery = new LambdaQueryWrapper<>();
                    stationPvQuery.like(IdxBizPvHealthLevel::getStatus, stationMap.getKey());
                    stationPvQuery.eq(IdxBizPvHealthLevel::getAnalysisObjType, "场站");
                    stationPvQuery.lt(IdxBizPvHealthLevel::getGroupLowerLimit, areaHealthScoreInfo);
                    stationPvQuery.ge(IdxBizPvHealthLevel::getGroupUpperLimit, areaHealthScoreInfo);
                    IdxBizPvHealthLevel stationPvLevel = idxBizPvHealthLevelMapper.selectOne(stationPvQuery);
                    if (ObjectUtils.isNotEmpty(stationPvLevel)) {
                        stationDto.setStatus(stationPvLevel.getHealthLevel());
                    }
                }
                HashMap<String, String> stationMapFromTo = new HashMap<>();
                stationMapFromTo.put("from", areaMapDto.getKey());
                stationMapFromTo.put("to", stationDto.getKey());
                resultMapFromToList.add(stationMapFromTo);
                stationInt++;
                for (Map.Entry<String, Map<String, Map<String, List<FullViewRecallDataDTO>>>> equipmentMap : stationMap.getValue().entrySet()) {



                    if (stationLowScore == null && stationHighScore == null) {
                        stationLowScore = equipmentIndexInfoMap.getOrDefault(equipmentMap.getKey(), 100.0);
                        stationHighScore = equipmentIndexInfoMap.getOrDefault(equipmentMap.getKey(), 100.0);
                    } else {
                        if (equipmentIndexInfoMap.getOrDefault(equipmentMap.getKey(), 100.0) < stationLowScore) {
                            stationLowScore = equipmentIndexInfoMap.getOrDefault(equipmentMap.getKey(), 100.0);
                        }
                        if (equipmentIndexInfoMap.getOrDefault(equipmentMap.getKey(), 100.0) > stationHighScore) {
                            stationHighScore = equipmentIndexInfoMap.getOrDefault(equipmentMap.getKey(), 100.0);
                        }
                    }



                    FullViewRecallInfoDTO equipmentMapDto = new FullViewRecallInfoDTO();
                    equipmentMapDto.setKey(stationDto.getKey() + "-" + equipmentInt);
                    equipmentMapDto.setName(equipmentMap.getKey());
                    equipmentMapDto.setLoc(1000 + " " + (400 + 200 * (equipmentInt - 1)));
                    equipmentMapDto.setScoreRange("");

                    IdxBizFanHealthLevel levelInfo = getHealthLevelByScore(healthLevelInfoList, stationMap.getKey(), "设备", equipmentIndexInfoMap.getOrDefault(equipmentMap.getKey(), 100.0));
                    equipmentMapDto.setStatus(levelInfo.getHealthLevel());
                    equipmentMapDto.setScore(equipmentIndexInfoMap.getOrDefault(equipmentMap.getKey(), 100.0));
                    fullViewRecallList.add(equipmentMapDto);
                    HashMap<String, String> equipmentMapFromTo = new HashMap<>();
                    equipmentMapFromTo.put("from", stationDto.getKey());
                    equipmentMapFromTo.put("to", equipmentMapDto.getKey());
                    resultMapFromToList.add(equipmentMapFromTo);
                    equipmentInt++;
                    for (Map.Entry<String, Map<String, List<FullViewRecallDataDTO>>> subSystemMap : equipmentMap.getValue().entrySet()) {
                        FullViewRecallInfoDTO subSystemMapDto = new FullViewRecallInfoDTO();
                        subSystemMapDto.setKey(equipmentMapDto.getKey() + "-" + subSystemInt);
                        subSystemMapDto.setName(subSystemMap.getKey());
                        subSystemMapDto.setLoc(2000 + " " + (300 + 90 * (subSystemInt - 1)));
                        subSystemMapDto.setScoreRange("");
//                        subSystemMapDto.setStatus(null);

                        IdxBizFanHealthLevel levelInfoZxt = getHealthLevelByScore(healthLevelInfoList, stationMap.getKey(), "子系统", subSystemIndexInfoMap.getOrDefault(subSystemMap.getKey(), 100.0));
                        subSystemMapDto.setStatus(levelInfoZxt.getHealthLevel());

                        subSystemMapDto.setScore(subSystemIndexInfoMap.getOrDefault(subSystemMap.getKey(), 100.0));
                        fullViewRecallList.add(subSystemMapDto);
                        HashMap<String, String> subSystemMapFromTo = new HashMap<>();
                        subSystemMapFromTo.put("from", equipmentMapDto.getKey());
                        subSystemMapFromTo.put("to", subSystemMapDto.getKey());
                        resultMapFromToList.add(subSystemMapFromTo);
                        subSystemInt++;
                        for (Map.Entry<String, List<FullViewRecallDataDTO>> pointNameMap : subSystemMap.getValue().entrySet()) {
                            FullViewRecallInfoDTO pointNameMapDto = new FullViewRecallInfoDTO();
                            pointNameMapDto.setKey(subSystemMapDto.getKey() + "-" + pointNameInt);
                            pointNameMapDto.setName(pointNameMap.getKey());

                            FullViewRecallDataDTO fullViewRecallDataDTO = pointNameMap.getValue().get(0);

                            pointNameMapDto.setLoc(3800 + " " + (250 + 80 * (pointNameInt - 1)));
                            pointNameMapDto.setScoreRange("");

                            IdxBizFanHealthLevel levelInfoBL = getHealthLevelByScore(healthLevelInfoList, stationMap.getKey(), "测点", pointNameIndexInfoMap.getOrDefault(fullViewRecallDataDTO.getStation() + "_" + fullViewRecallDataDTO.getIndexAddress(), 100.0));
                            pointNameMapDto.setStatus(levelInfoBL.getHealthLevel());

                            pointNameMapDto.setScore(pointNameIndexInfoMap.getOrDefault(fullViewRecallDataDTO.getStation() + "_" + fullViewRecallDataDTO.getIndexAddress(), 100.0));
                            fullViewRecallList.add(pointNameMapDto);
                            HashMap<String, String> pointNameMapFromTo = new HashMap<>();
                            pointNameMapFromTo.put("from", subSystemMapDto.getKey());
                            pointNameMapFromTo.put("to", pointNameMapDto.getKey());
                            resultMapFromToList.add(pointNameMapFromTo);
                            pointNameInt++;
                        }
                    }
                }
                stationDto.setScoreRange("(" + stationLowScore + ", " + stationHighScore + ")");
                fullViewRecallList.add(stationDto);
            }

            areaMapDto.setScoreRange("(" + areaLowScore + ", " + areaHighScore + ")");
            fullViewRecallList.add(areaMapDto);
        }

        resultMapFinally.put("nodeDataArray", fullViewRecallList);
        resultMapFinally.put("linkDataArray", resultMapFromToList);
        resultMapFinally.put("class", "GraphLinksModel");
        return ResponseHelper.buildResponse(resultMapFinally);
    }


    @TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "获取区域信息,根据层级查询单位信息 key 和 value都是区域名称")
    @GetMapping("/getAreaListByLevel")
    public ResponseModel<List<Map<String, String>>> getAreaListByLevel(@RequestParam("level") String level) throws Exception {
        FeignClientResult<List<CompanyModel>> listFeignClientResult = Privilege.companyClient.queryAgencyList(level);
        ArrayList<Map<String, String>> maps = new ArrayList<>();
        if (!ObjectUtils.isEmpty(listFeignClientResult)) {
            if (listFeignClientResult.getStatus() == 200) {
                listFeignClientResult.getResult().forEach(item -> {
                    HashMap<String, String> resultMap = new HashMap<>();
                    resultMap.put("text", item.getCompanyName());
                    resultMap.put("value", item.getCompanyName());
                    maps.add(resultMap);
                });
            } else {
                throw new RuntimeException(listFeignClientResult.getMessage());
            }
        }
        return ResponseHelper.buildResponse(maps);
    }

    @TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "风电-场站风速 、 光伏-辐照强度 （WTX-801_25_WTX-801_总辐射）")
    @GetMapping("/getFanWindSpeedInfo")
    public ResponseModel<Map<String, Object>> getFanWindSpeedInfo(@RequestParam("stationId") String stationId,
                                                                  @RequestParam("equipmentIndexName") String equipmentIndexName,
                                                                  @RequestParam("limitNum") Integer limitNum,
                                                                  @RequestParam(value = "stationType", required = false) String stationType) throws Exception {
        if (StrUtil.isNotEmpty(stationId)) {
            StationBasic stationBasic = stationBasicMapper.selectById(stationId);
            stationId = StrUtil.isNotEmpty(stationType) ? stationBasic.getBoosterGatewayId() : stationBasic.getFanGatewayId();
        }
        String date = DateUtils.convertDateToString(DateUtils.dateAddHours(DateUtils.getCurrentDayStartTime(new Date()), -8), DateUtils.DATE_TIME_PATTERN);
        List<IndicatorData> indicatorDataList = indicatorDataMapper.selectByIndexNameAndDate(equipmentIndexName, stationId, date, limitNum);
        Map<String,Object> map = new HashMap<>();
        List<Object> valueList = new ArrayList<>();
        List<Object> time = new ArrayList<>();
        Collections.reverse(indicatorDataList);
        for (IndicatorData indicatorData : indicatorDataList) {
            valueList.add(String.format("%.2f", indicatorData.getValueF()));
            Timestamp createdTime = indicatorData.getCreatedTime();
            String s = DateUtils.convertDateToString(createdTime, "HH:mm");
            time.add(s);
        }
        map.put("seriesData", valueList);
        map.put("axisData",time);
        return ResponseHelper.buildResponse(map);
    }


    @TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "修改业务事实表的一条数据")
    @PutMapping("/updateRowAndManyTable")
    public ResponseModel<Boolean> updateRowAndManyTable(@RequestBody Map<String, Object> kv) {
        if ("安全".equals(kv.get("HEALTH_LEVEL").toString())
                && (!"100.0".equals(kv.get("GROUP_UPPER_LIMIT").toString())
                && !"100".equals(kv.get("GROUP_UPPER_LIMIT").toString()))) {
            throw new RuntimeException("安全的分数上限只能是100");
        }
        if ("危险".equals(kv.get("HEALTH_LEVEL").toString())
                && (!"0.0".equals(kv.get("GROUP_LOWER_LIMIT").toString())
                && !"0".equals(kv.get("GROUP_LOWER_LIMIT").toString()))) {
            throw new RuntimeException("危险的分数下限只能是0");
        }

        idxBizFanHealthLevelMapper.updateByInfo(
                "idx_biz_pv_health_level",
                kv.get("GROUP_UPPER_LIMIT").toString(),
                kv.get("GROUP_LOWER_LIMIT").toString(),
                kv.get("ANALYSIS_OBJ_TYPE").toString(),
                kv.get("HEALTH_LEVEL").toString());
        idxBizFanHealthLevelMapper.updateByInfo(
                "idx_biz_fan_health_level",
                kv.get("GROUP_UPPER_LIMIT").toString(),
                kv.get("GROUP_LOWER_LIMIT").toString(),
                kv.get("ANALYSIS_OBJ_TYPE").toString(),
                kv.get("HEALTH_LEVEL").toString());

        if ("安全".equals(kv.get("HEALTH_LEVEL").toString())) {
            idxBizFanHealthLevelMapper.updateByInfoIsNull(
                    "idx_biz_fan_health_level",
                    kv.get("GROUP_LOWER_LIMIT").toString(),
                    null,
                    kv.get("ANALYSIS_OBJ_TYPE").toString(),
                    "注意");
            idxBizFanHealthLevelMapper.updateByInfoIsNull(
                    "idx_biz_pv_health_level",
                    kv.get("GROUP_LOWER_LIMIT").toString(),
                    null,
                    kv.get("ANALYSIS_OBJ_TYPE").toString(),
                    "注意");
        } else if ("注意".equals(kv.get("HEALTH_LEVEL").toString())) {
            idxBizFanHealthLevelMapper.updateByInfoIsNull(
                    "idx_biz_fan_health_level",
                    kv.get("GROUP_LOWER_LIMIT").toString(),
                    null,
                    kv.get("ANALYSIS_OBJ_TYPE").toString(),
                    "警告");
            idxBizFanHealthLevelMapper.updateByInfoIsNull(
                    "idx_biz_pv_health_level",
                    kv.get("GROUP_LOWER_LIMIT").toString(),
                    null,
                    kv.get("ANALYSIS_OBJ_TYPE").toString(),
                    "警告");
        } else if ("警告".equals(kv.get("HEALTH_LEVEL").toString())) {
            idxBizFanHealthLevelMapper.updateByInfoIsNull(
                    "idx_biz_fan_health_level",
                    kv.get("GROUP_LOWER_LIMIT").toString(),
                    null,
                    kv.get("ANALYSIS_OBJ_TYPE").toString(),
                    "危险");
            idxBizFanHealthLevelMapper.updateByInfoIsNull(
                    "idx_biz_pv_health_level",
                    kv.get("GROUP_LOWER_LIMIT").toString(),
                    null,
                    kv.get("ANALYSIS_OBJ_TYPE").toString(),
                    "危险");
        }
        if ("测点".equals(kv.get("ANALYSIS_OBJ_TYPE").toString())) {
            LambdaUpdateWrapper<IdxBizFanWarningRuleSet> lambda1 = new LambdaUpdateWrapper<>();
            lambda1.set(IdxBizFanWarningRuleSet::getWarningIf, "<=" + kv.get("GROUP_UPPER_LIMIT").toString());
            lambda1.eq(IdxBizFanWarningRuleSet::getWarningName, kv.get("HEALTH_LEVEL").toString());
            idxBizFanWarningRuleSetService.update(lambda1);

            LambdaUpdateWrapper<IdxBizPvWarningRuleSet> lambda2 = new LambdaUpdateWrapper<>();
            lambda2.set(IdxBizPvWarningRuleSet::getWarningIf, "<=" + kv.get("GROUP_UPPER_LIMIT").toString());
            lambda2.eq(IdxBizPvWarningRuleSet::getWarningName, kv.get("HEALTH_LEVEL").toString());
            idxBizPvWarningRuleSetService.update(lambda2);
        }
        return ResponseHelper.buildResponse(true);
    }

    /**
     * 获取用户权限(此处使用gatewayId)
     *
     * @return gatewayIds
     */
    private List<String> getGatewayIds() {
        List<String> permissions = permissionService.getCurrentUserPermissions();
        if (Objects.isNull(permissions)) {
            permissions = Collections.emptyList();
        }
        return permissions;
    }
}
