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

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
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.module.common.biz.utils.CommonResponseUtil;
import com.yeejoin.amos.boot.module.jxiop.api.Enum.GeneratingCapacity;
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.entity.StationPlan;
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.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.ResultsData;
import com.yeejoin.amos.boot.module.jxiop.biz.dto.StationCacheInfoDto;
import com.yeejoin.amos.boot.module.jxiop.biz.service.MonitorService;
import com.yeejoin.amos.boot.module.jxiop.biz.service.impl.CommonServiceImpl;
import com.yeejoin.amos.boot.module.jxiop.biz.service.impl.MonitorFanIndicatorImpl;
import com.yeejoin.amos.boot.module.jxiop.biz.service.impl.MonitoringServiceImpl;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.io.IOUtils;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.MatchPhraseQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.util.ObjectUtils;
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.io.IOException;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

import static com.alibaba.fastjson.JSON.parseArray;

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

    private final String NFDL = "年发电量";
    @Autowired
    MonitorFanIndicatorImpl monitorFanIndicatorImpl;
    @Autowired
    CommonServiceImpl commonServiceImpl;
    @Autowired
    MonitorFanIndicatorImpl monitorFanIndicator;
    @Autowired
    StationBasicMapper stationBasicMapper;
    @Autowired
    MonitorFanIndicatorMapper monitorFanIndicatorMapper;
    @Autowired
    EmqKeeper emqKeeper;
    @Autowired
    MonitoringServiceImpl monitoringService;
    @Autowired
    MonitorService monitorService;
    @Autowired
    StationPlanMapper StationPlanMapper;
    @Autowired
    private ElasticsearchRestTemplate elasticsearchTemplate;
    @Value("classpath:/json/overview.json")
    private Resource overview;
    @Value("classpath:/json/overviewGF.json")
    private Resource overviewGF;
    @Value("${fan.statuts.stattuspath}")
    private String fanStatusImagePathPrefix;

//    @TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
//    @ApiOperation(value = "根据设备编号、场站id、前段展示模块、系统类型查询表数据")
//    @GetMapping("/getFanIdxInfoByPage")
//    public ResponseModel<IPage<IndexDto>> 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));
//    }

    public static List<Map<String, Object>> sortByFeild(List<Map<String, Object>> list, String feild) {
        if (CollectionUtils.isNotEmpty(list)) {

            Collections.sort(list, (m1, m2) -> Integer.valueOf(m1.get(feild).toString()).compareTo(Integer.valueOf(m2.get(feild).toString())));
        }

        return list;
    }

    public static List<Map<String, Object>> sortByFeildString(List<Map<String, Object>> list, String feild) {
        if (CollectionUtils.isNotEmpty(list)) {

            Collections.sort(list, (m1, m2) -> String.valueOf(m1.get(feild).toString()).compareTo(String.valueOf(m2.get(feild).toString())));
        }

        return list;
    }


//    @TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
//    @ApiOperation(value = "风机布置图 - 风机状态列表")
//    @GetMapping("/getFanStatusList")
//    public ResponseModel<IPage<IndexDto>> getFanStatusList(@RequestParam(value = "stationId", required = false) String stationId,
//                                                           @RequestParam(value = "current", required = false) int current,
//                                                           @RequestParam(value = "size", required = false) int size) {
//        List<IndexDto> fanStatusList = monitorFanIndicator.getFanStatusList(stationId);
//        Page<IndexDto> page = new Page<>(current, size);
//        List<IndexDto> collect = fanStatusList.stream()
//                .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() {
//        List<IndexDto> fanStatusList = monitorFanIndicator.getFanStatusList("1660231556607774721");
//        List<IndexDto> collect = fanStatusList.stream()
//                .limit(999)
//                .collect(Collectors.toList());
//        IPage<HashMap<String,String>> page = new Page<>();
//        HashMap<String,String> hashMap = new HashMap<>();
//        List<IndexDto> indexDtoList = collect.stream().sorted(Comparator.comparing(IndexDto::getEquipmentNumber)).collect(Collectors.toList());
//        for (int i = 1; i <= indexDtoList.size(); i++) {
//            IndexDto indexDto =  indexDtoList.get(i-1);
//            hashMap.put("url"+i,fanStatusImagePathPrefix+"/"+"风机-"+indexDto.getState()+".gif");
//            hashMap.put("name"+i,indexDto.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 = "左侧树API")
    @GetMapping("/getTreeInfo")
    public ResponseModel<TreeDto> getTreeInfo(@RequestParam(value = "sequenceNbr") String sequenceNbr) {
        return ResponseHelper.buildResponse(monitorFanIndicator.getTreeInfo(sequenceNbr));
    }

