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

import org.apache.commons.lang3.time.DateUtils;
import org.springblade.common.utils.CommonUtil;
import org.springblade.modules.nh.factory.common.EachRunner;
import org.springblade.modules.nh.factory.goodwe.GoodweApi;
import org.springblade.modules.nh.factory.goodwe.GoodweRet;
import org.springblade.modules.nh.factory.goodwe.dto.getplantsstaticdatas.GetPlantsStaticDatasData;
import org.springblade.modules.nh.factory.goodwe.dto.getplantsstaticdatas.GetPlantsStaticDatasR;
import org.springblade.modules.nh.factory.goodwe.dto.getplantsstaticdatas.GetPlantsStaticDatasReqByTime;
import org.springblade.modules.nh.factory.goodwe.dto.getplantsstaticdatas.GetPlantsStaticDatasSiteData;
import org.springblade.modules.nh.pojo.dto.sync.DayEnergyDTO;
import org.springblade.modules.nh.service.IMonitorEntryMonthStatService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.*;

/**
 * 按日统计
 */
@Service
public class GoodweStationMonthEachRunner extends EachRunner<List<String>> {

    @Autowired
    GoodweApi goodweApi;
    @Autowired
	IMonitorEntryMonthStatService monitorEntryMonthStatService;

    @Override
    public void handle(List<String> stationIds, Map<String, Object> ctx) throws IOException {
        GetPlantsStaticDatasReqByTime req = new GetPlantsStaticDatasReqByTime();
        req.setIds(stationIds);
        Date now = new Date();
        // goodwe 同步最近三天的数据，不包括今天
        req.setStartdt(DateUtils.truncate(DateUtils.addDays(now, -30), Calendar.DATE).getTime());
        req.setEnddt(DateUtils.truncate(DateUtils.addDays(now, -1), Calendar.DATE).getTime()); // 包含enddt指定的值
        req.setPeriod(1);

		req.setIndex(CommonUtil.getVendorIndex(ctx));
        GoodweRet<GetPlantsStaticDatasData> resp = goodweApi.getPlantsStaticDatas(req);
        if (resp.getCode() == 0) {
            GetPlantsStaticDatasData data = resp.getData();
            List<GetPlantsStaticDatasSiteData> list = data.getList();
            List<DayEnergyDTO> dayEnergList = new ArrayList<>();
            for (GetPlantsStaticDatasSiteData siteData : list) {
                List<GetPlantsStaticDatasR> slist = siteData.getData();
                for (GetPlantsStaticDatasR s : slist) {
                    DayEnergyDTO dayEnergyDTO = new DayEnergyDTO();
                    dayEnergyDTO.setStationId(siteData.getSid());
                    dayEnergyDTO.setUnit(siteData.getDataunit());
                    dayEnergyDTO.setValue(s.getValue());
                    dayEnergyDTO.setDate(s.getTime());
                    dayEnergList.add(dayEnergyDTO);
                }
            }
            monitorEntryMonthStatService.syncMonthStatData(dayEnergList);
        }
    }

}
