package com.yeejoin.amos.boot.module.jxiop.biz.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.yeejoin.amos.boot.biz.common.dto.BaseDto;
import com.yeejoin.amos.boot.biz.common.utils.DateUtils;
import com.yeejoin.amos.boot.module.jxiop.api.dto.StationBasicDto;
import com.yeejoin.amos.boot.module.jxiop.api.entity.StationPlan;
import com.yeejoin.amos.boot.module.jxiop.api.feign.IdxFeign;
import com.yeejoin.amos.boot.module.jxiop.api.amosprojectmapper.CompanyMapper;
import com.yeejoin.amos.boot.module.jxiop.api.mapper.StationBasicMapper;
import com.yeejoin.amos.boot.module.jxiop.api.mapper.StationPlanMapper;
import com.yeejoin.amos.boot.module.jxiop.biz.ESDto.ESEquipments;
import com.yeejoin.amos.boot.module.jxiop.biz.constants.CommonConstans;
import com.yeejoin.amos.boot.module.jxiop.biz.dto.ESEquipmentsDTO;
import com.yeejoin.amos.component.feign.model.FeignClientResult;
import com.yeejoin.amos.component.robot.AmosRequestContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class AppletMonitorServiceImpl {

    @Autowired
    CommonServiceImpl commonServiceImpl;
    @Autowired
    StationBasicMapper stationBasicMapper;

    @Autowired
    CompanyMapper companyMapper;

    @Autowired
    CommonServiceImpl commonService;

    @Autowired
    MonitorFanIndicatorImpl monitorFanIndicator;

    @Autowired
    IdxFeign idxFeign;
    @Autowired
    AmosRequestContext requestContext;
    @Autowired
    StationPlanMapper stationPlanMapper;



   public Map<String,Object> getFanStationInfo(StationBasicDto stationBasic ){

       List<StationPlan> planPower = stationPlanMapper.getPlanGenByStationIdAndYear(String.valueOf(stationBasic.getSequenceNbr()), String.valueOf(DateUtils.getYear(new Date())));
       String gatewayId = stationBasic.getFanGatewayId();
       Map<String, Object> columnMap = new HashMap<>();
       Map<String, List<String>> queryCondtion = new HashMap<>();
       queryCondtion.put(CommonConstans.QueryStringEquipmentIndexName, Arrays.asList("30秒平均风速", "日发电量", "月发电量", "年发电量"));
       queryCondtion.put(CommonConstans.QueryStringGateWayId, Arrays.asList(gatewayId));
       List<ESEquipments> result2 = commonServiceImpl.getListDataByCondtions(queryCondtion, null, ESEquipments.class);
       columnMap.put("日发电量", String.format(CommonConstans.Fourdecimalplaces, commonServiceImpl.getSumByEquipmentIndxName(result2, "日发电量")));
       columnMap.put("月发电量", String.format(CommonConstans.Fourdecimalplaces, commonServiceImpl.getSumByEquipmentIndxName(result2, "月发电量")));
       columnMap.put("年发电量", String.format(CommonConstans.Fourdecimalplaces, commonServiceImpl.getSumByEquipmentIndxName(result2, "年发电量")));
       columnMap.put("30秒平均风速", String.format(CommonConstans.Twodecimalplaces, commonServiceImpl.getAvagerByEquipmentIndxName(result2, "30秒平均风速")));
       Map<String, List<String>> queryCondtion1 = new HashMap<>();
       queryCondtion1.put(CommonConstans.QueryStringEquipmentIndexName, Arrays.asList("220kV夏雩线212线路测控装置PCS-9705TA有功功率一次值"));
       queryCondtion1.put(CommonConstans.QueryStringGateWayId, Arrays.asList(stationBasic.getBoosterGatewayId()));
       List<ESEquipments> result1 = commonService.getListDataByCondtions(queryCondtion1, null, ESEquipments.class);
       columnMap.put("有功功率", String.format("%.2f", result1.get(0).getValueF()));
       String num = monitorFanIndicator.getEquipCount(gatewayId, "FDZ");
       columnMap.put("风机台数", num);
       Double capacityl = commonService.getStationCapactityByStationWerks(stationBasic.getStationNumber());
       columnMap.put("装机容量", String.format("%.2f", capacityl));

       Map<String, Object> data = new HashMap<>();
       data.put("installedCapacity", columnMap.get("装机容量").toString());
       data.put("dayPowerGeneration", columnMap.get("日发电量").toString());
       data.put("equipNum", columnMap.get("风机台数").toString().replace(".0", ""));
       data.put("monthPowerGeneration", columnMap.get("月发电量").toString());
       data.put("windSpeed", columnMap.get("30秒平均风速").toString());
       data.put("yearPowerGeneration", columnMap.get("年发电量").toString());
       data.put("activePower", columnMap.get("有功功率"));
       data.put("dailyUseOfHour", String.format("%.2f", ((Double.parseDouble(columnMap.get("日发电量").toString()) * 10) / (Double.parseDouble(columnMap.get("装机容量").toString())))));
       //风机运行 及 停机
       List<ESEquipmentsDTO> equipmentsDTOS =  monitorFanIndicator.getFanStatusList(String.valueOf(stationBasic.getSequenceNbr()));
       Map<String, Long> countMap = equipmentsDTOS.stream()
               .collect(Collectors.groupingBy(ESEquipmentsDTO::getAddress, Collectors.counting()));

       HashMap<String, Object> colorMap = new HashMap<>();
       colorMap.put("正常运行",0);
       colorMap.put("报警运行",0);
       colorMap.put("停机状态",0);
       colorMap.put("故障状态",0);
       colorMap.put("限功率",0);
       colorMap.put("待机状态",0);
       colorMap.put("维护状态",0);
       colorMap.put("通讯中断",0);

       countMap.keySet().forEach(e->{
           colorMap.put(e,countMap.get(e));

       });
       data.put("statusMap",colorMap);
       Map<String, Object> stationMark = idxFeign.getStationMarkList(stationBasic.getProjectOrgCode(),"1","4");
      // Map<String, Object> result = stationMark.getResult();
       List<String> list = Arrays.asList("P1", "S1", "H2", "V1");
       //   P1 工况管控分数 S1 设备管控分数 H2 其他分数  V1 人员管控分数
       list.forEach(e->{
           data.put(e,stationMark.get(e));
       });
       data.put("value",stationMark.get("value"));

       double yearPower = planPower.stream().mapToDouble(StationPlan::getValue).sum();
       Double monthPower = planPower.stream().filter(e -> e.getMonthly().equals(String.valueOf(DateUtils.getMonth(new Date())))).findFirst().get().getValue();
       double dayPower = monthPower / DateUtils.getDaysOfMonth(new Date());
       data.put("yearPower",yearPower);
       data.put("monthPower",monthPower);
       data.put("dayPower",dayPower);
       return data;
   }


    public  Map<String,Object>  getPvStationInfo(StationBasicDto stationBasic){

        String gatewayId = stationBasic.getFanGatewayId();
        String boosterGatewayId = stationBasic.getBoosterGatewayId();
        String[] columnList = new String[]{CommonConstans.taiHeGenIndicatorDay, CommonConstans.taiHeGenIndicatorMonth, CommonConstans.taiHeGenIndicatorYear};
        Map<String, Object> columnMap = new HashMap<>();
        //日 月 年发电量同仅统计逆变器数据
        List<Map<String, Object>> mapList;

        for (String column : columnList) {
            Double result = commonService.getTotalByIndicatiorByGF(boosterGatewayId, column);
            columnMap.put(column, result);
        }

        Map<String, List<String>> queryCondtion = new HashMap<>();
        queryCondtion.put(CommonConstans.QueryStringEquipmentIndexName, Arrays.asList("南瑞光差保护_313P", "WTX-801_25_WTX-801_总辐射累计", "WTX-801_25_WTX-801_总辐射", "313光差保护_总反向有功电度"));
        queryCondtion.put(CommonConstans.QueryStringGateWayId, Arrays.asList(stationBasic.getBoosterGatewayId()));
        List<ESEquipments> result1 = commonService.getListDataByCondtions(queryCondtion, null, ESEquipments.class);
        columnMap.put("有功功率", String.format("%.2f", commonService.getSumByEquipmentIndxName(result1, "南瑞光差保护_313P") * CommonConstans.kwToMv));
        String num = monitorFanIndicator.getEquipCount(gatewayId, "GF");
        columnMap.put("风机台数", num);
        Double capacityl = commonService.getStationCapactityByStationWerks(stationBasic.getStationNumber());
        //装机容量保留两位小数
        columnMap.put("装机容量", String.format("%.2f", capacityl));
        Map<String, Object> data = new HashMap<>();
        data.put("installedCapacity", columnMap.get("装机容量").toString());
        data.put("dayPowerGeneration", columnMap.get(CommonConstans.taiHeGenIndicatorDay).toString());
        data.put("equipNum", columnMap.get("风机台数").toString().replace(".0", ""));
        data.put("monthPowerGeneration", columnMap.get(CommonConstans.taiHeGenIndicatorMonth).toString());
        data.put("irradiation", String.format("%.2f", commonService.getSumByEquipmentIndxName(result1, "WTX-801_25_WTX-801_总辐射")));
        data.put("yearPowerGeneration", columnMap.get(CommonConstans.taiHeGenIndicatorYear).toString());
        data.put("activePower", columnMap.get("有功功率").toString());
        data.put("dailyUseOfHour", String.format("%.2f", ((Double.parseDouble(columnMap.get(CommonConstans.taiHeGenIndicatorDay).toString()) * CommonConstans.wkwhToMv) / (Double.parseDouble(columnMap.get("装机容量").toString())))));
        data.put("globalRadiation", String.format("%.2f", commonService.getSumByEquipmentIndxName(result1, "WTX-801_25_WTX-801_总辐射累计")));

        //综合效率 = 发电量/理论发电量
        //理论发电量 = 峰值日照数 * 总装机容量
        //峰值日照数 = 累计辐照度/3.6
        Double todayPower = Double.valueOf(columnMap.get(CommonConstans.taiHeGenIndicatorDay).toString());
        Double total = commonService.getSumByEquipmentIndxName(result1, "WTX-801_25_WTX-801_总辐射累计");
        if (todayPower > 0 && total > 0) {
            Double overallEfficiency = todayPower * CommonConstans.wkwhToMv / ((total / 3.6) * capacityl);
            data.put("combinedEfficiency", String.format("%.2f", overallEfficiency * 100) + "%");//综合效率
        } else {
            data.put("combinedEfficiency", "0.00%");//综合效率
        }


        Map<String, Object> stationMark = idxFeign.getStationMarkList(stationBasic.getProjectOrgCode(),"1","4");
        List<String> list = Arrays.asList("P1", "S1", "H2", "V1");
        //   P1 工况管控分数 S1 设备管控分数 H2 其他分数  V1 人员管控分数
        list.forEach(e->{
            data.put(e,stationMark.get(e));
        });
        data.put("value",stationMark.get("value"));
        //计划发电量
        List<StationPlan> planPower = stationPlanMapper.getPlanGenByStationIdAndYear(String.valueOf(stationBasic.getSequenceNbr()), String.valueOf(DateUtils.getYear(new Date())));
        double yearPower = planPower.stream().mapToDouble(StationPlan::getValue).sum();
        Double monthPower = planPower.stream().filter(e -> e.getMonthly().equals(String.valueOf(DateUtils.getMonth(new Date())))).findFirst().get().getValue();
        double dayPower = monthPower / DateUtils.getDaysOfMonth(new Date());
        data.put("yearPower",yearPower);
        data.put("monthPower",monthPower);
        data.put("dayPower",dayPower);
        return data;
    }

    public Map<String,Object> getAreaInfo(String code) {

        List<StationBasicDto> stations = stationBasicMapper.getStationsByAreaCode(code);
        Map<String, Object> result = new HashMap<>();
        //全部场站的总装机容量
        double installedCapacity = stations.stream().mapToDouble(StationBasicDto::getInstalledCapacity).sum();
        result.put("installedCapacity",String.format("%.2f",installedCapacity));

        Map<String, List<String>> queryCondtion = new HashMap<>();
        queryCondtion.put(CommonConstans.QueryStringEquipmentIndexName, Arrays.asList("南瑞光差保护_313P", "WTX-801_25_WTX-801_总辐射累计", "WTX-801_25_WTX-801_总辐射", "313光差保护_总反向有功电度"));
        queryCondtion.put(CommonConstans.QueryStringGateWayId, stations.stream().map(StationBasicDto::getBoosterGatewayId).collect(Collectors.toList()));
        List<ESEquipments> result1 = commonService.getListDataByCondtions(queryCondtion, null, ESEquipments.class);




        List<StationBasicDto> fdz = stations.stream().filter(e -> e.getStationType().equals("FDZ")).collect(Collectors.toList());
        Map<String, List<String>> queryCondtion2 = new HashMap<>();
        queryCondtion2.put(CommonConstans.QueryStringEquipmentIndexName, Arrays.asList("220kV夏雩线212线路测控装置PCS-9705TA有功功率一次值"));
        queryCondtion2.put(CommonConstans.QueryStringGateWayId, Arrays.asList(fdz.get(0).getBoosterGatewayId()));
        List<ESEquipments> result2 = commonService.getListDataByCondtions(queryCondtion2, null, ESEquipments.class);


        stations.removeAll(fdz);
        List<Map<String,Object>> list = new ArrayList<>();
        Map<String, Object> data = new HashMap<>();
        data.put("type","光伏");
        data.put("installedCapacity",String.format("%.2f",fdz.stream().mapToDouble(StationBasicDto::getInstalledCapacity).sum()));
        data.put("num",stations.size());
        data.put("activePower",String.format("%.2f", result2.get(0).getValueF()));
        list.add(data);

        Map<String, Object> data2 = new HashMap<>();
        data2.put("type","风电");
        data2.put("installedCapacity",String.format("%.2f",stations.stream().mapToDouble(StationBasicDto::getInstalledCapacity).sum()));
        data2.put("num",fdz.size());
        data2.put("activePower",String.format("%.2f", commonService.getSumByEquipmentIndxName(result1, "南瑞光差保护_313P") * CommonConstans.kwToMv));
        list.add(data2);
        result.put("stationList",list);

        result.put("activePower",commonService.getSumByEquipmentIndxName(result1, "南瑞光差保护_313P") * CommonConstans.kwToMv+result2.get(0).getValueF());
        double fzl = (commonService.getSumByEquipmentIndxName(result1, "南瑞光差保护_313P") * CommonConstans.kwToMv+result2.get(0).getValueF())/installedCapacity;
        String load = String.format(CommonConstans.Fourdecimalplaces, fzl);
        result.put("load",load);

        String areaCompanyCode = companyMapper.getAreaCompanyCode(code);

        Map<String, Object> stationMark = idxFeign.assessIndexMap("asc",null,areaCompanyCode);
        //   P1 工况管控分数 S1 设备管控分数 H2 其他分数  V1 人员管控分数
        result.putAll(stationMark);

        //获取区域场站排名
        FeignClientResult<Map<String, Object>> map = idxFeign.stationRanking(1L, Long.MAX_VALUE,"DESC", "FDZ", areaCompanyCode);
        FeignClientResult<Map<String, Object>> map1 = idxFeign.stationRanking(1L, Long.MAX_VALUE, "DESC","JZSGFDZ", areaCompanyCode);;
        Map<String, Object> result3 = map.getResult();
        Map<String, Object> result4 = map1.getResult();
        result.put("rankingFD", result3.get("records"));
        result.put("rankingGF", result4.get("records"));

        Map<String, List<String>> queryCondtion1 = new HashMap<>();
        List<String> collect = fdz.stream().map(StationBasicDto::getFanGatewayId).collect(Collectors.toList());
        collect.addAll(stations.stream().map(StationBasicDto::getBoosterGatewayId).collect(Collectors.toList()));
        queryCondtion1.put(CommonConstans.QueryStringGateWayId, collect);
        Map<String, String> likeMap = new HashMap<String, String>();
        likeMap.put(CommonConstans.QueryStringEquipmentIndexName, "发电量");
        List<ESEquipments> resultWarn = commonServiceImpl.getListDataByCondtions(queryCondtion1, null,
                ESEquipments.class, likeMap);
        double dayPowerGeneration = resultWarn.stream().filter(e -> e.getEquipmentIndexName().contains("日发电量")).mapToDouble(ESEquipments::getValueF).sum();
        double monthPowerGeneration = resultWarn.stream().filter(e -> e.getEquipmentIndexName().contains("月发电量")).mapToDouble(ESEquipments::getValueF).sum();
        double yearPowerGeneration = resultWarn.stream().filter(e -> e.getEquipmentIndexName().contains("年发电量")).mapToDouble(ESEquipments::getValueF).sum();
        result.put("dayPowerGeneration",String.format("%.4f",dayPowerGeneration));
        result.put("monthPowerGeneration",String.format("%.4f",monthPowerGeneration));
        result.put("yearPowerGeneration",String.format("%.4f",yearPowerGeneration));

        List<String> collect1 = stations.stream().map(BaseDto::getSequenceNbr).map(String::valueOf).collect(Collectors.toList());
        String join = String.join(",", collect1);
        List<StationPlan> plansPower = stationPlanMapper.getPlansGenByStationIdAndYear(join, String.valueOf(DateUtils.getYear(new Date())));
        double yearPower = plansPower.stream().mapToDouble(StationPlan::getValue).sum();
        Double monthPower = plansPower.stream().filter(e -> e.getMonthly().equals(String.valueOf(DateUtils.getMonth(new Date())))).mapToDouble(StationPlan::getValue).sum();
        double dayPower = monthPower / DateUtils.getDaysOfMonth(new Date());
        result.put("yearPower",yearPower);
        result.put("monthPower",monthPower);
        result.put("dayPower",dayPower);

        return result;
    }

}
