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

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yeejoin.amos.boot.biz.common.bo.ReginParams;
import com.yeejoin.amos.boot.biz.common.controller.BaseController;
import com.yeejoin.amos.boot.module.common.biz.utils.CommonResponseUtil;
import com.yeejoin.amos.boot.module.jxiop.api.dto.IndexDto;
import com.yeejoin.amos.boot.module.jxiop.api.dto.TreeDto;
import com.yeejoin.amos.boot.module.jxiop.api.entity.StationBasic;
import com.yeejoin.amos.boot.module.jxiop.api.mapper.MonitorFanIndicatorMapper;
import com.yeejoin.amos.boot.module.jxiop.api.mapper.StationBasicMapper;
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.DeaviationRateDto;
import com.yeejoin.amos.boot.module.jxiop.biz.dto.ESEquipmentsDTO;
import com.yeejoin.amos.boot.module.jxiop.biz.dto.ResultsData;
import com.yeejoin.amos.boot.module.jxiop.biz.service.impl.CommonServiceImpl;
import com.yeejoin.amos.boot.module.jxiop.biz.service.impl.EquipAlarmEventServiceImpl;
import com.yeejoin.amos.boot.module.jxiop.biz.service.impl.MonitorFanIndicatorImpl;
import com.yeejoin.amos.boot.module.jxiop.biz.tdmapper.IndicatorDataMapper;
//import com.yeejoin.amos.component.influxdb.InfluxdbUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.typroject.tyboot.component.emq.EmqKeeper;
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.math.BigDecimal;
import java.text.Collator;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@Api(tags = "大屏相关API")
@RequestMapping(value = "/monitorFanIdx")
public class MonitorFanIdxController extends BaseController {

    @Autowired
    MonitorFanIndicatorImpl monitorFanIndicatorImpl;

    @Autowired
    MonitorFanIndicatorImpl monitorFanIndicator;

    @Autowired
    EquipAlarmEventServiceImpl equipAlarmEventService;

    @Autowired
    EquipAlarmEventServiceImpl equipAlarmEventServiceImpl;
    @Autowired
    CommonServiceImpl commonServiceImpl;
    @Autowired
    StationBasicMapper stationBasicMapper;

    @Autowired
    CommonServiceImpl commonService;

    @Value("${gl.sum.column}")
    String sumColumn;

    @Value("${gl.avg.column}")
    String avgColumn;
    @Autowired
    IndicatorDataMapper indicatorDataMapper;
    @Autowired
    MonitorFanIndicatorMapper monitorFanIndicatorMapper;
    @Autowired
    EmqKeeper emqKeeper;
    //    @Autowired
//    InfluxdbUtil influxdbUtil;
    @Value("${fan.statuts.stattuspath}")
    private String fanStatusImagePathPrefix;

