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 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.*;

/**
 * @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);

        Date currentDayStartTime = DateUtils.getCurrentDayStartTime(new Date());
        Date currentDayEndTime = DateUtils.getCurrentDayEndTime(new Date());
        Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
        sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
        String startTime = sdf.format(currentDayStartTime);
        String endTime= sdf.format(currentDayEndTime);



        Double flags=null;
        if("FDZ".equals(stationType)){
            //indexDto= this.getlast(gatewayId,value, datyvalue);

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

        }else{
            //增加系数转化
            //"日发电量"


            if("日发电量".equals(value)){
                //"日发电量"
                value=  CommonConstans.taiHeGenIndicatorDay;
            }else if("月发电量".equals(value)){
                //"月发电量"
                value= CommonConstans.taiHeGenIndicatorMonth;
            }else{
                //"年发电量"
                value=  CommonConstans.taiHeGenIndicatorYear;
            }
            indexDto=  indicatorDataMapper.selectlastgf(value,  stationCacheInfoDto.getBoosterGatewayId(),  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;
                }
                String equipmentIndexName="";
                if(CommonConstans.taiHeGenIndicatorDay.equals(dto.getEquipmentIndexName())){
                    //"日发电量"
                    equipmentIndexName=  "日发电量";
                }else{
                    equipmentIndexName=dto.getEquipmentIndexName();
                }


                ESDailyPowerGeneration dailyPowerGeneration=new ESDailyPowerGeneration(
                        daty+"_"+dto.getAddress(),
                        stationCacheInfoDto.getStationId(),
                        stationCacheInfoDto.getStationName(),
                        stationCacheInfoDto.getStationType(),
                        stationCacheInfoDto.getBelongProvince(),
                        stationCacheInfoDto.getBelongArea(),
                        day,
                        dto.getGatewayId(),
                        new Date(),
                        value,
                        equipmentIndexName,
                        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;
                }
                String equipmentIndexName="";

                if(CommonConstans.taiHeGenIndicatorMonth.equals(dto.getEquipmentIndexName())){
                    equipmentIndexName=  "月发电量";
                }else{
                    equipmentIndexName=dto.getEquipmentIndexName();
                }


                ESMoonPowerGeneration moonPowerGeneration=new ESMoonPowerGeneration(
                        daty+"_"+dto.getAddress(),
                        stationCacheInfoDto.getStationId(),
                        stationCacheInfoDto.getStationName(),
                        stationCacheInfoDto.getStationType(),
                        stationCacheInfoDto.getBelongProvince(),
                        stationCacheInfoDto.getBelongArea(),
                        day,
                        dto.getGatewayId(),
                        new Date(),
                        value,
                        equipmentIndexName,
                        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;
                }
                String equipmentIndexName="";
                if(CommonConstans.taiHeGenIndicatorYear.equals(dto.getEquipmentIndexName())){
                    equipmentIndexName=  "年发电量";
                }else{
                    equipmentIndexName=dto.getEquipmentIndexName();
                }

                ESYearPowerGeneration yearPowerGeneration=new ESYearPowerGeneration(
                        daty+"_"+dto.getAddress(),
                        stationCacheInfoDto.getStationId(),
                        stationCacheInfoDto.getStationName(),
                        stationCacheInfoDto.getStationType(),
                        stationCacheInfoDto.getBelongProvince(),
                        stationCacheInfoDto.getBelongArea(),
                        day,
                        dto.getGatewayId(),
                        new Date(),
                        value,
                        equipmentIndexName,
                        dto.getEquipmentNumber(),
                        dto.getAddress()
                );
                list.add(yearPowerGeneration);
            }
        }
        return list;
    }







}
