package org.springblade.modules.nh.factory.ginlong.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.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.inverterday.GetInverterDayR;
import org.springblade.modules.nh.factory.ginlong.dto.inverterday.GetInverterDayReq;
import lombok.extern.slf4j.Slf4j;
import org.springblade.modules.nh.pojo.dto.sync.InverterHourlyEnergyDTO;
import org.springblade.modules.nh.service.IMonitorInverterDailyStatService;
import org.springblade.modules.nh.service.IMonitorInverterStatService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

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

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

    @Autowired
    GinlongApi ginlongApi;

    @Autowired
	IMonitorInverterStatService monitorInverterStatService;

    @Autowired
	IMonitorInverterDailyStatService monitorInverterDailyStatService;

    /**
     * 逆变器按时统计，每天凌晨2点统计更新昨天的数据
     */
    @Override
    public void handle(String sn, Map<String, Object> ctx) throws IOException {
        Date yesterday = DateUtil.plusDays(new Date(), -1);
        String yesterdayStr = DateUtil.format(yesterday, "yyyy-MM-dd");

        GetInverterDayReq req = new GetInverterDayReq();
        req.setSn(sn);
        req.setMoney("CNY");
        req.setTime(yesterdayStr);
        req.setTimeZone(8);
		req.setIndex(CommonUtil.getVendorIndex(ctx));
        IRet<List<GetInverterDayR>> ret = ginlongApi.inverterDay(req);
        if (!Objects.equals(ret.getCode(), "0")) {
            log.info("get inverter day error, msg :{}", ret.getMsg());
            return;
        }
        List<GetInverterDayR> data = ret.getData();
        if (CollectionUtils.isEmpty(data)) {
            return;
        }
        List<InverterHourlyEnergyDTO> list = Lists.newArrayList();
        for (GetInverterDayR datum : data) {
            InverterHourlyEnergyDTO dto = new InverterHourlyEnergyDTO();
            dto.setSyncTime(new Date(datum.getDataTimestamp()));
            dto.setSn(sn);
            dto.setEnergy(datum.getEToday()); // 单位为kw
            dto.setJlgl(UnitUtil.convPower(datum.getPac(), datum.getPacStr()));
            list.add(dto);
        }
        monitorInverterDailyStatService.syncHourlyData(NhConstants.SYS_TYPE_GINLONG, list);
    }

}