    @TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "根据设备编号、场站id、前段展示模块、系统类型查询表数据")
    @GetMapping("/getFanIdxInfoByPage")
    public ResponseModel<IPage<ESEquipments>> getFanIdxInfoByPage(@RequestParam(value = "equipNum", required = false) String equipNum,
                                                                  @RequestParam(value = "stationId", required = false) String stationId,
                                                                  @RequestParam(value = "frontModule", required = false) String frontModule,
                                                                  @RequestParam(value = "systemType", required = false) String systemType,
                                                                  @RequestParam(value = "current", required = false) int current,
                                                                  @RequestParam(value = "size", required = false) int size) {
        return ResponseHelper.buildResponse(monitorFanIndicator.getFanIdxInfoByPage(equipNum, stationId, frontModule, current, size, systemType));
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "左侧树API")
    @GetMapping("/getTreeInfo")
    public ResponseModel<TreeDto> getTreeInfo(@RequestParam(value = "sequenceNbr") String sequenceNbr) {
        ReginParams reginParams = getSelectedOrgInfo();
        return ResponseHelper.buildResponse(monitorFanIndicator.getTreeInfo(sequenceNbr,reginParams));
    }


    @TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "风机布置图 - 风机状态列表")
    @GetMapping("/getFanStatusList")
    public ResponseModel<IPage<ESEquipmentsDTO>> getFanStatusList(@RequestParam(value = "stationId", required = false) String stationId,
                                                                  @RequestParam(value = "current", required = false) int current,
                                                                  @RequestParam(value = "size", required = false) int size) {
        List<ESEquipmentsDTO> fanStatusList = monitorFanIndicator.getFanStatusList(stationId);
        Page<ESEquipmentsDTO> page = new Page<>(current, size);
        List<ESEquipmentsDTO> collect = fanStatusList.stream()
                .sorted(Comparator.comparing(t -> Integer.parseInt(t.getEquipmentNumber())))
                .skip((long) (current - 1) * size)
                .limit(size)
                .collect(Collectors.toList());
        page.setTotal(fanStatusList.size());
        page.setRecords(collect);
        return ResponseHelper.buildResponse(page);
    }

    @TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "风机布置图 - 风机状态图片")
    @GetMapping("/getFanStatusListImage")
    public ResponseModel<IPage<HashMap<String, String>>> getFanStatusListImages(@RequestParam(value = "stationId", required = false) String stationId) {
        List<ESEquipmentsDTO> fanStatusList = monitorFanIndicator.getFanStatusList(stationId);
        List<ESEquipmentsDTO> collect = fanStatusList.stream()
                .limit(999)
                .collect(Collectors.toList());
        IPage<HashMap<String, String>> page = new Page<>();
        HashMap<String, String> hashMap = new HashMap<>();
        List<ESEquipmentsDTO> indexDtoList = collect.stream().sorted(Comparator.comparing(ESEquipmentsDTO::getEquipmentNumber)).collect(Collectors.toList());
        //获取拼音首字母
        String prefix = commonService.getFanDevicePrefix(stationId);
        for (int i = 1; i <= indexDtoList.size(); i++) {
            ESEquipmentsDTO ESEquipments = indexDtoList.get(i - 1);
            hashMap.put("url" + i, fanStatusImagePathPrefix + "/" + "风机-" + ESEquipments.getAddress() + ".gif");
            hashMap.put("name" + i, prefix + ESEquipments.getEquipmentNumber());
            //用于参数传递
            hashMap.put("name" + i + 'd', ESEquipments.getEquipmentNumber());
        }
        page.setTotal(10);
        page.setSize(10);
        page.setCurrent(1);
        List<HashMap<String, String>> hashMapList = new ArrayList<>();
        hashMapList.add(hashMap);
        page.setRecords(hashMapList);
        return ResponseHelper.buildResponse(page);
    }

    @TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "风机布置图 - 风机数量")
    @GetMapping("/getFanNum")
    public ResponseModel<Integer> getFanNum(@RequestParam(value = "stationId", required = false) String stationId) {
        Integer num = monitorFanIndicator.getFanNum(stationId);
        return ResponseHelper.buildResponse(num);
    }

    @TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "风机布置图 - 实时监控表计仪表盘数据")
    @GetMapping("/getFanDataByType")
    public ResponseModel<Map<String, String>> getFanDataByType(@RequestParam(value = "stationId", required = false) String stationId,
                                                               @RequestParam(value = "equipNum", required = false) String equipNum,
                                                               @RequestParam(value = "frontModule", required = false) String frontModule,
                                                               @RequestParam(value = "typeName", required = false) String typeName) {
        String num = monitorFanIndicator.getFanDataByType(stationId, equipNum, frontModule, typeName);
        Map<String, String> map = new HashMap<>();
        map.put("value", num);
        return ResponseHelper.buildResponse(map);
    }


    @TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "风机布置图 - 风机状态统计")
    @GetMapping("/getFanStatusStatistics")
    public ResponseModel<IPage<IndexDto>> getFanStatusStatistics(@RequestParam(value = "stationId", required = false) String stationId,
                                                                 @RequestParam(value = "current", required = false) int current,
                                                                 @RequestParam(value = "size", required = false) int size) {
        List<IndexDto> fanStatusStatistics = monitorFanIndicator.getFanStatusStatistics(stationId);
        Page<IndexDto> page = new Page<>(current, size);
        List<IndexDto> collect = fanStatusStatistics.stream()
                .skip((long) (current - 1) * size)
                .limit(size)
                .collect(Collectors.toList());
        page.setTotal(fanStatusStatistics.size());
        page.setRecords(collect);
        return ResponseHelper.buildResponse(page);
    }

    @TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "风机布置图 - 风机基础信息")
    @GetMapping("/getFanBasicInfoByEquipNum")
    public ResponseModel<IndexDto> getFanBasicInfoByEquipNum(@RequestParam(value = "equipNum", required = false) String equipNum,
                                                             @RequestParam(value = "stationId", required = false) String stationId) {
        return ResponseHelper.buildResponse(monitorFanIndicator.getFanBasicInfoByEquipNum(equipNum, stationId));
    }

    @TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "获取当前表记的实时温度")
    @GetMapping("/getRealTimeTemperature")
    public ResponseModel<HashMap<String, List<String>>> getRealTimeTemperature(@RequestParam(value = "equipNum", required = false) String equipNum,
                                                                               @RequestParam(value = "stationId", required = false) String stationId,
                                                                               @RequestParam(value = "frontModule", required = false) String frontModule) {
        return ResponseHelper.buildResponse(monitorFanIndicator.getRealTimeTemperature(equipNum, stationId, frontModule));
    }

    @TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "风机布置图-总概览")
    @GetMapping("/overview")
    public ResponseModel<IPage<Map<String, Object>>> getData(@RequestParam(value = "stationId") String stationId) {


        StationBasic stationBasic = stationBasicMapper.selectById(stationId);
        String gatewayId = stationBasic.getFanGatewayId();
//        String[] columnList = new String[]{"日发电量", "月发电量", "年发电量"};
//        String[] columnLists = new String[]{"30秒平均风速"};
        Map<String, Object> columnMap = new HashMap<>();

//        for (String column : columnList) {
//            Double result = commonService.getTotalByIndicatior(gatewayId, column);
//            columnMap.put(column, String.format("%.2f", result));
//        }
//        for (String column : columnLists) {
//            Double result = commonService.getAvgvalueByIndicatior(gatewayId, column);
//            columnMap.put(column, String.format("%.2f", result));
//        }


        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));


        List<Map<String, Object>> objects = new ArrayList<>();
        Map<String, Object> data = new HashMap<>();
        data.put("title", columnMap.get("装机容量").toString());
        objects.add(data);
        Map<String, Object> data1 = new HashMap<>();
        data1.put("title", columnMap.get("日发电量").toString());
        objects.add(data1);
        Map<String, Object> data2 = new HashMap<>();
        data2.put("title", columnMap.get("风机台数").toString().replace(".0", ""));
        objects.add(data2);
        Map<String, Object> data3 = new HashMap<>();
        data3.put("title", columnMap.get("月发电量").toString());
        objects.add(data3);
        Map<String, Object> data4 = new HashMap<>();
        data4.put("title", columnMap.get("30秒平均风速").toString());
        objects.add(data4);
        Map<String, Object> data5 = new HashMap<>();
        data5.put("title", columnMap.get("年发电量").toString());
        objects.add(data5);
        Map<String, Object> data6 = new HashMap<>();
        data6.put("title", columnMap.get("有功功率"));

        objects.add(data6);
        Map<String, Object> data7 = new HashMap<>();
        data7.put("title", String.format("%.2f", ((Double.parseDouble(columnMap.get("日发电量").toString()) * 10) / (Double.parseDouble(columnMap.get("装机容量").toString())))));
        objects.add(data7);

        IPage<Map<String, Object>> result = new Page<>();
        result.setRecords(objects);
        result.setCurrent(1);
        result.setTotal(objects.size());

        return ResponseHelper.buildResponse(result);
    }


    @TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "概览-全站功率曲线")
    @GetMapping("/overviewWindSpeed")
    public void getOverviewWindSpeed(@RequestParam(value = "stationBasicId", required = true) String stationBasicId, @RequestParam(value = "type", required = false) String type, @RequestParam(value = "areaCode", required = false) String areaCode) {
        StationBasic stationBasic = stationBasicMapper.selectById(stationBasicId);
        monitorFanIndicator.getDetailsWindSpeedAll(stationBasic);
    }

    @TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "风机详情-风速功率曲线")
    @GetMapping("/detailsWindSpeed")
    public ResponseModel<Map<String, Object>> getDetailsWindSpeed(@RequestParam(value = "stationId") String stationId, String name) {
//        name = name + "风机";
        StationBasic stationBasic = stationBasicMapper.selectById(stationId);
        String gatewayId = stationBasic.getFanGatewayId();
        Map<String, Object> detailsWindSpeed = monitorFanIndicator.getDetailsWindSpeed(gatewayId, name);

        return ResponseHelper.buildResponse(detailsWindSpeed);
    }

    @TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "逆变器-功率曲线")
    @GetMapping("/getDetailsWindSpeeds")
    public ResponseModel<Map<String, Object>> getDetailsWindSpeeds(@RequestParam(value = "stationId") String stationId, String equipNum) {

        StationBasic stationBasic = stationBasicMapper.selectById(stationId);
        String gatewayId = stationBasic.getFanGatewayId();
        Map<String, Object> detailsWindSpeed = monitorFanIndicator.getDetailsWindSpeeds(gatewayId, equipNum);

        return ResponseHelper.buildResponse(detailsWindSpeed);
    }

    @TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "状态监控")
    @GetMapping("/statusMonitoring")
    public ResponseModel<IPage<Map<String, Object>>> getStatusMonitoring(@RequestParam(value = "stationId") String stationId, String equipNum, String systemType) {
        StationBasic stationBasic = stationBasicMapper.selectById(stationId);
        String gatewayId = stationBasic.getFanGatewayId();
        List<Map<String, Object>> statusMonitoring = monitorFanIndicator.getStatusMonitoring(gatewayId, equipNum, systemType);
        IPage<Map<String, Object>> result = new Page<>();
        result.setRecords(statusMonitoring);
        result.setCurrent(1);
        result.setTotal(statusMonitoring.size());
        return ResponseHelper.buildResponse(result);
    }

    @TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)

    @ApiOperation(value = "升压站光字牌/开关-通用")
    @GetMapping("/getStatusGzp")
    public ResponseModel<IPage<Map<String, Object>>> getStatusGzp(@RequestParam(value = "stationId") String stationId, String frontModule, String systemType, String equipNum, @RequestParam(required = false) String stationType) {
        StationBasic stationBasic = stationBasicMapper.selectById(stationId);
        String gatewayId = stationBasic.getBoosterGatewayId();
        if (null != stationType) {
            gatewayId = stationBasic.getFanGatewayId();
        }
        List<Map<String, Object>> statusMonitoring = monitorFanIndicator.getStatusGzp(gatewayId, systemType, frontModule, equipNum,stationBasic.getStationType());
        IPage<Map<String, Object>> result = new Page<>();
        result.setRecords(statusMonitoring);
        result.setCurrent(1);
        result.setTotal(statusMonitoring.size());
        return ResponseHelper.buildResponse(result);
    }
    @TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "升压站光字牌/开关-通用")
    @GetMapping("/getStatusGzpnew")
    public ResponseModel<IPage<Map<String, Object>>> getStatusGzpnew(@RequestParam(required = false) String name,@RequestParam(value = "stationId") String stationId, String frontModule, String systemType, String equipNum, @RequestParam(required = false) String stationType) {
        StationBasic stationBasic = stationBasicMapper.selectById(stationId);
        String gatewayId = stationBasic.getBoosterGatewayId();
        if (null != stationType) {
            gatewayId = stationBasic.getFanGatewayId();
        }
        List<Map<String, Object>> statusMonitoring = monitorFanIndicator.getStatusGzp(gatewayId, systemType, frontModule, equipNum,stationBasic.getStationType());

        if(name!=null){
            statusMonitoring=   statusMonitoring.stream().filter(s-> s.get("data").toString().contains(name)).collect(Collectors.toList());
        }


        IPage<Map<String, Object>> result = new Page<>();
        result.setRecords(statusMonitoring);
        result.setCurrent(1);
        result.setTotal(statusMonitoring.size());


        return ResponseHelper.buildResponse(result);
    }






    @TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "升压站光字牌/压板状态API-通用")
    @GetMapping("/getStatusGzpAndYb")
    public ResponseModel getStatusGzp(@RequestParam(value = "stationId") String stationId,
                                      @RequestParam(value = "frontModule") String frontModule) {
        StationBasic stationBasic = stationBasicMapper.selectById(stationId);
        String gatewayId = stationBasic.getBoosterGatewayId();
        Map<String, String> map = monitorFanIndicatorMapper.getMajorBoosterStationInfoBySort(gatewayId, frontModule);
        String name = map.get("text").contains("主变") ? map.get("text").substring(0, 3) : map.get("text");
        HashMap<String, String> stringStringHashMap = new HashMap<>();
        stringStringHashMap.put("gzp", "光字牌");
        stringStringHashMap.put("ybzt", "压板");
        stringStringHashMap.put("agzp", "A套保护光字牌");
        stringStringHashMap.put("bgzp", "B套保护光字牌");
        for (Map.Entry<String, String> stringStringEntry : stringStringHashMap.entrySet()) {
            List<Map<String, Object>> statusMonitoring = monitorFanIndicator.getStatusGzp(gatewayId, stringStringEntry.getValue(), name, null,stationBasic.getStationType());
            IPage<Map<String, Object>> result = new Page<>();
            result.setRecords(statusMonitoring);
            result.setCurrent(1);
            result.setTotal(statusMonitoring.size());
            try {
                emqKeeper.getMqttClient().publish(String.format("%s/%s/%s", stationId, frontModule, stringStringEntry.getKey()), JSON.toJSONString(result).getBytes(), 1, true);
            } catch (MqttException e) {
                e.printStackTrace();
            }
        }
        return ResponseHelper.buildResponse(null);
    }


    @TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "模拟量接口Api")
    @GetMapping("/getAnalogQuantity")
    public ResponseModel<IPage<Map<String, Object>>> getAnalogQuantity(@RequestParam(value = "stationId") String stationId, String frontModule, @RequestParam(required = false) String systemType) {
        StationBasic stationBasic = stationBasicMapper.selectById(stationId);
        String gatewayId = stationBasic.getBoosterGatewayId();
        if (null == systemType) {
            systemType = "模拟量";
        }

        List<Map<String, Object>> statusMonitoring = monitorFanIndicator.getAnalogQuantity(gatewayId, frontModule, systemType);
        IPage<Map<String, Object>> result = new Page<>();
        result.setRecords(statusMonitoring);
        result.setCurrent(1);
        result.setTotal(statusMonitoring.size());
        return ResponseHelper.buildResponse(result);
    }


    @TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "集电线路图左侧 集电线列表")
    @GetMapping("/jdTree")
    @Scheduled(cron = "0/10 * * * * ? ")
    public ResponseModel<IPage<Map<String, Object>>> getStatusJDX() {
        LambdaQueryWrapper<StationBasic> wrapper = new LambdaQueryWrapper<>();
        List<StationBasic> stationBasics = stationBasicMapper.selectList(wrapper);
        for (StationBasic stationBasic : stationBasics) {
            String gatewayId = stationBasic.getBoosterGatewayId();
            String werks = stationBasic.getStationNumber();
            if (stationBasic.getStationType().equals("FDZ")) {
                monitorFanIndicator.getStatusJDX(gatewayId, stationBasic.getSequenceNbr().toString(), "集电");
            } else if (stationBasic.getStationType().equals("JZSGFDZ")) {
                monitorFanIndicator.getStatusJDX(gatewayId, stationBasic.getSequenceNbr().toString(), "前光");
            }
        }
        return CommonResponseUtil.success();
    }


    @TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "集电线路图右侧 风机列表")
    @GetMapping("/fjList")
    @Scheduled(cron = "0/10 * * * * ? ")
    public ResponseModel getListByFJ() {


        LambdaQueryWrapper<StationBasic> wrapper = new LambdaQueryWrapper<>();
        List<StationBasic> stationBasics = stationBasicMapper.selectList(wrapper);
        for (StationBasic stationBasic : stationBasics) {
            String gatewayId = stationBasic.getFanGatewayId();
            String werks = stationBasic.getStationNumber();
            monitorFanIndicator.getListByFJ(gatewayId, werks, stationBasic.getSequenceNbr().toString());
        }


        return CommonResponseUtil.success();
    }
    @TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "统一获取集电线与风机状态")
    @GetMapping("/fanLineList")
    public void getFanLineList() {
        getStatusJDX();
        getListByFJ();
    }

    @TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "获取升压站信息 通过排序等")
    @GetMapping("/getBoosterStationInfo")
    public ResponseModel<List<Map<String, String>>> getBoosterStationInfo(@RequestParam(value = "stationId", required = false) String stationId) {
        return ResponseHelper.buildResponse(monitorFanIndicator.getBoosterStationInfo(stationId));
    }

    @TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "根据id获取场站信息")
    @GetMapping("/getByStationId")
    public ResponseModel<IPage<StationBasic>> getByStationId(@RequestParam(value = "stationId", required = false) String stationId) {
        StationBasic oneByStationNumber = monitorFanIndicator.getOneByStationNumber(stationId);
        oneByStationNumber.setTitlePos(null);
        List<StationBasic> stationBasics = Collections.singletonList(oneByStationNumber);
        IPage<StationBasic> result = new Page<>();
        result.setRecords(stationBasics);
        result.setCurrent(1);
        result.setTotal(1);
        return ResponseHelper.buildResponse(result);
    }

    @TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "夏造运行列表API")
    @GetMapping("/runningPageByStationId")
    public ResponseModel<ResultsData> runningPageByStationId(@RequestParam(value = "current") int current,
                                                             @RequestParam(value = "size") int size,
                                                             @RequestParam(value = "stationId") String stationId) {
        ResultsData resultsData = monitorFanIndicatorImpl.runningPageByStationId(current, size, stationId);
        return ResponseHelper.buildResponse(resultsData);
    }

    //@Scheduled(cron = "0/15 * * * * ? ")
    @TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "模拟量列表消息")
    @GetMapping("/getAnalogQuantityInfo")
    public ResponseModel getAnalogQuantityInfo(@RequestParam(value = "stationId") String stationId, @RequestParam(value = "routeName") String routeName) {
        StationBasic stationBasic = stationBasicMapper.selectById(stationId);
        String gatewayId = stationBasic.getBoosterGatewayId();
        monitorFanIndicator.getAnalogQuantityInfo(gatewayId, stationBasic.getSequenceNbr().toString(), routeName);
        return CommonResponseUtil.success();
    }

    //@Scheduled(cron = "0/15 * * * * ? ")
    @TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "升压站主屏消息接口")
    @GetMapping("/getMajorAnalogQuantityByPage")
    public ResponseModel getMajorAnalogQuantityByPage(@RequestParam(required = false) String stationId) {
        StationBasic stationBasic = stationBasicMapper.selectById(stationId);
        String gatewayId = stationBasic.getBoosterGatewayId();
        if (stationBasic.getStationName().contains("夏造")) {
            monitorFanIndicator.getMajorAnalogQuantityByPage(gatewayId, stationBasic.getSequenceNbr().toString());
        } else if (stationBasic.getStationName().contains("泰和")) {
            monitorFanIndicator.getMajorAnalogQuantityByPageByTHGF(gatewayId, stationBasic.getSequenceNbr().toString());
        }
        return CommonResponseUtil.success();
    }

    @TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "故障记录API")
    @GetMapping("/alarmEventtList")
    public ResponseModel<ResultsData> getAlarmEventList(@RequestParam(value = "current") int current,
                                                        @RequestParam(value = "size") int size,
                                                        @RequestParam(value = "stationId") String stationId,
                                                        @RequestParam(value = "type") String type) {
        ResultsData resultsData = new ResultsData();
        if (type.equals("0")) {
            resultsData = monitorFanIndicatorImpl.getAlarmEventList(current, size, stationId);

        } else if (type.equals("1")) {
            StationBasic stationBasic = stationBasicMapper.selectById(stationId);
            String fanGatewayId = stationBasic.getFanGatewayId();
            if ("FDZ".equals(stationBasic.getStationType())) {
                resultsData = monitorFanIndicatorImpl.getNationWideInfo(current, size, fanGatewayId, null);
            } else {
                resultsData = equipAlarmEventServiceImpl.getEventByEquipIndex(fanGatewayId, current, size, null, null);
            }

        }
        return ResponseHelper.buildResponse(resultsData);
    }


    @TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "夏造电量表计API")
    @GetMapping("/electricQuantity")
    public ResponseModel<ResultsData> getElectricQuantityList(@RequestParam(value = "current") int current,
                                                              @RequestParam(value = "size") int size,
                                                              @RequestParam(value = "stationId") String stationId,
                                                              @RequestParam(value = "stationType", required = false) String stationType) {
        StationBasic stationBasic = stationBasicMapper.selectById(stationId);
//        String gatewayId = stationBasic.getBoosterGatewayId();
        ResultsData resultsData = monitorFanIndicatorImpl.getElectricQuantityList(current, size, stationBasic);
        return ResponseHelper.buildResponse(resultsData);
    }


    @TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "开关图片API/消息")
    @GetMapping("/switchUrl")
    public ResponseModel<Map<String, Object>> getElectricQuantityList(
            @RequestParam(value = "stationId") String stationId
    ) {

        LambdaQueryWrapper<StationBasic> wrapper = new LambdaQueryWrapper<>();
        List<StationBasic> stationBasics = stationBasicMapper.selectList(wrapper);
        for (StationBasic stationBasic : stationBasics) {
            monitorFanIndicatorImpl.getSwitchUrlAll(stationBasic);
        }

        return CommonResponseUtil.success();
    }


    @TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "动态面板页面消息")
    @GetMapping("/pageTopic")
    public ResponseModel<Map<String, Object>> sendPageTopic(
            @RequestParam(value = "stationId") String stationId, @RequestParam(value = "equipName") String equipName
    ) {

        StationBasic stationBasic = stationBasicMapper.selectById(stationId);
        String gatewayId = stationBasic.getBoosterGatewayId();


        Map<String, String> map = monitorFanIndicatorMapper.getMajorBoosterStationInfoBySort(gatewayId, equipName);
        String name =  map.get("text");
//        String sql = " SELECT * FROM indicators_" + gatewayId + " WHERE (equipmentIndexName ='待机' or equipmentIndexName ='故障停机' or equipmentIndexName ='告警运行' or equipmentIndexName ='限额运行' or equipmentIndexName ='停机 or 'equipmentIndexName ='停机' or equipmentIndexName ='停机') and value = 'true'";
        if(map.get("text").equals(CommonConstans.XIAZAO_ZHUBIANGAOYACE) || map.get("text").equals(CommonConstans.XIAZAO_ZHUBIANDIYACE)){
            name = map.get("text").substring(0, 3);
        }
        Map<String, Object> switchUrl = monitorFanIndicatorImpl.getSwitchUrl(gatewayId, name);
        List<Map<String, Object>> statusMonitoring = monitorFanIndicator.getStatusGzp(gatewayId, "网络", name, null,stationBasic.getStationType());
        IPage<Map<String, Object>> result = new Page<>();
        switchUrl.put("records", statusMonitoring);
        switchUrl.put("current", 1);
        switchUrl.put("total", 100);
        List<Map<String, Object>> data = new ArrayList<>();
        data.add(switchUrl);
        result.setRecords(data);
        result.setCurrent(1);
        result.setTotal(100);

        try {
            emqKeeper.getMqttClient().publish(stationId + "/switch/" + equipName, JSON.toJSONString(result).getBytes(), 1, true);
        } catch (MqttException e) {
            e.printStackTrace();
        }
        return CommonResponseUtil.success();
    }

    @TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "1#主变油温")
    @GetMapping("/zbyw")
    public ResponseModel<Map<String, Object>> getYwData(@RequestParam(value = "stationId") String stationId) {
        StationBasic stationBasic = stationBasicMapper.selectById(stationId);
        String gatewayId = stationBasic.getBoosterGatewayId();
        Map<String, Object> resultsData = monitorFanIndicatorImpl.getyw(gatewayId);
        return ResponseHelper.buildResponse(resultsData);
    }


    @TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "光伏-总概览")
    @GetMapping("/solarPowerOverview")
    public ResponseModel<IPage<Map<String, Object>>> solarPowerData(@RequestParam(value = "stationId") String stationId) {


        StationBasic stationBasic = stationBasicMapper.selectById(stationId);
        String gatewayId = stationBasic.getFanGatewayId();
        String boosterGatewayId = stationBasic.getBoosterGatewayId();
        String[] columnList = new String[]{CommonConstans.taiHeGenIndicatorDay, CommonConstans.taiHeGenIndicatorMonth, CommonConstans.taiHeGenIndicatorYear};
        String[] columnLists = new String[]{"有功功率"};
        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));
        List<Map<String, Object>> objects = new ArrayList<>();
        Map<String, Object> data = new HashMap<>();
        data.put("title", columnMap.get("装机容量").toString());
        objects.add(data);
        Map<String, Object> data1 = new HashMap<>();
        data1.put("title", columnMap.get(CommonConstans.taiHeGenIndicatorDay).toString());
        objects.add(data1);
        Map<String, Object> data2 = new HashMap<>();
        data2.put("title", columnMap.get("风机台数").toString().replace(".0", ""));
        objects.add(data2);
        Map<String, Object> data3 = new HashMap<>();
        data3.put("title", columnMap.get(CommonConstans.taiHeGenIndicatorMonth).toString());
        objects.add(data3);
        Map<String, Object> data4 = new HashMap<>();
        data4.put("title", String.format("%.2f", commonService.getSumByEquipmentIndxName(result1, "WTX-801_25_WTX-801_总辐射")));
        objects.add(data4);
        Map<String, Object> data5 = new HashMap<>();
        data5.put("title", columnMap.get(CommonConstans.taiHeGenIndicatorYear).toString());
        objects.add(data5);
        Map<String, Object> data6 = new HashMap<>();
        data6.put("title", columnMap.get("有功功率").toString());
        objects.add(data6);
        Map<String, Object> data7 = new HashMap<>();
        data7.put("title", String.format("%.2f", ((Double.parseDouble(columnMap.get(CommonConstans.taiHeGenIndicatorDay).toString()) * CommonConstans.wkwhToMv) / (Double.parseDouble(columnMap.get("装机容量").toString())))));
        objects.add(data7);
        Map<String, Object> data8 = new HashMap<>();
        data8.put("title", String.format("%.2f", commonService.getSumByEquipmentIndxName(result1, "WTX-801_25_WTX-801_总辐射累计")));
        objects.add(data8);
        Map<String, Object> data9 = new HashMap<>();
        //综合效率 = 发电量/理论发电量
        //理论发电量 = 峰值日照数 * 总装机容量
        //峰值日照数 = 累计辐照度/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);
            data9.put("title", String.format("%.2f", overallEfficiency * 100) + "%");//综合效率
        } else {
            data9.put("title", "0.00%");//综合效率
        }
        objects.add(data9);
        IPage<Map<String, Object>> result = new Page<>();
        result.setRecords(objects);
        result.setCurrent(1);
        result.setTotal(objects.size());
        return ResponseHelper.buildResponse(result);
    }


    @TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "详情基础信息")
    @GetMapping("/getEquipInfoByEquipNum")
    public ResponseModel<Map<String, Object>> getEquipInfoByEquipNum(@RequestParam(value = "equipNum", required = false) String equipNum,
                                                                     @RequestParam(value = "stationId", required = false) String stationId) {
        StationBasic stationBasic = stationBasicMapper.selectById(stationId);
        String gatewayId = stationBasic.getFanGatewayId();
        return ResponseHelper.buildResponse(monitorFanIndicator.getEquipInfoByEquipNum(gatewayId, equipNum));
    }


    @TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "光伏左侧资源树")
    @GetMapping("/getEquipTree")
    public ResponseModel<IPage<Map<String, Object>>> getEquipTree(@RequestParam(value = "stationId", required = false) String stationId,
                                                                  @RequestParam(value = "frontModule", required = false) String frontModule,
                                                                  @RequestParam(value = "equipmentNumber", required = false) String equipmentNumber
    ) {
        StationBasic stationBasic = stationBasicMapper.selectById(stationId);
        String gatewayId = stationBasic.getFanGatewayId();
        List<Map<String, Object>> equipmentNum = monitorFanIndicator.getEquipmentNum(gatewayId, frontModule, equipmentNumber);
        IPage<Map<String, Object>> result = new Page<>();
        result.setRecords(equipmentNum);
        result.setCurrent(1);
        result.setTotal(equipmentNum.size());
        return ResponseHelper.buildResponse(result);
    }


    @TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "详情基础信息")
    @GetMapping("/getStatisticsInfo")
    public ResponseModel<Map<String, Object>> getStatisticsInfo(@RequestParam(value = "equipmentIndexName", required = false) String equipmentIndexName,
                                                                @RequestParam(value = "stationId", required = false) String stationId,
                                                                @RequestParam(value = "stationType", required = false) String stationType) {
//        StationBasic stationBasic = stationBasicMapper.selectById(stationId);
//        String gatewayId = stationBasic.getFanGatewayId();
//        if (null != stationType){
//            gatewayId = stationBasic.getBoosterGatewayId();
//        }
        return ResponseHelper.buildResponse(monitorFanIndicator.getStatisticsInfo(equipmentIndexName, stationId));
    }

    @TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "码速表")
    @GetMapping("/SpeedIndicator")
    public ResponseModel<Map<String, Object>> SpeedIndicator(@RequestParam(value = "equipNum", required = false) String equipNum,
                                                             @RequestParam(value = "stationId", required = false) String stationId,
                                                             @RequestParam(value = "equipmentIndexName", required = false) String equipmentIndexName
    ) {
        StationBasic stationBasic = stationBasicMapper.selectById(stationId);
        String gatewayId = stationBasic.getFanGatewayId();
        return ResponseHelper.buildResponse(monitorFanIndicator.SpeedIndicator(gatewayId, equipNum, equipmentIndexName));
    }

    @TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "箱变实时开关状态")
    @GetMapping("/equipSwitchStatus")
    @Scheduled(cron = "0/10 * * * * ? ")
    public ResponseModel<Map<String, Object>> getEquipSwitchStatus() {


        LambdaQueryWrapper<StationBasic> wrapper = new LambdaQueryWrapper<>();
        List<StationBasic> stationBasics = stationBasicMapper.selectList(wrapper);
        for (StationBasic stationBasic : stationBasics) {
            String fanGatewayId = stationBasic.getFanGatewayId();
            monitorFanIndicatorImpl.getEquipSwitchStatus(stationBasic);
        }

        return CommonResponseUtil.success();
    }

    @TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "汇流箱支路电流离散率")
    @GetMapping("/collectingBox")
    public ResponseModel<ResultsData> collectingBox(@RequestParam(value = "current") int current,
                                                    @RequestParam(value = "size") int size,
                                                    @RequestParam(value = "stationId") String stationId) {

        StationBasic stationBasic = stationBasicMapper.selectById(stationId);
        String gatewayId = stationBasic.getFanGatewayId();
        return ResponseHelper.buildResponse(monitorFanIndicatorImpl.collectingBox(gatewayId, current, size));
    }

	@TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
	@ApiOperation(value = "汇流箱支路电流偏差率")
	@GetMapping("/getDeaviAtionRate")
	public ResponseModel<ResultsData> getDeaviAtionRate(@RequestParam(value = "stationId") String stationId,
			@RequestParam(value = "zz") String zz, @RequestParam(value = "nbq") String nbq,
			@RequestParam(value = "hlx") String hlx) {
		StationBasic stationBasic = stationBasicMapper.selectById(stationId);
		String gatewayId = stationBasic.getFanGatewayId();
		return ResponseHelper.buildResponse(monitorFanIndicatorImpl.getDeaviAtionRate(gatewayId, zz, nbq, hlx));
	}


    @TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "光伏 运行列表")
    @GetMapping("/solarPowerOperation")
    public ResponseModel<IPage<Map<String, Object>>> solarPowerOperation(@RequestParam(value = "stationId") String stationId, @RequestParam(value = "current") int current, int size) {
        StationBasic stationBasic = stationBasicMapper.selectById(stationId);
        String gatewayId = stationBasic.getFanGatewayId();

        List<Map<String, Object>> statusMonitoring = monitorFanIndicator.solarPowerOperation(gatewayId);
        List<Map<String, Object>> collect = statusMonitoring.stream()
                .sorted(Comparator.comparing(t -> Integer.parseInt(t.get("sort").toString())))
                .skip((long) (current - 1) * size)
                .limit(size)
                .collect(Collectors.toList());
        IPage<Map<String, Object>> result = new Page<>();
        result.setRecords(collect);
        result.setCurrent(current);
        result.setTotal(statusMonitoring.size());
        return ResponseHelper.buildResponse(result);
    }


    @TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "汇流箱 功率曲线")
    @GetMapping("/hlWindSpeeds")
    public ResponseModel<Map<String, Object>> hlWindSpeeds(@RequestParam(value = "stationId") String stationId, @RequestParam(value = "equipNum") String equipNum) {
        StationBasic stationBasic = stationBasicMapper.selectById(stationId);
        String gatewayId = stationBasic.getFanGatewayId();

        Map<String, Object> result = monitorFanIndicator.hlWindSpeeds(gatewayId, equipNum);

        return ResponseHelper.buildResponse(result);
    }

    @TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "集电线路图右侧 光伏列表")
    @GetMapping("/gfList")
    @Scheduled(cron = "0/10 * * * * ? ")
    public ResponseModel getListByNbq() {


        LambdaQueryWrapper<StationBasic> wrapper = new LambdaQueryWrapper<>();
        List<StationBasic> stationBasics = stationBasicMapper.selectList(wrapper);
        for (StationBasic stationBasic : stationBasics) {
            String gatewayId = stationBasic.getFanGatewayId();
            String werks = stationBasic.getStationNumber();
            if (!stationBasic.getStationType().equals("FDZ")) {
                monitorFanIndicator.getListByNbq(gatewayId, werks, stationBasic.getSequenceNbr().toString());
            }
        }


        return CommonResponseUtil.success();
    }


    @TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "风机-三维告警")
    @GetMapping("/partofWaring3D")
    public ResponseModel<Map<String, Object>> partofWaring3D(@RequestParam(value = "stationId") String stationId, @RequestParam(value = "equipNum") String equipNum) {
        Map<String, Object> result = monitorFanIndicator.partofWaring3D(stationId, equipNum);
        return ResponseHelper.buildResponse(result);
    }

    @TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "逆变器状态数量")
    @GetMapping("/nbqStatus")
    public ResponseModel<Page<Map<String, Object>>> nbqStatus(@RequestParam("stationId") String stationId) {
        StationBasic stationBasic = stationBasicMapper.selectById(stationId);
        Page<Map<String, Object>> result = monitorFanIndicator.nbqStatus(stationBasic.getFanGatewayId());
        return ResponseHelper.buildResponse(result);
    }

    @TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "实时告警")
    @GetMapping("/getEventByEquipIndex")
    public ResponseModel<ResultsData> getEventByEquipIndex(@RequestParam(value = "current") int current,
                                                           @RequestParam(value = "size") int size,
                                                           @RequestParam(value = "stationId") String stationId,
                                                           @RequestParam(value = "equipIndex", required = false) String equipIndex,
                                                           @RequestParam(value = "frontModule", required = false) String frontModule) {
        StationBasic stationBasic = stationBasicMapper.selectById(stationId);
        String gatewayId = stationBasic.getFanGatewayId();
        ResultsData resultsData = equipAlarmEventService.getEventByEquipIndex(gatewayId, current, size, equipIndex, frontModule);
        return ResponseHelper.buildResponse(resultsData);
    }
}
