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

import com.yeejoin.amos.boot.biz.common.utils.DateUtils;
import com.yeejoin.amos.boot.module.jxiop.api.dto.IndexDto;
import com.yeejoin.amos.boot.module.jxiop.biz.ESDto.ESDailyPowerGeneration;
import com.yeejoin.amos.boot.module.jxiop.biz.ESDto.ESMoonPowerGeneration;
import com.yeejoin.amos.boot.module.jxiop.biz.ESDto.ESYearPowerGeneration;
import com.yeejoin.amos.boot.module.jxiop.biz.constants.CommonConstans;
import com.yeejoin.amos.boot.module.jxiop.biz.dto.StationCacheInfoDto;
import com.yeejoin.amos.boot.module.jxiop.biz.entity.IndicatorData;
import com.yeejoin.amos.boot.module.jxiop.biz.repository.ESDailyPowerGenerationRepository;
import com.yeejoin.amos.boot.module.jxiop.biz.repository.ESMoonPowerGenerationRepository;
import com.yeejoin.amos.boot.module.jxiop.biz.repository.ESYearPowerGenerationRepository;
import com.yeejoin.amos.boot.module.jxiop.biz.tdmapper.IndicatorDataMapper;
import com.yeejoin.amos.boot.module.jxiop.biz.utils.InfluxDButils;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * @description:
 * @author: tw
 * @createDate: 2023/8/9
 */
@Service
public class PowerGenerationImpl {

    @Autowired
    InfluxDButils influxDButils;
    @Autowired
    private ElasticsearchRestTemplate elasticsearchTemplate;
    @Autowired
    ESYearPowerGenerationRepository yearPowerGenerationRepository;
    @Autowired
    ESMoonPowerGenerationRepository moonPowerGenerationRepository;
    @Autowired
    ESDailyPowerGenerationRepository dailyPowerGenerationRepository;
    @Autowired(required=true)
    IndicatorDataMapper indicatorDataMapper;

    //获取指定指标，当天最后一条数据
    public List<IndexDto> getlast(String gatewayId, String value,String daty){
        IndexDto indexDto=null;

        String querySql = " SELECT * FROM iot_data_%s  WHERE equipmentIndexName='%s'  and time >='%sT00:55:00Z' AND time < '%sT23:59:59Z'  group by equipmentsIdx order by time desc  LIMIT   1";

        querySql = String.format(querySql, gatewayId, value,daty,daty);
        List<IndexDto> queryList  = influxDButils.getListData(querySql,IndexDto.class);
        return queryList;
    }
    public List<IndexDto> getlastgf(String gatewayId, String value,String daty){
        IndexDto indexDto=null;
        String querySql = " SELECT * FROM iot_data_%s  WHERE equipmentIndexName='%s' and   equipmentSpecificName    =~/.*逆变器.*/   and time >='%sT00:55:00Z' AND time < '%sT23:59:59Z'  group by equipmentsIdx order by time desc  LIMIT   1";

        querySql = String.format(querySql, gatewayId, value,daty,daty);
        List<IndexDto> queryList  = influxDButils.getListData(querySql,IndexDto.class);
        queryList.forEach(item -> {
            item.setValue(String.valueOf(Double.parseDouble(item.getValue()) * CommonConstans.pvGenPoweActor * CommonConstans.pvGenPoweActorDay));
            item.setValueLabel(String.valueOf(Double.parseDouble(item.getValueLabel()) * CommonConstans.pvGenPoweActor * CommonConstans.pvGenPoweActorDay));
        });
        return queryList;
    }
    //更新es 数据

    //@Async("jxiopAsyncExecutor")
    public void addPowerGeneration(StationCacheInfoDto stationCacheInfoDto,String gatewayId, String value, String dateFormat, String type, String stationType,String datyvalue){
        //获取指标值
      // List<IndexDto> indexDto=null;
        List<IndicatorData> indexDto=null;
        Date currentDayStartTime = DateUtils.getCurrentDayStartTime(new Date());
        Date currentDayEndTime = DateUtils.getCurrentDayEndTime(new Date());
        String startTime = DateUtils.convertDateToString(currentDayStartTime, DateUtils.DATE_TIME_PATTERN);
        String endTime = DateUtils.convertDateToString(currentDayEndTime, DateUtils.DATE_TIME_PATTERN);
        Double flags=null;
        if("FDZ".equals(stationType)){
            //indexDto= this.getlast(gatewayId,value, datyvalue);

            indexDto=  indicatorDataMapper.selectlastfd(value,  gatewayId,  startTime, endTime);

        }else{
            //增加系数转化
            //"日发电量"
            if("日发电量".equals(value)){
                //"日发电量"
                flags=  CommonConstans.pvGenPoweActor * CommonConstans.pvGenPoweActorDay;
            }else if("月发电量".equals(value)){
                //"月发电量"
                flags= CommonConstans.pvGenPoweActornew;
            }else{
                //"年发电量"
                flags=  CommonConstans.pvGenPoweActorYear;
            }

            indexDto=  indicatorDataMapper.selectlastgf(value,  gatewayId,  startTime, endTime);
            //indexDto= this.getlastgf(gatewayId,value,datyvalue);
        }

        SimpleDateFormat myFmt2=new SimpleDateFormat(dateFormat);
        Date now=new Date();
        String daty= myFmt2.format(now);
        this.PowerGeneration(stationCacheInfoDto,indexDto,daty,type,flags);
    }


