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

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.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.RunRecord;
import com.yeejoin.amos.boot.module.jxiop.api.dto.TreeDto;
import com.yeejoin.amos.boot.module.jxiop.api.entity.MonitorFanIndicator;
import com.yeejoin.amos.boot.module.jxiop.api.entity.StationBasic;
import com.yeejoin.amos.boot.module.jxiop.api.mapper.StationBasicMapper;
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.MonitorFanIndicatorImpl;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.elasticsearch.index.Index;
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.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.File;
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
    StationBasicMapper stationBasicMapper;

    @Autowired
    CommonServiceImpl commonService;

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

    @Value("${gl.avg.column}")
    String avgColumn;

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

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


    @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 = "风机布置图 - 风机基础信息")
    @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", required = true)String stationId) {


        StationBasic stationBasic = stationBasicMapper.selectById(stationId);
        String gatewayId = stationBasic.getFanGatewayId();
        String [] sumColumns = new String[]{"日发电量","月发电量","年发电量"};
        String [] avgColumns = new String[]{"有功功率","瞬时风速"};
        List<String> columnList = Arrays.asList(sumColumns);
        List<String> columnLists = Arrays.asList(avgColumns);
        Map<String, Object> columnMap = new HashMap<>();


        for (String column : columnList) {
            Double result = commonService.getTotalByIndicatior(gatewayId, column);
            columnMap.put(column, result);
        }
        for (String column : columnLists) {
            Double result = commonService.getAvgvalueByIndicatior(gatewayId, column);
            columnMap.put(column, result);
        }

        String num = monitorFanIndicator.getFJCount(gatewayId);
        columnMap.put("风机台数",num);

        Double capacityl = commonService.getStationCapactityByStationWerks(stationBasic.getStationNumber());
        columnMap.put("装机容量",capacityl);


        List<Map<String,Object>> objects = new ArrayList<>();
        Map<String, Object> data = new HashMap<>();
        data.put("title",Float.valueOf(columnMap.get("装机容量").toString()));
        objects.add(data);
        Map<String, Object> data1 = new HashMap<>();
        data1.put("title",Float.valueOf(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",Float.valueOf(columnMap.get("月发电量").toString()));
        objects.add(data3);
        Map<String, Object> data4 = new HashMap<>();
        data4.put("title",Float.valueOf(columnMap.get("瞬时风速").toString()));
        objects.add(data4);
        Map<String, Object> data5 = new HashMap<>();
        data5.put("title",Float.valueOf(columnMap.get("年发电量").toString()));
        objects.add(data5);
        Map<String, Object> data6 = new HashMap<>();
        data6.put("title",Float.valueOf(columnMap.get("有功功率").toString()));
        objects.add(data6);
        Map<String, Object> data7 = new HashMap<>();
        data7.put("title",7.47);
        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 ResponseModel<Map<String, Object>> getOverviewWindSpeed(@RequestParam(value = "stationId", required = true)String stationId) {
        StationBasic stationBasic = stationBasicMapper.selectById(stationId);
        String gatewayId = stationBasic.getFanGatewayId();
        Map<String, Object> detailsWindSpeed = monitorFanIndicator.getDetailsWindSpeedAll(gatewayId);

        return ResponseHelper.buildResponse(detailsWindSpeed);
    }

    @TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "风机详情-风速功率曲线")
    @GetMapping("/detailsWindSpeed")
    public ResponseModel<Map<String, Object>> getDetailsWindSpeed(@RequestParam(value = "stationId", required = true)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("/statusMonitoring")
    public ResponseModel<IPage<Map<String, Object>>> getStatusMonitoring(@RequestParam(value = "stationId", required = true)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", required = true)String stationId,String frontModule,String systemType) {
        StationBasic stationBasic = stationBasicMapper.selectById(stationId);
        String gatewayId = stationBasic.getBoosterGatewayId();
        List<Map<String, Object>> statusMonitoring = monitorFanIndicator.getStatusGzp(gatewayId ,systemType,frontModule);
        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")
    public ResponseModel<IPage<Map<String, Object>>> getStatusJDX(@RequestParam(value = "stationId", required = true)String stationId) {
        StationBasic stationBasic = stationBasicMapper.selectById(stationId);
        String gatewayId = stationBasic.getBoosterGatewayId();
        String werks = stationBasic.getStationNumber();
         monitorFanIndicator.getStatusJDX(gatewayId, "集电线" ,werks,stationBasic.getSequenceNbr().toString());

        return  CommonResponseUtil.success();
    }


    @TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "集电线路图右侧 风机列表")
    @GetMapping("/fjList")
    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();
    }




    @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);
        List<StationBasic> stationBasics = Collections.singletonList(oneByStationNumber);
        IPage<StationBasic> result = new Page<>();
        result.setRecords(stationBasics);
        result.setCurrent(1);
        result.setTotal(stationBasics.size());
        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/10 * * * * ? ")
    @TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "模拟量列表消息")
    @GetMapping("/getAnalogQuantityInfo")
    public ResponseModel getAnalogQuantityInfo() {
        LambdaQueryWrapper<StationBasic> wrapper = new LambdaQueryWrapper<>();
        List<StationBasic> stationBasics = stationBasicMapper.selectList(wrapper);
        for (StationBasic stationBasic : stationBasics) {
            String gatewayId = stationBasic.getFanGatewayId();
            monitorFanIndicator.getAnalogQuantityInfo(gatewayId, stationBasic.getSequenceNbr().toString());
        }
        return CommonResponseUtil.success();
    }

}