//    @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("/getBasicInfonew")
    public ResponseModel<Map<String, Object>> getBasicInfonew(@RequestParam(value = "stationId") String stationId) {
        List<Map<String, String>> list = new ArrayList<>();
        StationBasic stationBasic = stationBasicMapper.selectById(stationId);
        Map<String, String> date = monitoringService.getStationfs(stationBasic);
        Map<String, String> date1 = monitoringService.getStationrl(stationBasic);
        list.add(date);
        list.add(date1);
        Map<String, Object> queryCondtion = new HashMap<>();
        queryCondtion.put("color", stationBasic.getQrcodeColor());
        queryCondtion.put("data", list);
        return ResponseHelper.buildResponse(queryCondtion);
    }

    @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("/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);
//        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);
//            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(),0,false);
//            } 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("/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 ("夏造风电站".equals(stationBasic.getStationName())) {
//            monitorFanIndicator.getMajorAnalogQuantityByPage(gatewayId, stationBasic.getSequenceNbr().toString());
//        } else if ("泰和前进光伏站".equals(stationBasic.getStationName())) {
//            monitorFanIndicator.getMajorAnalogQuantityByPageByTHGF(gatewayId, stationBasic.getSequenceNbr().toString());
//        }
//        return CommonResponseUtil.success();
//    }

    @TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "全国风机-总概览")
    @GetMapping("/overview")
    public ResponseModel<IPage<Map>> 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 = commonServiceImpl.getTotalByIndicatior(gatewayId, column);
            columnMap.put(column, String.format("%.2f", result));
        }
        for (String column : columnLists) {
//            Double result = commonServiceImpl.getAvgvalueByIndicatior(gatewayId, column);

            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(column, String.format("%.2f", 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 = commonServiceImpl.getListDataByCondtions(queryCondtion1, null, ESEquipments.class);
        columnMap.put("有功功率", String.format("%.2f", result1.get(0).getValueF()));

        //String num = monitorFanIndicator.getFJCount(gatewayId);
        String num = monitorFanIndicator.getEquipCount(gatewayId, "FDZ");
        columnMap.put("风机台数", num);
        columnMap.put("风机台数", Double.valueOf(num).intValue());

        Double capacityl = commonServiceImpl.getStationCapactityByStationWerks(stationBasic.getStationNumber());
        columnMap.put("装机容量", String.format("%.2f", capacityl));

        SimpleDateFormat myFmt2 = new SimpleDateFormat("yyyy");
        String monthy = myFmt2.format(new Date());
        QueryWrapper<StationPlan> wrapper = new QueryWrapper<>();
        wrapper.select("sum(value) as value ,monthly");
        wrapper.eq("year", monthy);
        wrapper.eq("station_basic_id", stationBasic.getSequenceNbr());
        wrapper.groupBy("monthly");
        List<Map<String, Object>> list1 = StationPlanMapper.selectMaps(wrapper);
        Double sumValue = list1 != null && !list1.isEmpty() ? (Double) list1.get(0).get("value") : 0;

        columnMap.put("年发电量完成率(%)", String.format("%.2f", Double.parseDouble(columnMap.get("年发电量").toString()) / sumValue * 100));

//        StationBasic stationBasic = stationBasicMapper.selectById(stationId);
//        String gatewayId = stationBasic.getFanGatewayId();
//        String [] columnList = new String[]{"日发电量","月发电量","年发电量"};
//        String [] columnLists = new String[]{"有功功率","瞬时风速"};
//        Map<String, Object> columnMap = new HashMap<>();
//
//        for (String column : columnList) {
//            Double result = commonServiceImpl.getTotalByIndicatior(gatewayId, column);
//            columnMap.put(column, String.format("%.2f",result));
//        }
//        for (String column : columnLists) {
//            Double result = commonServiceImpl.getAvgvalueByIndicatior(gatewayId, column);
//            columnMap.put(column, String.format("%.2f",result));
//        }
//
//        String num = monitorFanIndicator.getFJCount(gatewayId);
//
//
//        Double capacityl = commonServiceImpl.getStationCapactityByStationWerks(stationBasic.getStationNumber());
//        columnMap.put("装机容量",String.format("%.2f",capacityl));

        String json = null;
        try {
            json = IOUtils.toString(overview.getInputStream(), java.lang.String.valueOf(StandardCharsets.UTF_8));
        } catch (IOException e) {
            e.printStackTrace();
        }
        List<Map> list = parseArray(json, Map.class);
        for (Map map : list) {
            String key = map.get("title").toString();
            map.put("title", columnMap.get(key) == null ? 0.00 : columnMap.get(key));
            map.put("title2", map.get("title"));
            if (map.containsKey("action")) {
                if (key.equals("日利用小时(h)")) {
                    String format = String.format("%.2f", ((Double.parseDouble(columnMap.get("日发电量").toString()) * 10) / (Double.parseDouble(columnMap.get("装机容量").toString()))));
                    map.put("title", format);
                    map.put("title2", map.get("title"));
                } else {
                    map.put("title", String.format("%.2f", Double.parseDouble(columnMap.get(key).toString()) / 1000));
                    map.put("title2", map.get("title"));
                }
            }

        }

        IPage<Map> result = new Page<>();
        result.setRecords(list);
        result.setCurrent(1);
        result.setTotal(list.size());

        return ResponseHelper.buildResponse(result);
    }


//    @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, gatewayId,stationType);
//        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").equals("1主变高压侧") || map.get("text").equals("1主变低压侧") ?map.get("text").substring(0,3):map.get("text");
//
//
//        Map<String, Object> switchUrl = monitorFanIndicatorImpl.getSwitchUrl(gatewayId, name);
//        List<Map<String, Object>> statusMonitoring = monitorFanIndicator.getStatusGzp(gatewayId ,"网络",name,null);
//        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(),0,false);
//        } 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("/overviewWindSpeed")
    public ResponseModel<Map<String, Object>> getOverviewWindSpeed(@RequestParam(value = "stationId", required = false) String stationId, @RequestParam(value = "type", required = false) String type
            , @RequestParam(value = "areaCode", required = false) String areaCode) {
        String gatewayId = "";
        String paramId = "";
        List<String> ids = new ArrayList<>();
        List<StationCacheInfoDto> listStationCacheInfoDto = commonServiceImpl.getListStationCacheInfoDto();
        double installedCapacity = listStationCacheInfoDto.stream().mapToDouble(t -> Double.parseDouble(t.getInstalledCapacity())).sum();
        if (null != areaCode) {
            List<String> collect = listStationCacheInfoDto.stream().filter(e -> e.getAreaCode().equals(areaCode)).map(StationCacheInfoDto::getFanGatewayId).collect(Collectors.toList());
            ids = listStationCacheInfoDto.stream().filter(e -> e.getAreaCode().equals(areaCode)).map(StationCacheInfoDto::getBoosterGatewayId).collect(Collectors.toList());
            installedCapacity = listStationCacheInfoDto.stream().filter(e -> e.getAreaCode().equals(areaCode)).mapToDouble(t -> Double.parseDouble(t.getInstalledCapacity())).sum();
            gatewayId = String.join(",", collect);
        }
        if (null != stationId) {
            StationBasic stationBasic = stationBasicMapper.selectById(stationId);
            gatewayId = stationBasic.getBoosterGatewayId();
            if (null == type) {
                gatewayId = stationBasic.getFanGatewayId();
            }
            installedCapacity = listStationCacheInfoDto.stream().filter(e -> e.getStationId().equals(stationId)).mapToDouble(t -> Double.parseDouble(t.getInstalledCapacity())).sum();
        }
        Map<String, Object> detailsWindSpeed = monitorFanIndicator.getDetailsWindSpeedAll(gatewayId, installedCapacity, ids);

        return ResponseHelper.buildResponse(detailsWindSpeed);
    }


//    @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 = "故障记录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();
            resultsData = monitorFanIndicatorImpl.getNationWideInfo(current, size, fanGatewayId, null);

        }
        return ResponseHelper.buildResponse(resultsData);
    }

