package org.springblade.modules.nh.factory.aiswei.scheduler;

import org.apache.commons.compress.utils.Lists;
import org.springblade.common.constant.NhConstants;
import org.springblade.common.utils.CommonUtil;
import org.springblade.common.utils.UnitUtil;
import org.springblade.core.tool.utils.DateUtil;
import org.springblade.modules.nh.factory.aiswei.AisweiApi;
import org.springblade.modules.nh.factory.aiswei.AisweiRet;
import org.springblade.modules.nh.factory.aiswei.dto.getplantoutputpro.GetPlantOutputProR;
import org.springblade.modules.nh.factory.aiswei.dto.getplantoutputpro.GetPlantOutputProReq;
import org.springblade.modules.nh.factory.aiswei.dto.getplantoutputpro.GetPlantOutputProResp;
import org.springblade.modules.nh.factory.common.EachRunner;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.time.DateUtils;
import org.springblade.modules.nh.pojo.dto.sync.DayEnergyDTO;
import org.springblade.modules.nh.pojo.dto.sync.JlglHourlyDTO;
import org.springblade.modules.nh.pojo.dto.sync.MonthEnergyDTO;
import org.springblade.modules.nh.service.IMonitorEntryDailyStatService;
import org.springblade.modules.nh.service.IMonitorEntryMonthStatService;
import org.springblade.modules.nh.service.IMonitorEntryYearStatService;
import org.springblade.modules.nh.service.impl.MonitorEntryMonthStatServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
@Slf4j
public class AisStationDMYEachRunner extends EachRunner<String> {

    @Autowired
    AisweiApi aisweiApi;
    @Autowired
	IMonitorEntryDailyStatService monitorEntryDailyStatService;
    @Autowired
	IMonitorEntryMonthStatService monitorEntryMonthStatService;
    @Autowired
	IMonitorEntryYearStatService monitorEntryYearStatService;

    @Override
    public void handle(String stationId, Map<String, Object> ctx) throws IOException {
        boolean statPacOnly = false;
        if (ctx != null) {
            Object statPacOnlyVal = ctx.get("stat_pac_only");
            if (Objects.equals(statPacOnlyVal, "1")) {
                statPacOnly = true;
            }
        }
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        final Date baseDate = new Date();
        if (statPacOnly) {
            GetPlantOutputProResp resp = syncOutput(stationId, "bydays", df.format(baseDate));
            if (resp != null) {
                handlePacByDay(df.format(baseDate), resp);
            }
            return;
        }

        // 同步最近3天的Pac
        for (int i = 0; i < 3; i++) {
            Date date = DateUtils.addDays(baseDate, -(i + 1));
            GetPlantOutputProResp resp = syncOutput(stationId, "bydays", df.format(date));
            if (resp != null) {
                handlePacByDay(df.format(date), resp);
            }
        }
        // 同步本月/上月的发电量
        df = new SimpleDateFormat("yyyy-MM");
        GetPlantOutputProResp resp = syncOutput(stationId, "bymonth", df.format(baseDate));
        if (resp != null) {
            handleEnergyByMonth(resp);
        }
        if (CommonUtil.monthBeginLessThanDays(3, baseDate)) {
            Date lastMonth = DateUtils.addMonths(baseDate, -1);
            resp = syncOutput(stationId, "bymonth", df.format(lastMonth));
            if (resp != null) {
                handleEnergyByMonth(resp);
            }
        }
        // 同步本年/上年的发电量
        df = new SimpleDateFormat("yyyy");
        resp = syncOutput(stationId, "byyear", df.format(baseDate));
        if (resp != null) {
            handleEnergyByYear(resp);
        }

        if (CommonUtil.yearBeginLessThanDays(3, baseDate)) {
            Date lastYear = DateUtils.addYears(baseDate, -1);
            resp = syncOutput(stationId, "byyear", df.format(lastYear));
            if (resp != null) {
                handleEnergyByYear(resp);
            }
        }
    }

    private void handleEnergyByYear(GetPlantOutputProResp resp) {
        if (!CollectionUtils.isEmpty(resp.getResult())) {
            List<MonthEnergyDTO> monthEnergyDTOList = Lists.newArrayList();
            for (GetPlantOutputProR s : resp.getResult()) {
                MonthEnergyDTO monthEnergyDTO = new MonthEnergyDTO();
                monthEnergyDTO.setStationId(resp.getApikey());
                monthEnergyDTO.setUnit(resp.getDataunit());
                monthEnergyDTO.setValue(s.getValue());
                monthEnergyDTO.setMonth(s.getTime());
                monthEnergyDTO.setSysType(NhConstants.SYS_TYPE_AISWEI);
                monthEnergyDTOList.add(monthEnergyDTO);
            }
            monitorEntryYearStatService.syncYearStatData(monthEnergyDTOList);
        }
    }

    private void handleEnergyByMonth(GetPlantOutputProResp resp) {
        List<GetPlantOutputProR> list = resp.getResult();
        if (CollectionUtils.isEmpty(list)) {
            return;
        }

        List<DayEnergyDTO> dayEnergyList = Lists.newArrayList();
        for (GetPlantOutputProR item : list) {
            Date date = DateUtil.parse(item.getTime(), "yyyy-MM-dd");
            if (DateUtils.isSameDay(date, new Date())) {
                // 不使用今日的数据
                continue;
            }
            DayEnergyDTO data = new DayEnergyDTO();
            data.setStationId(resp.getApikey());
            data.setUnit(resp.getDataunit());
            data.setValue(item.getValue());
            data.setDate(item.getTime());
            dayEnergyList.add(data);
        }
        monitorEntryMonthStatService.syncMonthStatData(dayEnergyList);
    }

    private void handlePacByDay(String date, GetPlantOutputProResp resp) {
        String dataunit = resp.getDataunit();
        List<JlglHourlyDTO> jlglHourlyDTOS = new ArrayList<>();
        List<GetPlantOutputProR> result = resp.getResult();
        Set<String> hours = new HashSet<>();
        for (GetPlantOutputProR plantOutputProR : result) {
            String time = plantOutputProR.getTime();
            String[] splits = time.split(":");
            String hour = splits[0];
            if (!hours.contains(hour)) {
                JlglHourlyDTO item = new JlglHourlyDTO();
                item.setHour(Integer.parseInt(hour));
                item.setJlgl(UnitUtil.convPower(plantOutputProR.getValue(), dataunit));
                jlglHourlyDTOS.add(item);
                hours.add(hour);
            }
        }
        monitorEntryDailyStatService.syncEntryDailyJlglStat(jlglHourlyDTOS, date, resp.getApikey(), NhConstants.SYS_TYPE_AISWEI);
    }

    private GetPlantOutputProResp syncOutput(String stationId, String period, String date) {
        try {
            GetPlantOutputProReq req = new GetPlantOutputProReq();
            req.setApikey(stationId);
            req.setDate(date);
            req.setPeriod(period); // "time": "2024-01",
            AisweiRet<GetPlantOutputProResp> pro = aisweiApi.getPlantOutputPro(req);
            if (Objects.equals(pro.getStatus(), 200)) {
                return pro.getData();
            } else {
                log.error("aiswei 同步日月年数据失败, status:{}, info:{}, stationId:{}", pro.getStatus(), pro.getInfo(), stationId);
            }
            Thread.sleep(1000);
        } catch (Exception ex) {
            log.error("aiswei 同步日月年数据失败", ex);
        }
        return null;
    }

}
