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

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.injector.methods.SelectOne;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yeejoin.amos.boot.module.jxiop.api.entity.Region;
import com.yeejoin.amos.boot.module.jxiop.api.entity.StationBasic;
import com.yeejoin.amos.boot.module.jxiop.api.entity.StationCoordinate;
import com.yeejoin.amos.boot.module.jxiop.api.mapper.RegionMapper;
import com.yeejoin.amos.boot.module.jxiop.api.mapper.StationBasicMapper;
import com.yeejoin.amos.boot.module.jxiop.api.mapper.StationCoordinateMapper;
import com.yeejoin.amos.boot.module.jxiop.biz.dto.*;
import com.yeejoin.amos.boot.module.jxiop.biz.utils.InfluxDButils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.typroject.tyboot.component.emq.EmqKeeper;

import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;


@Service
public class MonitoringServiceImpl {
    Logger logger = LoggerFactory.getLogger(MonitoringServiceImpl.class);
    /**
     * 区域mapper
     */
    @Autowired
    RegionMapper regionMapper;
    /**
     * 场站mapper
     */
    @Autowired
    StationBasicMapper stationBasicMapper;
    /**
     * 场站坐标mapper
     */
    @Autowired
    StationCoordinateMapper stationCoordinateMapper;
    /***
     * 设备基础信息中间表数据-热工院
     */
    @Autowired
    SjglZsjZsbtzServiceImpl SjglZsjZsbtzServiceImpl;


    @Autowired
    CommonServiceImpl commonServiceImpl;


    /**
     * 根据场站编号获取该场站的装机容量
     *
     * @param werks
     * @return
     */
    public Double getStationCaPACITYL(String werks) {
        return this.SjglZsjZsbtzServiceImpl.getStationCapactityByStationWerks(werks);
    }

    /**
     * 根据省份名称查询电站详情
     *
     * @param provinceName
     * @return
     */
    public List<RegionNationWideDto> getNationWideInfo(String provinceName) {
        List<RegionNationWideDto> regionNationWideDtoList = new ArrayList<>();
        //如果 provinceName 为空则表示当前为全国地图 否则则为省份地图
        if (ObjectUtils.isEmpty(provinceName) || provinceName.equals("")) {
            List<Region> regionList = this.regionMapper.selectList(new QueryWrapper<Region>().eq("level", 1));
            for (int i = 0; i < regionList.size(); i++) {
                RegionNationWideDto regionNationWideDto = new RegionNationWideDto();
                AtomicReference<Double> guangfuMW = new AtomicReference<>(0.0);
                AtomicReference<Double> fengdianMW = new AtomicReference<>(0.0);
                AtomicReference<Integer> guangfu = new AtomicReference<>(0);
                AtomicReference<Integer> fengdian = new AtomicReference<>(0);
                Region region = regionList.get(i);
                List<StationBasic> list = stationBasicMapper.selectList(new QueryWrapper<StationBasic>().like("belong_area", region.getRegionCode()));
                list.forEach(stationBasic -> {
                    if (!ObjectUtils.isEmpty(stationBasic.getFanGatewayId()) && !ObjectUtils.isEmpty(stationBasic.getStationNumber())) {
                        regionNationWideDto.setJsJoin(true);
                    }
                    if (stationBasic.getStationType().equals("FDZ")) {
                        fengdianMW.set(getStationCaPACITYL(stationBasic.getStationNumber()));
                        fengdian.getAndSet(fengdian.get() + 1);
                    } else {
                        guangfuMW.set(getStationCaPACITYL(stationBasic.getStationNumber()));
                        guangfu.getAndSet(guangfu.get() + 1);
                    }
                });
                regionNationWideDto.setFengdian(fengdian.toString());
                regionNationWideDto.setGuangfu(guangfu.toString());
                regionNationWideDto.setGuangfuMW("0");
                regionNationWideDto.setFengdianMV("0");
                if (!ObjectUtils.isEmpty(guangfuMW.get())) {
                    regionNationWideDto.setGuangfuMW(guangfuMW.toString());
                }
                if (!ObjectUtils.isEmpty(fengdianMW.get())) {
                    regionNationWideDto.setFengdianMV(fengdianMW.toString());
                }
                regionNationWideDto.setName(region.getRegionName());
                regionNationWideDtoList.add(regionNationWideDto);
            }
        } else {
            if (provinceName.contains("%")) {
                try {
                    provinceName = URLDecoder.decode(provinceName, "UTF-8");
                } catch (Exception e) {

                }
            }
            Region region = this.regionMapper.selectOne(new QueryWrapper<Region>().eq("level", 1).eq("region_name", provinceName));
            List<StationBasic> list = stationBasicMapper.selectList(new QueryWrapper<StationBasic>().like("belong_area", region.getRegionCode()));
            for (int i = 0; i < list.size(); i++) {
                HashMap<String, Double> hashMap = new HashMap<>();
                StationBasic stationBasic = list.get(i);
                RegionNationWideDto regionNationWideDto = new RegionNationWideDto();
                regionNationWideDto.setStaitionId(String.valueOf(stationBasic.getSequenceNbr()));
                regionNationWideDto.setStaitionName(stationBasic.getStationName());
                regionNationWideDto.setStaitionType(stationBasic.getStationType());
                String speendOrirradiate = "";
                regionNationWideDto.setStationCapacity(String.valueOf(getStationCaPACITYL(stationBasic.getStationNumber())));
                if (stationBasic.getStationType().equals("FDZ")) {
                    speendOrirradiate = String.valueOf(commonServiceImpl.getAvgvalueByIndicatior(stationBasic.getFanGatewayId(), "30秒平均风速"));
                    regionNationWideDto.setSpeendOrirradiate(speendOrirradiate);
                } else {
                    regionNationWideDto.setSpeendOrirradiate(String.valueOf(Math.random() * 100));
                    regionNationWideDto.setStationCapacity("0");
                }
                StationCoordinate stationCoordinate = stationCoordinateMapper.selectOne(new QueryWrapper<StationCoordinate>().eq("station_id", stationBasic.getSequenceNbr()).eq("is_main_coordinate", 0));
                hashMap.put("lng", Double.valueOf(stationCoordinate.getLongitude()));
                hashMap.put("lat", Double.valueOf(stationCoordinate.getLaitude()));
                regionNationWideDto.setPosition(hashMap);
                regionNationWideDtoList.add(regionNationWideDto);
            }

        }
        return regionNationWideDtoList;
    }