//    @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("/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()
//                .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();
//            monitorFanIndicator.getListByNbq(gatewayId,werks,stationBasic.getSequenceNbr().toString());
//        }
//
//
//        return CommonResponseUtil.success();
//    }

//
//    @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("/solarPowerOverview")
    public ResponseModel<IPage<Map>> solarPowerData(@RequestParam(value = "stationId") String stationId) {


        StationBasic stationBasic = stationBasicMapper.selectById(stationId);
        String gatewayId = stationBasic.getFanGatewayId();
        String boosterGatewayId = stationBasic.getBoosterGatewayId();
        String[] columnList = new String[]{"日发电量", "月发电量", "年发电量"};
        String[] columnLists = new String[]{"有功功率"};
        Map<String, Object> columnMap = new HashMap<>();
        //日 月 年发电量同仅统计逆变器数据
        List<Map<String, Object>> mapList;

        for (String column : columnList) {
            Double result = commonServiceImpl.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 = commonServiceImpl.getListDataByCondtions(queryCondtion, null, ESEquipments.class);
        columnMap.put("有功功率", String.format("%.2f", commonServiceImpl.getSumByEquipmentIndxName(result1, "南瑞光差保护_313P") * CommonConstans.kwToMv));

        String num = monitorFanIndicator.getEquipCount(gatewayId, "GF");
        columnMap.put("逆变器台数", num);
        Double capacityl = commonServiceImpl.getStationCapactityByStationWerks(stationBasic.getStationNumber());
        columnMap.put("装机容量", String.format("%.2f", capacityl));
        columnMap.put("辐照强度", String.format("%.2f", commonServiceImpl.getSumByEquipmentIndxName(result1, "WTX-801_25_WTX-801_总辐射")));


        SimpleDateFormat myFmt2 = new SimpleDateFormat("yyyy");
        String monthy = myFmt2.format(new Date());
        QueryWrapper<StationPlan> wrapper = new QueryWrapper<>();
        wrapper.select(" monthly ,sum(value) as data_value ");
        wrapper.eq("year", monthy);
        wrapper.eq("station_basic_id", stationBasic.getSequenceNbr());
        wrapper.groupBy("monthly");
        List<Map<String, Object>> list1 = StationPlanMapper.selectMaps(wrapper);
        Double sumValue = list1 != null && !list1.isEmpty() ? (Double) list1.get(0).get("data_value") : 0;

        columnMap.put("年发电量完成率(%)", String.format("%.2f", Double.parseDouble(columnMap.get("年发电量").toString()) / sumValue * 100));


        columnMap.put("总辐射累计", String.format("%.2f", commonServiceImpl.getSumByEquipmentIndxName(result1, "WTX-801_25_WTX-801_总辐射累计")));


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


        String json = null;
        try {
            json = IOUtils.toString(overviewGF.getInputStream(), java.lang.String.valueOf(StandardCharsets.UTF_8));
        } catch (IOException e) {
            e.printStackTrace();
        }
        List<Map> list = parseArray(json, Map.class);
        for (Map map : list) {
            String key = map.get("title").toString();
            if (map.containsKey("action")) {
                if (key.equals("日利用小时(h)")) {
                    map.put("title", String.format("%.2f", ((Double.parseDouble(columnMap.get("日发电量").toString()) * CommonConstans.wkwhToMv) / (Double.parseDouble(columnMap.get("装机容量").toString())))));
                    columnMap.put("日利用小时(h)", map.get("title"));
                    map.put("title2", map.get("title"));
                } else {
                    map.put("title", map.get("action").toString().replace("*", columnMap.get(key).toString()));
                    map.put("title2", map.get("title"));
                }
            }
            map.put("title", columnMap.get(key) == null ? 0.00 : columnMap.get(key));
            map.put("title2", map.get("title"));

        }


//        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("总辐射").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", String.format("%.2f",Double.parseDouble(columnMap.get("有功功率").toString())/1000)) ;
//        objects.add(data6);
//        Map<String, Object> data7 = new HashMap<>();
//        data7.put("title",columnMap.get("日照时数").toString());
//        objects.add(data7);
//        Map<String, Object> data8 = new HashMap<>();
//        data8.put("title",columnMap.get("总辐射累计").toString());
//        objects.add(data8);
//        Map<String, Object> data9 = new HashMap<>();
//        data9.put("title","84.00%");//综合效率
//        objects.add(data9);


        IPage<Map> result = new Page<>();
        result.setRecords(list);
        result.setCurrent(1);
        result.setTotal(list.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) {
        String gatewayId = "";
        if (null != stationId) {
            StationBasic stationBasic = stationBasicMapper.selectById(stationId);
            gatewayId = stationBasic.getFanGatewayId();
            if (null != stationType) {
                gatewayId = stationBasic.getBoosterGatewayId();
            }
        }
        List<StationCacheInfoDto> list = commonServiceImpl.getListStationCacheInfoDto();
        double sum = 0.0;
        sum = list.stream().filter(obj -> !ObjectUtils.isEmpty(obj.getInstalledCapacity())).mapToDouble(l -> Double.parseDouble(l.getInstalledCapacity())).sum();

        Map<String, Object> statisticsInfo = monitorFanIndicator.getStatisticsInfo(gatewayId, equipmentIndexName);
        double v = Double.parseDouble(statisticsInfo.get("mean").toString());
        String load = String.format("%.2f", v / sum);
        statisticsInfo.put("load", load);
        return ResponseHelper.buildResponse(statisticsInfo);
    }

    @ApiOperation(value = "电站排名")
    @Scheduled(cron = "0/10 * * * * ? ")
    @GetMapping("/stationRanking")
    public ResponseModel stationRanking() {
        LambdaQueryWrapper<StationBasic> wrapper = new LambdaQueryWrapper<>();
        List<StationBasic> stationBasics = stationBasicMapper.selectList(wrapper);
        List<Map<String, Object>> datDataFJ = new ArrayList<>();
        List<Map<String, Object>> monthDataFJ = new ArrayList<>();
        List<Map<String, Object>> yearDataFJ = new ArrayList<>();
        List<Map<String, Object>> datDataGF = new ArrayList<>();
        List<Map<String, Object>> monthDataGF = new ArrayList<>();
        List<Map<String, Object>> yearDataGF = new ArrayList<>();
        for (StationBasic stationBasic : stationBasics) {

            String gatewayId = stationBasic.getFanGatewayId();
            String boosterGatewayId = stationBasic.getBoosterGatewayId();
            String querySql = null;
            String name = stationBasic.getStationName();
            if (stationBasic.getStationType().equals("FDZ")) {
                Map<String, Object> map = monitorFanIndicator.generatingCapacity(gatewayId, querySql);
                Map<String, Object> dayMap = new HashMap<>();
                Map<String, Object> monthMap = new HashMap<>();
                Map<String, Object> yearMap = new HashMap<>();
                dayMap.put("name", name);
                dayMap.put("value", map.get("日发电量") == null ? 0 : String.format("%.4f", map.get("日发电量")));
                dayMap.put("gateWayId", stationBasic.getFanGatewayId());
                monthMap.put("name", name);
                monthMap.put("value", map.get("月发电量") == null ? 0 : String.format("%.4f", map.get("月发电量")));
                monthMap.put("gateWayId", stationBasic.getFanGatewayId());
                yearMap.put("name", name);
                yearMap.put("gateWayId", stationBasic.getFanGatewayId());
                yearMap.put("value", map.get("年发电量") == null ? 0 : String.format("%.4f", map.get("年发电量")));
                datDataFJ.add(dayMap);
                monthDataFJ.add(monthMap);
                yearDataFJ.add(yearMap);
            } else {
                querySql = "逆变器";
                Map<String, Object> map = monitorFanIndicator.generatingCapacity(boosterGatewayId, querySql);
                Map<String, Object> dayMap = new HashMap<>();
                Map<String, Object> monthMap = new HashMap<>();
                Map<String, Object> yearMap = new HashMap<>();
                dayMap.put("name", name);
                dayMap.put("gateWayId", stationBasic.getFanGatewayId());
                dayMap.put("value", map.get("日发电量") == null ? 0 : String.format("%.4f", Double.parseDouble(map.get("日发电量").toString())));
                monthMap.put("name", name);
                monthMap.put("gateWayId", stationBasic.getFanGatewayId());
                monthMap.put("value", map.get("月发电量") == null ? 0 : String.format("%.4f", Double.parseDouble(map.get("月发电量").toString())));
                yearMap.put("name", name);
                yearMap.put("gateWayId", stationBasic.getFanGatewayId());
                yearMap.put("value", map.get("年发电量") == null ? 0 : String.format("%.4f", Double.parseDouble(map.get("年发电量").toString())));
                datDataGF.add(dayMap);
                monthDataGF.add(monthMap);
                yearDataGF.add(yearMap);
            }
        }
        monitorFanIndicator.sendMqttByRanking(datDataFJ, GeneratingCapacity.DAY.getCode(), "fjpm");
        monitorFanIndicator.sendMqttByRanking(monthDataFJ, GeneratingCapacity.MONTH.getCode(), "fjpm");
        monitorFanIndicator.sendMqttByRanking(yearDataFJ, GeneratingCapacity.YEAR.getCode(), "fjpm");
        monitorFanIndicator.sendMqttByRanking(datDataGF, GeneratingCapacity.DAY.getCode(), "gfpm");
        monitorFanIndicator.sendMqttByRanking(monthDataGF, GeneratingCapacity.MONTH.getCode(), "gfpm");
        monitorFanIndicator.sendMqttByRanking(yearDataGF, GeneratingCapacity.YEAR.getCode(), "gfpm");
        return CommonResponseUtil.success();
    }

    @TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "电站排名")
    @GetMapping("/stationRankingtype")
    public ResponseModel stationRanking(String day, String type, String areaCode) {


//        LambdaQueryWrapper<StationBasic> wrapper = new LambdaQueryWrapper<>();
//
//        wrapper.eq(areaCode!=null,StationBasic::getAreaCode,areaCode);
//
//        List<StationBasic> stationBasics = stationBasicMapper.selectList(wrapper);
//
//
//
//        List<Map<String, Object>> datDataFJ = new ArrayList<>();
//        List<Map<String, Object>> monthDataFJ = new ArrayList<>();
//        List<Map<String, Object>> yearDataFJ = new ArrayList<>();
//        List<Map<String, Object>> datDataGF = new ArrayList<>();
//        List<Map<String, Object>> monthDataGF = new ArrayList<>();
//        List<Map<String, Object>> yearDataGF = new ArrayList<>();
//        for (StationBasic stationBasic : stationBasics) {
//
//            String gatewayId = stationBasic.getFanGatewayId();
//            String boosterGatewayId = stationBasic.getBoosterGatewayId();
//            String querySql = null;
//            String name = stationBasic.getStationName();
//            if (stationBasic.getStationType().equals("FDZ")) {
//                Map<String, Object> map = monitorFanIndicator.generatingCapacity(gatewayId, querySql);
//                Map<String, Object> dayMap = new HashMap<>();
//                Map<String, Object> monthMap = new HashMap<>();
//                Map<String, Object> yearMap = new HashMap<>();
//                dayMap.put("name", name);
//                dayMap.put("value", map.get("日发电量") == null ? 0 : String.format("%.4f", map.get("日发电量")));
//                dayMap.put("gateWayId", stationBasic.getFanGatewayId());
//                monthMap.put("name", name);
//                monthMap.put("value", map.get("月发电量") == null ? 0 : String.format("%.4f", map.get("月发电量")));
//                monthMap.put("gateWayId", stationBasic.getFanGatewayId());
//                yearMap.put("name", name);
//                yearMap.put("gateWayId", stationBasic.getFanGatewayId());
//                yearMap.put("value", map.get("年发电量") == null ? 0 : String.format("%.4f", map.get("年发电量")));
//                datDataFJ.add(dayMap);
//                monthDataFJ.add(monthMap);
//                yearDataFJ.add(yearMap);
//            } else {
//                querySql = "逆变器";
//                Map<String, Object> map = monitorFanIndicator.generatingCapacity(boosterGatewayId, querySql);
//                Map<String, Object> dayMap = new HashMap<>();
//                Map<String, Object> monthMap = new HashMap<>();
//                Map<String, Object> yearMap = new HashMap<>();
//                dayMap.put("name", name);
//                dayMap.put("gateWayId", stationBasic.getFanGatewayId());
//                dayMap.put("value", map.get("日发电量") == null ? 0 : String.format("%.4f", Double.parseDouble(map.get("日发电量").toString())));
//                monthMap.put("name", name);
//                monthMap.put("gateWayId", stationBasic.getFanGatewayId());
//                monthMap.put("value", map.get("月发电量") == null ? 0 : String.format("%.4f", Double.parseDouble(map.get("月发电量").toString())));
//                yearMap.put("name", name);
//                yearMap.put("gateWayId", stationBasic.getFanGatewayId());
//                yearMap.put("value", map.get("年发电量") == null ? 0 : String.format("%.4f", Double.parseDouble(map.get("年发电量").toString())));
//                datDataGF.add(dayMap);
//                monthDataGF.add(monthMap);
//                yearDataGF.add(yearMap);
//            }
//        }
////        monitorFanIndicator.sendMqttByRanking(datDataFJ, GeneratingCapacity.DAY.getCode(), "fjpm");
////        monitorFanIndicator.sendMqttByRanking(monthDataFJ, GeneratingCapacity.MONTH.getCode(), "fjpm");
////        monitorFanIndicator.sendMqttByRanking(yearDataFJ, GeneratingCapacity.YEAR.getCode(), "fjpm");
////        monitorFanIndicator.sendMqttByRanking(datDataGF, GeneratingCapacity.DAY.getCode(), "gfpm");
////        monitorFanIndicator.sendMqttByRanking(monthDataGF, GeneratingCapacity.MONTH.getCode(), "gfpm");
////        monitorFanIndicator.sendMqttByRanking(yearDataGF, GeneratingCapacity.YEAR.getCode(), "gfpm");
//        Page<Map<String, Object>> socialContributionDtoPage = new Page<Map<String, Object>>();
//        socialContributionDtoPage.setCurrent(1);
//        socialContributionDtoPage.setTotal(100);
//
//      if("gf".equals(type)){
//          if("0".equals(day)){
//
//
//              socialContributionDtoPage.setRecords(datDataGF);
//
//          }else  if("1".equals(day)){
//              socialContributionDtoPage.setRecords(monthDataGF);
//          } else if("2".equals(day)){
//              socialContributionDtoPage.setRecords(yearDataGF);
//          }
//      }else{
//          if("0".equals(day)){
//              socialContributionDtoPage.setRecords(datDataFJ);
//
//          }else  if("1".equals(day)){
//              socialContributionDtoPage.setRecords(monthDataFJ);
//
//          } else if("2".equals(day)){
//              socialContributionDtoPage.setRecords(yearDataFJ);
//
//          }
//      }


        return CommonResponseUtil.success(monitorService.stationRanking(day, type, areaCode));


    }

    @TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "运维数据 ")
    @GetMapping("/operationData")
    public ResponseModel<IPage<Map<String, Object>>> operationData(@RequestParam(value = "areaCode", required = false) String areaCode,
                                                                   @RequestParam(value = "platformStationId", required = false) String platformStationId) {


//        List<StationCacheInfoDto> list = commonServiceImpl.getListStationCacheInfoDto();
//        if (null != areaCode) {
//            list = list.stream().filter(e -> e.getAreaCode().toUpperCase(Locale.ROOT).equals(areaCode.toUpperCase(Locale.ROOT))).collect(Collectors.toList());
//        }
//        List<Map<String, Object>> mapList = new ArrayList<>();
//        Map<String, List<StationCacheInfoDto>> listMap = list.stream().collect(Collectors.groupingBy(StationCacheInfoDto::getStationType, Collectors.toList()));
//
//
//        for (StationType value : StationType.values()) {
//            Map<String, Object> map = new LinkedHashMap<>();
//            List<StationCacheInfoDto> dtos = listMap.get(value.getCode());
//            map.put("data", dtos == null ? 0 : dtos.size());
//            map.put("title", dtos == null ? 0 : dtos.stream().filter(obj -> !ObjectUtils.isEmpty(obj.getInstalledCapacity())).mapToDouble(l -> Double.parseDouble(l.getInstalledCapacity())).sum());
//            mapList.add(map);
//        }
//
//
//        IPage<Map<String, Object>> result = new Page<>();
//        result.setRecords(mapList);
//        result.setCurrent(1);
//        result.setTotal(mapList.size());
        return ResponseHelper.buildResponse(monitorService.operationData(areaCode,platformStationId));
    }
    @TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "全国新能源接入情况 ")
    @GetMapping("/getAccessSituation")
    public ResponseModel<Map<String, Object>> getAccessSituation(@RequestParam(value = "areaCode", required = false) String areaCode,
                                                                 @RequestParam(value = "platformStationId", required = false) String platformStationId) {
        return ResponseHelper.buildResponse(monitorService.getAccessSituation(areaCode,platformStationId));
    }

    @TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "社会贡献 ")
    @GetMapping("/SocialContribution")
    public ResponseModel<Page<HashMap<String, String>>> socialContribution(String areaCode) {
//        Page<HashMap<String, String>> page3 = new Page<>(1, 10);
//        List<String> value = new ArrayList<>();
//        value.add(NFDL);
//        Map<String, List<String>> map = new HashMap<>();
//        map.put("equipmentIndexName.keyword", value);
//        List<StationCacheInfoDto> stationBasicListAll = new ArrayList<>();
//        if (null != areaCode) {
//            stationBasicListAll = commonServiceImpl.getListStationCacheInfoDto();
//            List<String> collect = stationBasicListAll.stream().filter(e -> e.getAreaCode().equals(areaCode)).map(StationCacheInfoDto::getFanGatewayId).collect(Collectors.toList());
//            map.put("gatewayId.keyword", collect);
//        }
//        List<StationCacheInfoDto> fdzList = stationBasicListAll.stream().filter(stationBasic -> stationBasic.getStationType().equals("FDZ")).collect(Collectors.toList());
//        List<StationCacheInfoDto> gfList = stationBasicListAll.stream().filter(stationBasic -> !stationBasic.getStationType().equals("FDZ")).collect(Collectors.toList());
//        List<HashMap<String, String>> list1 = new ArrayList<>();
//        List<HashMap<String, String>> list2 = new ArrayList<>();
//        List<HashMap<String, String>> list3 = new ArrayList<>();
//        AtomicReference<Double> powerOfDayFD = new AtomicReference<>(new Double(0.00));
//        AtomicReference<Double> powerOfMonthFD = new AtomicReference<>(new Double(0.00));
//        AtomicReference<Double> powerOfAnnualFD = new AtomicReference<>(new Double(0.00));
//        AtomicReference<Double> powerOfDayGF = new AtomicReference<>(new Double(0.00));
//        AtomicReference<Double> powerOfMonthGF = new AtomicReference<>(new Double(0.00));
//        AtomicReference<Double> powerOfAnnualGF = new AtomicReference<>(new Double(0.00));
//        fdzList.forEach(stationBasic -> {
//            Map<String, List<String>> queryCondtion = new HashMap<>();
//            queryCondtion.put(CommonConstans.QueryStringEquipmentIndexName, Arrays.asList("日发电量", "月发电量", "年发电量"));
//            queryCondtion.put(CommonConstans.QueryStringGateWayId, Arrays.asList(stationBasic.getFanGatewayId()));
//            List<ESEquipments> result = commonServiceImpl.getListDataByCondtions(queryCondtion, null, ESEquipments.class);
//            powerOfDayFD.updateAndGet(v -> v + commonServiceImpl.getSumByEquipmentIndxName(result, "日发电量"));
//            powerOfMonthFD.updateAndGet(v -> v + commonServiceImpl.getSumByEquipmentIndxName(result, "月发电量"));
//            powerOfAnnualFD.updateAndGet(v -> v + commonServiceImpl.getSumByEquipmentIndxName(result, "年发电量"));
//        });
//        gfList.forEach(stationBasic -> {
//            Map<String, List<String>> queryCondtion = new HashMap<>();
//            queryCondtion.put(CommonConstans.QueryStringEquipmentIndexName, CommonConstans.taiHeGenIndicator);
//            queryCondtion.put(CommonConstans.QueryStringGateWayId, Arrays.asList(stationBasic.getBoosterGatewayId()));
//            List<ESEquipments> result = commonServiceImpl.getListDataByCondtions(queryCondtion, null, ESEquipments.class);
//            powerOfDayGF.updateAndGet(v -> v + commonServiceImpl.getSumByEquipmentIndxName(result, CommonConstans.taiHeGenIndicatorDay));
//            powerOfMonthGF.updateAndGet(v -> v + commonServiceImpl.getSumByEquipmentIndxName(result, CommonConstans.taiHeGenIndicatorMonth));
//            powerOfAnnualGF.updateAndGet(v -> v + commonServiceImpl.getSumByEquipmentIndxName(result, CommonConstans.taiHeGenIndicatorYear));
//        });
//        Double totalAnnual = (powerOfAnnualFD.get() + powerOfAnnualGF.get());
//        HashMap<String, String> stringHashMap13 = new HashMap<>();
//        stringHashMap13.put("title", String.format(CommonConstans.Twodecimalplaces, (totalAnnual * CommonConstans.carbonDioxide )));
//        stringHashMap13.put("unit", "二氧化碳减排量（t）");
//        list3.add(stringHashMap13);
//        HashMap<String, String> stringHashMap14 = new HashMap<>();
//        stringHashMap14.put("title", String.format(CommonConstans.Twodecimalplaces, (totalAnnual * CommonConstans.standardCoal )));
//        stringHashMap14.put("unit", "节约标准煤（t）");
//        list3.add(stringHashMap14);
//        HashMap<String, String> stringHashMap15 = new HashMap<>();
//        stringHashMap15.put("title", String.format(CommonConstans.Twodecimalplaces, (totalAnnual * CommonConstans.toner)));
//        stringHashMap15.put("unit", "碳粉尘减排量（t）");
//        list3.add(stringHashMap15);
//        HashMap<String, String> stringHashMap16 = new HashMap<>();
//        stringHashMap16.put("title", String.format(CommonConstans.Twodecimalplaces, (totalAnnual * CommonConstans.sulfurDioxide )));
//        stringHashMap16.put("unit", "二氧化硫减排量（t）");
//        list3.add(stringHashMap16);
//        page3.setRecords(list3);

        return ResponseHelper.buildResponse(monitorService.socialContribution(areaCode));
    }

    @TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "设备发电量 ")
    @GetMapping("/equipGeneratingCapacity")
    public ResponseModel<IPage<Map<String, Object>>> equipGeneratingCapacity(@RequestParam(value = "current") int current,
                                                                             @RequestParam(value = "size") int size,
                                                                             @RequestParam(value = "stationId") String stationId) {
        StationBasic stationBasic = stationBasicMapper.selectById(stationId);
        String gatewayId = stationBasic.getFanGatewayId();


        BoolQueryBuilder boolMustAll = QueryBuilders.boolQuery();
        List<QueryBuilder> should = boolMustAll.should();
        String[] keys = new String[]{"日发电量", "月发电量", "年发电量", "有功功率"};
        List<String> list = Arrays.asList(keys);
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        if (!stationBasic.getStationType().equals("FDZ")) {

            MatchPhraseQueryBuilder queryBuilder1 = QueryBuilders.matchPhraseQuery(CommonConstans.QueryStringFrontMoudleNotKeyWord, "*逆变器*");

            boolQueryBuilder.must((QueryBuilders.termsQuery("equipmentIndexName.keyword", list))

            ).must(QueryBuilders.matchQuery("gatewayId.keyword", stationBasic.getFanGatewayId()));
            boolQueryBuilder.must(queryBuilder1);
        } else {
            boolQueryBuilder.must((QueryBuilders.termsQuery("equipmentIndexName.keyword", list))).must(QueryBuilders.matchQuery("gatewayId.keyword", gatewayId));

        }
        should.add(boolQueryBuilder);

        // 创建查询构造器
        NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder()
                // 分页
                //过滤条件
                .withQuery(boolMustAll);

        List<ESEquipments> equipments = new LinkedList<>();
        long totle = 0;
        try {
            SearchHits<ESEquipments> searchHits = elasticsearchTemplate.search(queryBuilder.build(), ESEquipments.class);

            for (SearchHit searchHit : searchHits.getSearchHits()) {
                JSONObject jsonObject = (JSONObject) JSONObject.toJSON(searchHit.getContent());
                ESEquipments eSAlertCalled = JSONObject.toJavaObject(jsonObject, ESEquipments.class);
                equipments.add(eSAlertCalled);
            }
            totle = searchHits.getTotalHits();
        } catch (Exception e) {
            // TODO: handle exception
        }
        List<Map<String, Object>> esEquipmentsMap = new ArrayList<>();
        Map<String, List<ESEquipments>> resultMap = equipments.stream().collect(Collectors.groupingBy(ESEquipments::getEquipmentNumber));
        for (String key : resultMap.keySet()) {
            Map<String, Object> map = new HashMap<>();
            map.put("num", key);
            for (ESEquipments equip : resultMap.get(key)) {
                String value = String.format("%.4f", equip.getValueF());
                if (stationBasic.getStationType().equals("FDZ")) {
                    map.put("name", equip.getEquipmentSpecificName().substring(0, equip.getEquipmentSpecificName().indexOf("#")) + "/" + key);

                } else {
                    map.put("name", key);
                }
                if (!stationBasic.getStationType().equals("FDZ")) {

                    switch (equip.getEquipmentIndexName()) {
                        case "日发电量":
                            map.put("dayNum", String.format(CommonConstans.Fourdecimalplaces, Double.valueOf(value) * CommonConstans.pvGenPoweActor * CommonConstans.pvGenPoweActorDay));
                            break;
                        case "月发电量":
                            map.put("monthNum", String.format(CommonConstans.Fourdecimalplaces, Double.valueOf(value) * CommonConstans.pvGenPoweActorCurrentData));
                            break;
                        case "年发电量":
                            map.put("yearNum", String.format(CommonConstans.Fourdecimalplaces, Double.valueOf(value) * CommonConstans.pvGenPoweActorCurrentData));
                        case "有功功率":
                            map.put("yggl", String.format(CommonConstans.Fourdecimalplaces, Double.valueOf(value)));
                    }

                } else {
                    switch (equip.getEquipmentIndexName()) {
                        case "日发电量":
                            map.put("dayNum", value);
                            break;
                        case "月发电量":
                            map.put("monthNum", value);
                            break;
                        case "年发电量":
                            map.put("yearNum", value);
//                        case CommonConstans.taiHeGenIndicatorDay:
//                            map.put("dayNum", value);
//                            break;
//                        case CommonConstans.taiHeGenIndicatorMonth:
//                            map.put("monthNum", value);
//                            break;
//                        case CommonConstans.taiHeGenIndicatorYear:
//                            map.put("yearNum", value);
//                            break;
                        case "有功功率":
                            map.put("yggl", String.format(CommonConstans.Fourdecimalplaces, Double.valueOf(value)));
                    }
                }

            }
            esEquipmentsMap.add(map);
        }
        if (stationBasic.getStationType().equals("FDZ")) {
            this.sortByFeild(esEquipmentsMap, "num");
        } else {
            this.sortByFeildString(esEquipmentsMap, "num");

        }
        IPage<Map<String, Object>> page = new Page<>();
        page.setTotal(esEquipmentsMap.size());
        page.setSize(999);
        page.setCurrent(1);
        page.setRecords(esEquipmentsMap);

        return ResponseHelper.buildResponse(page);
//        //构建平台数据
//        DataGridMock DataGridMock = new DataGridMock(current, esEquipmentsMap.size(), false, current, esEquipmentsMap);
//        ColModel colModelEquipmentNumber = new ColModel("name", "name", "设备名称", "设备名称", "dataGrid", "name");
//        ColModel colModelPower = new ColModel("dayNum", "dayNum", "日发电量", "日发电量", "dataGrid", "dayNum");
//        ColModel colModelWindSpeed = new ColModel("monthNum", "monthNum", "月发电量", "月发电量", "dataGrid", "monthNum");
//        ColModel colModelWind = new ColModel("yearNum", "yearNum", "年发电量", "年发电量", "dataGrid", "yearNum");
//        List<ColModel> listColModel = Arrays.asList(colModelEquipmentNumber, colModelPower, colModelWindSpeed, colModelWind);
//        ResultsData resultsData = new ResultsData(DataGridMock, listColModel);
//        return ResponseHelper.buildResponse(resultsData);

    }

    //@Scheduled(cron = "0/10 * * * * ? ")
    @TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "测试方法 ")
    @GetMapping("/testaaaa")
    public void mother() {
        //    List<IdxBizUhefDto> data = idxBizUhefMapper.getInfluxDBData();
        //     Map<String, List<IdxBizUhefDto>> maps = data.stream().collect(Collectors.groupingBy(IdxBizUhefDto::getGatewayId));
        BoolQueryBuilder boolMustAll = QueryBuilders.boolQuery();
        Map<String, String> maps = new HashMap<>();
        maps.put("1668801435891929089", "123");
        maps.put("1669524885619085313", "123");

        List<QueryBuilder> should = boolMustAll.should();
        for (String s : maps.keySet()) {
            BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
            //     List<String> address = maps.get(s).stream().map(IdxBizUhefDto::getAddress).collect(Collectors.toList());
            //警情状态
            //       BoolQueryBuilder qb0 = QueryBuilders.boolQuery();
            //    qb0.must((QueryBuilders.termsQuery("address.keyword", address)));
            String[] keys = new String[]{"日发电量", "月发电量", "年发电量"};
            List<String> list = Arrays.asList(keys);
            //      qb0.must((QueryBuilders.termsQuery("equipmentIndexName.keyword", list)));
            //   qb0.must(QueryBuilders.matchQuery("gatewayId.keyword",s));
            //   boolQueryBuilder.must(qb0);

            boolQueryBuilder.must(QueryBuilders.termsQuery("equipmentIndexName.keyword", list)).must(QueryBuilders.matchQuery("gatewayId.keyword", s));
            should.add(boolQueryBuilder);
        }

        // 创建查询构造器
        NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder()
                //过滤条件
                .withQuery(boolMustAll);
        List<ESEquipments> equipments = new LinkedList<>();
        long totle = 0;
        try {
            SearchHits<ESEquipments> searchHits = elasticsearchTemplate.search(queryBuilder.build(), ESEquipments.class);

            for (SearchHit searchHit : searchHits.getSearchHits()) {
                JSONObject jsonObject = (JSONObject) JSONObject.toJSON(searchHit.getContent());
                ESEquipments eSAlertCalled = JSONObject.toJavaObject(jsonObject, ESEquipments.class);
                equipments.add(eSAlertCalled);
            }
            totle = searchHits.getTotalHits();
        } catch (Exception e) {
            // TODO: handle exception
        }

    }

    @TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
    @Scheduled(cron = "0/30 * * * * ? ")
    @ApiOperation(value = "接入情况 ")
    @GetMapping("/accessSituation")
    public ResponseModel accessSituation() {
        Map<String, Object> map = monitorService.accessSituation();
//        List<StationCacheInfoDto> list = commonServiceImpl.getListStationCacheInfoDto();
//        double sum = list.stream().mapToDouble(l -> Double.parseDouble(l.getInstalledCapacity())).sum();
//        Map<String, List<StationCacheInfoDto>> listMap = list.stream().collect(Collectors.groupingBy(StationCacheInfoDto::getStationType, Collectors.toList()));
//        for (StationType value : StationType.values()) {
//            List<StationCacheInfoDto> dtos = listMap.get(value.getCode());
//            map.put(value.getCode(), dtos == null ? 0 : dtos.size());
//            map.put(value.getCode() + "title", dtos == null ? 0 : dtos.stream().filter(obj -> !ObjectUtils.isEmpty(obj.getInstalledCapacity())).mapToDouble(l -> Double.parseDouble(l.getInstalledCapacity())).sum());
//        }
//        map.put("total", list.size());
//        map.put("num", sum);
//        try {
//            emqKeeper.getMqttClient().publish("/accessSituation/topic", JSON.toJSONString(map).getBytes(), 0, true);
//        } catch (MqttException e) {
//
//        }
        return CommonResponseUtil.success();
    }

    @TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
    @Scheduled(cron = "0/30 * * * * ? ")
    @ApiOperation(value = "区域接入情况 ")
    @GetMapping("/qyAccessSituation")
    public ResponseModel qyAccessSituation() {
        monitorService.qyAccessSituation();
//        Map<String, Object> map = new LinkedHashMap<>();
//        List<StationCacheInfoDto> list = commonServiceImpl.getListStationCacheInfoDto();
//        Map<String, List<StationCacheInfoDto>> belongAreaList = list.stream().collect(Collectors.groupingBy(StationCacheInfoDto::getAreaCode));
//        for (String s : belongAreaList.keySet()) {
//            double sum = belongAreaList.get(s).stream().mapToDouble(l -> Double.parseDouble(l.getInstalledCapacity())).sum();
//            Map<String, List<StationCacheInfoDto>> listMap = list.stream().collect(Collectors.groupingBy(StationCacheInfoDto::getStationType, Collectors.toList()));
//            for (StationType value : StationType.values()) {
//                List<StationCacheInfoDto> dtos = listMap.get(value.getCode());
//                map.put(value.getCode(), dtos == null ? 0 : dtos.size());
//                map.put(value.getCode() + "title", dtos == null ? 0 : dtos.stream().filter(obj -> !ObjectUtils.isEmpty(obj.getInstalledCapacity())).mapToDouble(l -> Double.parseDouble(l.getInstalledCapacity())).sum());
//            }
//            map.put("total", list.size());
//            map.put("num", sum);
//            try {
//                emqKeeper.getMqttClient().publish("/accessSituation/topic/" + s, JSON.toJSONString(map).getBytes(), 1, true);
//            } catch (MqttException e) {
//
//            }
//        }

        return CommonResponseUtil.success();
    }


