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

import org.apache.commons.lang3.time.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springblade.common.utils.UnitUtil;
import org.springblade.modules.nh.factory.aiswei.AisweiApi;
import org.springblade.modules.nh.factory.aiswei.AisweiRet;
import org.springblade.modules.nh.factory.aiswei.dto.getplantoverviewpro.GetPlantOverviewProR;
import org.springblade.modules.nh.factory.aiswei.dto.getplantoverviewpro.GetPlantOverviewProReq;
import org.springblade.modules.nh.factory.aiswei.dto.getplantoverviewpro.UnitData;
import org.springblade.modules.nh.factory.common.EachRunner;
import org.springblade.modules.nh.pojo.entity.MonitorEntryStatEntity;
import org.springblade.modules.nh.service.IMonitorEntryStatService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Date;
import java.util.Map;
import java.util.Objects;

/**
 * 更新今日发电量，今年发电量和今年发电量和当月发电量和总发电量
 */
@Service
public class AisweiUserStationEachRunner extends EachRunner<String> {

    @Autowired
    AisweiApi aisweiApi;
    @Autowired
	IMonitorEntryStatService monitorEntryStatService;

    private static final Logger logger = LoggerFactory.getLogger(AisweiUserStationEachRunner.class);

    @Override
    public void handle(String stationId, Map<String, Object> ctx) throws IOException {
        GetPlantOverviewProReq req = new GetPlantOverviewProReq();
        req.setApikey(stationId);
        AisweiRet<GetPlantOverviewProR> resp = aisweiApi.getPlantOverviewPro(req);
        GetPlantOverviewProR data = resp.getData();
        if (Objects.equals(resp.getStatus(), 200)) {
            Date ludt = resp.getData().getLudt();
			MonitorEntryStatEntity r = monitorEntryStatService.findByStationId(stationId);
            Double etd = UnitUtil.convEnergy(data.getEtoday().getValue(), data.getEtoday().getUnit());
            if (DateUtils.isSameDay(ludt, r.getSyncTime()) && etd > r.getEtd()) {
				r.setEtd(etd);
            }
			r.setEtm(UnitUtil.convEnergy(data.getEmonth().getValue(), data.getEmonth().getUnit()));
			r.setEty(UnitUtil.convEnergy(data.getEyear().getValue(), data.getEyear().getUnit()));
			r.setEta(UnitUtil.convEnergy(data.getEtotal().getValue(), data.getEtotal().getUnit()));
            UnitData power = data.getPower();
            if (power != null) {
				r.setPower(UnitUtil.convPower(power.getValue(), power.getUnit()));
            }
			r.setSyncTime(ludt);
			r.setUpdateTime(new Date());
			monitorEntryStatService.updateById(r);
        } else {
            logger.error("同步电站今日、月、年和总发电量 error, info:{}, code：{}， stationId: {}", resp.getInfo(), resp.getStatus(), stationId);
        }
    }
}