    public ResultsData getCompletionOfPowerIndicatorsByProvinceName(int current, int size, String provinceName) {
        Region region = this.regionMapper.selectOne(new QueryWrapper<Region>().eq("level", 1).eq("region_name", provinceName));
        List<StationBasic> stationBasicList = stationBasicMapper.selectList(new QueryWrapper<StationBasic>().like("belong_area", region.getRegionCode()));
        List<ColModel> colModels = new ArrayList<>();
        List<CompletionOfPowerIndicatorsDto> completionOfPowerIndicatorsDtoList = new ArrayList<>();
        ColModel colModelStatitonName = new ColModel("stationName", "stationName", "场站", "场站", "dataGrid", "stationName");
        ColModel colModelInstallCapactity = new ColModel("installCapactity", "installCapactity", "装机容量", "装机容量", "dataGrid", "installCapactity");
        ColModel colModelWindSpeedOrIrradiance = new ColModel("windSpeedOrIrradiance", "windSpeedOrIrradiance", "风度/辐照度", "风度/辐照度", "dataGrid", "windSpeedOrIrradiance");
        ColModel colModelActivePower = new ColModel("activePower", "activePower", "有功", "有功", "dataGrid", "activePower");
        ColModel colModelDailyPower = new ColModel("dailyPower", "dailyPower", "日发电量", "日发电量", "dataGrid", "dailyPower");
        ColModel colModelMonthlyPower = new ColModel("monthlyPower", "monthlyPower", "月发电量", "月发电量", "dataGrid", "monthlyPower");
        ColModel colModelAnnualPower = new ColModel("annualPower", "annualPower", "年发电量", "年发电量", "dataGrid", "annualPower");
        colModels.add(colModelStatitonName);
        colModels.add(colModelInstallCapactity);
        colModels.add(colModelWindSpeedOrIrradiance);
        colModels.add(colModelActivePower);
        colModels.add(colModelDailyPower);
        colModels.add(colModelMonthlyPower);
        colModels.add(colModelAnnualPower);
        //遍历列表
        stationBasicList.forEach(stationBasic -> {
            CompletionOfPowerIndicatorsDto completionOfPowerIndicatorsDto = new CompletionOfPowerIndicatorsDto();
            completionOfPowerIndicatorsDto.setStationName(stationBasic.getStationName());
            completionOfPowerIndicatorsDto.setInstallCapactity("0");
            if (getStationCaPACITYL(stationBasic.getStationNumber()) != null) {
                completionOfPowerIndicatorsDto.setInstallCapactity(String.valueOf(getStationCaPACITYL(stationBasic.getStationNumber())));
            }
            try {
                completionOfPowerIndicatorsDto.setWindSpeedOrIrradiance(String.valueOf(commonServiceImpl.getAvgvalueByIndicatior(stationBasic.getFanGatewayId(), "30秒平均风速")));
                completionOfPowerIndicatorsDto.setActivePower(String.valueOf(commonServiceImpl.getTotalByIndicatior(stationBasic.getFanGatewayId(), "有功功率")));
                completionOfPowerIndicatorsDto.setDailyPower(String.valueOf(commonServiceImpl.getTotalByIndicatior(stationBasic.getFanGatewayId(), "日发电量")));
                completionOfPowerIndicatorsDto.setMonthlyPower(String.valueOf(commonServiceImpl.getTotalByIndicatior(stationBasic.getFanGatewayId(), "月发电量")));
                completionOfPowerIndicatorsDto.setAnnualPower(String.valueOf(commonServiceImpl.getTotalByIndicatior(stationBasic.getFanGatewayId(), "年发电量")));
            } catch (Exception exception) {
                completionOfPowerIndicatorsDto.setWindSpeedOrIrradiance("0");
                completionOfPowerIndicatorsDto.setActivePower("0");
                completionOfPowerIndicatorsDto.setDailyPower("0");
                completionOfPowerIndicatorsDto.setMonthlyPower("0");
                completionOfPowerIndicatorsDto.setAnnualPower("0");
            }
            completionOfPowerIndicatorsDtoList.add(completionOfPowerIndicatorsDto);
        });
        Integer allsize = completionOfPowerIndicatorsDtoList.size();
        DataGridMock dataGridMock = new DataGridMock(current, allsize, false, allsize / size + 1, completionOfPowerIndicatorsDtoList);
        ResultsData resultsData = new ResultsData(dataGridMock, colModels);
        return resultsData;
    }