//    @TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
//    @ApiOperation(value = "健康运行百分比 ")
//    @GetMapping("/getFanStatusByZC")
//    public ResponseModel<Map<String,Object>> getFanStatusByZC(@RequestParam(value = "stationId", required = false) String stationId
//                                                             ) {
//        List<IndexDto> fanStatusList = monitorFanIndicator.getFanStatusStatistics(stationId);
//        int healthNum = 0;
//        int sum = 0;
//        for (IndexDto indexDto : fanStatusList) {
//            if (indexDto.getEquipmentIndexName().equals("正常运行")){
//                healthNum = Integer.parseInt(indexDto.getCountString());
//            }
//            sum += Integer.parseInt(indexDto.getCountString());
//        }
//        Map<String, Object>  hashMap = new HashMap<>() ;
//
//
//        double percent = (double) healthNum / sum * 100;
//        int value = (int) percent;
//        String[] values = new String[]{String.valueOf(value)};
//        hashMap.put("seriesData",values);
//        hashMap.put("title",healthNum+"/"+sum);
//        return ResponseHelper.buildResponse(hashMap);
//    }

//    @TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
//    @ApiOperation(value = "单个风机状态")
//    @GetMapping("/getFanStatusByEquipNum")
//    public ResponseModel<Map<String,Object>> getFanStatusList(@RequestParam(value = "stationId", required = false) String stationId,
//                                                           @RequestParam(value="equip")String equipNum) {
//        List<IndexDto> fanStatusList = monitorFanIndicator.getFanStatusList(stationId);
//        Map<String, Object>  hashMap = new HashMap<>() ;
//        String status = "";
//        for (IndexDto indexDto : fanStatusList) {
//            if (indexDto.getEquipmentNumber().equals(equipNum)){
//                status =indexDto.getState();
//            }
//        }
//        hashMap.put("title",status);
//        return ResponseHelper.buildResponse(hashMap);
//    }

    @TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "给部盾提供的发电率完成情况接口")
    @GetMapping("/getGenPowerInfoForBuDun")
    public ResponseModel<Map<String, String>> getGenPowerInfoForBuDun(@RequestParam(required = false) String areaCode, @RequestParam(required = false) String stationId) {
        return ResponseHelper.buildResponse(monitoringService.getGenPowerInfoForBuDun(areaCode, stationId));
    }


    @TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "全国发电详情部盾")
    @GetMapping("/getGenPowerInfo")
    public ResponseModel<Map<String, Object>> getGenPowerInfo(@RequestParam(required = false) String areaCode) {
        return ResponseHelper.buildResponse(monitoringService.getGenPowerInfo(areaCode));
    }
}


