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

import lombok.AllArgsConstructor;
import org.apache.commons.lang3.time.DateUtils;
import org.springblade.common.utils.CommonUtil;
import org.springblade.core.tool.utils.DateUtil;
import org.springblade.core.tool.utils.Func;
import org.springblade.modules.nh.factory.common.EachRunner;
import org.springblade.modules.nh.factory.ginlong.GinlongApi;
import org.springblade.modules.nh.factory.ginlong.IRet;
import org.springblade.modules.nh.factory.ginlong.dto.stationmonth.GetStationMonthR;
import org.springblade.modules.nh.factory.ginlong.dto.stationmonth.GetStationMonthReq;
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.IMonitorEntryStatService;
import org.springblade.modules.nh.service.IMonitorEntryYearStatService;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

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

/**
 * 实时获取电站当前的发电量和功率
 */
@Service
@AllArgsConstructor
public class GinlongStationFisGenDateEachRunner extends EachRunner<String> {

	private final GinlongApi ginlongApi;
	private final IMonitorEntryStatService monitorEntryStatService;
	private final IMonitorEntryYearStatService yearStatService;

	@Override
	public void handle(String stationId, Map<String, Object> ctx) throws IOException {
		handleData(stationId, CommonUtil.getVendorIndex(ctx));
	}

	public void handleData(String stationId,int index) throws IOException {
		String month = yearStatService.getFirstMonth(stationId);
		if(month==null){
			return;
		}
		GetStationMonthReq req = new GetStationMonthReq();
		req.setId(stationId);
		req.setMoney("CNY");
		req.setMonth(month);
		req.setTimeZone(8);
		req.setIndex(index);
		IRet<List<GetStationMonthR>> ret = ginlongApi.stationMonth(req);
		if (ret!=null && Objects.equals(ret.getCode(), "0")) {
			List<GetStationMonthR> dataList = ret.getData();
			if (CollectionUtils.isEmpty(dataList)) {
				return;
			}
			Date firstDate = null;
			for (GetStationMonthR getStationMonthR : dataList) {
				if(getStationMonthR.getEnergy()>0){
					Date date = new Date(getStationMonthR.getDate());
					if(firstDate==null){
						firstDate = date;
					}else{
						if(date.before(firstDate)){
							firstDate = date;
						}
					}
				}
			}

			if(firstDate!=null){
				monitorEntryStatService.updateFisDate(stationId,DateUtil.formatDate(firstDate));
			}
		}

	}

}