    public List<TabDto> getTabsByStationBasicId(String stationBasicId) {
        StationBasic stationBasic = stationBasicMapper.selectById(stationBasicId);
        List<TabDto> tabDtoList = new ArrayList<>();
        if (stationBasic.getStationType().contains("FDZ")&&stationBasic.getStationType().length()<4) {
            TabDto tab0 = new TabDto("风机布置图", "0");
            TabDto tab1 = new TabDto("集电线路图", "1");
            TabDto tab2 = new TabDto("运行列表", "2");
            TabDto tab3 = new TabDto("升压站监控", "3");
            TabDto tab4 = new TabDto("电量表记", "4");
            TabDto tab5 = new TabDto("故障信息", "5");
            tabDtoList.add(tab0);
            tabDtoList.add(tab1);
            tabDtoList.add(tab2);
            tabDtoList.add(tab3);
            tabDtoList.add(tab4);
            tabDtoList.add(tab5);
        } else {
            TabDto tab6 = new TabDto("光伏区布置图", "6");
            TabDto tab7 = new TabDto("集电线路图", "7");
            TabDto tab8 = new TabDto("运行列表", "8");
            TabDto tab9 = new TabDto("升压站监控", "9");
            TabDto tab10 = new TabDto("电量表记", "10");
            TabDto tab11 = new TabDto("故障信息", "11");
            TabDto tab12 = new TabDto("集中式-离散率", "12");
            TabDto tab13 = new TabDto("组串式-离散率", "13");
            tabDtoList.add(tab6);
            tabDtoList.add(tab7);
            tabDtoList.add(tab8);
            tabDtoList.add(tab9);
            tabDtoList.add(tab10);
            tabDtoList.add(tab11);
            tabDtoList.add(tab12);
            tabDtoList.add(tab13);
        }
        return tabDtoList;
    }
}