    //更新es
    public void PowerGeneration(StationCacheInfoDto stationCacheInfoDto, List<IndicatorData>  indexDto,String daty,String type,Double flags){
        Calendar calendar = Calendar.getInstance();
        int day = calendar.get(Calendar.DATE);
        int month = calendar.get(Calendar.MONTH) + 1;
        int year = calendar.get(Calendar.YEAR);

        SimpleDateFormat myFmt2=new SimpleDateFormat("yyyyMM");
        Date now=new Date();
        String monthy= myFmt2.format(now);

        SimpleDateFormat myFmty=new SimpleDateFormat("yyyy");
        Date nowy=new Date();
        String yeary= myFmty.format(nowy);


        switch (type) {
            case "day":
                List<ESDailyPowerGeneration> listd=   this.getESDailyPowerGeneration(stationCacheInfoDto,indexDto,daty,String.valueOf(day),monthy,flags);
                dailyPowerGenerationRepository.saveAll(listd);
                break;
            case "moon":
                List<ESMoonPowerGeneration> listm=   this.getESMoonPowerGeneration(stationCacheInfoDto,indexDto,daty,String.valueOf(month),yeary,flags);
                moonPowerGenerationRepository.saveAll(listm);
                break;
            case "year":
                List<ESYearPowerGeneration> listy=   this.getESYearPowerGeneration(stationCacheInfoDto,indexDto,daty,String.valueOf(year),flags);
                yearPowerGenerationRepository.saveAll(listy);
                break;
            default:
                break;
        }

    }

// 组装数据

    public List<ESDailyPowerGeneration> getESDailyPowerGeneration(StationCacheInfoDto stationCacheInfoDto, List<IndicatorData>  indexDto,String daty,String day,String month,Double flags){

        List<ESDailyPowerGeneration> list=new ArrayList<>();
        if(indexDto!=null&&!indexDto.isEmpty()){
            for (IndicatorData dto : indexDto) {
                double value=dto.getValueF()!=null?(double)dto.getValueF():0.0;
                if(flags!=null){
                    value=value*flags;
                }

                ESDailyPowerGeneration dailyPowerGeneration=new ESDailyPowerGeneration(
                        daty+"_"+dto.getAddress(),
                        stationCacheInfoDto.getStationId(),
                        stationCacheInfoDto.getStationName(),
                        stationCacheInfoDto.getStationType(),
                        stationCacheInfoDto.getBelongProvince(),
                        stationCacheInfoDto.getBelongArea(),
                        day,
                        dto.getGatewayId(),
                        new Date(),
                        value,
                        dto.getEquipmentIndexName(),
                        dto.getEquipmentNumber(),
                        dto.getAddress(),
                        month
                );
                list.add(dailyPowerGeneration);
            }
        }
        return list;
    }
    public List<ESMoonPowerGeneration> getESMoonPowerGeneration(StationCacheInfoDto stationCacheInfoDto,List<IndicatorData> indexDto,String daty,String day,String year,Double flags){
        List<ESMoonPowerGeneration> list=new ArrayList<>();
        if(indexDto!=null&&!indexDto.isEmpty()){
            for (IndicatorData dto : indexDto) {
                double value=dto.getValueF()!=null?(double)dto.getValueF():0.0;
                if(flags!=null){
                    value=value*flags;
                }
                ESMoonPowerGeneration moonPowerGeneration=new ESMoonPowerGeneration(
                        daty+"_"+dto.getAddress(),
                        stationCacheInfoDto.getStationId(),
                        stationCacheInfoDto.getStationName(),
                        stationCacheInfoDto.getStationType(),
                        stationCacheInfoDto.getBelongProvince(),
                        stationCacheInfoDto.getBelongArea(),
                        day,
                        dto.getGatewayId(),
                        new Date(),
                        value,
                        dto.getEquipmentIndexName(),
                        dto.getEquipmentNumber(),
                        dto.getAddress(),
                        year
                );
                list.add(moonPowerGeneration);
            }
        }
        return list;
    }
    public List<ESYearPowerGeneration> getESYearPowerGeneration(StationCacheInfoDto stationCacheInfoDto,List<IndicatorData> indexDto,String daty,String day,Double flags){
        List<ESYearPowerGeneration> list=new ArrayList<>();
        if(indexDto!=null&&!indexDto.isEmpty()){
            for (IndicatorData dto : indexDto) {
                double value=dto.getValueF()!=null?(double)dto.getValueF():0.0;
                if(flags!=null){
                    value=value*flags;
                }
                ESYearPowerGeneration yearPowerGeneration=new ESYearPowerGeneration(
                        daty+"_"+dto.getAddress(),
                        stationCacheInfoDto.getStationId(),
                        stationCacheInfoDto.getStationName(),
                        stationCacheInfoDto.getStationType(),
                        stationCacheInfoDto.getBelongProvince(),
                        stationCacheInfoDto.getBelongArea(),
                        day,
                        dto.getGatewayId(),
                        new Date(),
                        value,
                        dto.getEquipmentIndexName(),
                        dto.getEquipmentNumber(),
                        dto.getAddress()
                );
                list.add(yearPowerGeneration);
            }
        }
        return list;
    }







}
