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

import lombok.extern.slf4j.Slf4j;
import org.springblade.common.constant.NhConstants;
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.getdevicelistpro.GetDeviceListProR;
import org.springblade.modules.nh.factory.aiswei.dto.getdevicelistpro.GetDeviceListProReq;
import org.springblade.modules.nh.factory.aiswei.dto.getdevicelistpro.GetDeviceListProResp;
import org.springblade.modules.nh.factory.common.EachRunner;
import org.springblade.modules.nh.factory.ginlong.dto.inverterdetaillist.GetInverterDetailR;
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.*;

/**
 * for each station and station related device
 */
@Service
@Slf4j
public class AisweiInverterEachRunner extends EachRunner<String> {

    @Autowired
    AisweiApi aisweiApi;
    @Autowired
	IMonitorInverterStatService monitorInverterStatService;

    @Override
    public void handle(String stationId, Map<String, Object> ctx) throws IOException {
        GetDeviceListProReq req = new GetDeviceListProReq();
        req.setApiKey(stationId);
        AisweiRet<List<GetDeviceListProResp>> resp = aisweiApi.getDeviceListPro(req);
        if (!Objects.equals(resp.getStatus(), 200)) {
            log.error("aiswei 获取电站下设备列表 error，stationId:{}, info:{}, status:{}", stationId, resp.getInfo(), resp.getStatus());
            return;
        }

        List<GetDeviceListProResp> data = resp.getData();
        List<GetInverterDetailR> inverterList = new ArrayList<>();
        for (GetDeviceListProResp datum : data) {
            List<GetDeviceListProR> inverters = datum.getInverters();
            for (GetDeviceListProR inverter : inverters) {
                inverterList.add(convR(inverter, stationId, datum.getPsn()));
            }
        }
        if (!CollectionUtils.isEmpty(inverterList)) {
            try {
                Set<String> updateFields = new HashSet<>();
                updateFields.add("state");
                updateFields.add("collector_sn");
                monitorInverterStatService.syncInverterDetails(inverterList, NhConstants.SYS_TYPE_AISWEI, updateFields);
            } catch (Exception ex) {
                log.error("sync inverter details error", ex);
            }
        }
    }

    private GetInverterDetailR convR(GetDeviceListProR r, String stationId, String psn) {
        GetInverterDetailR ret = new GetInverterDetailR();
        ret.setDataTimestamp(DateUtil.parse(r.getLudt(), "yyyy-MM-dd HH:mm:ss").getTime());
        ret.setStationId(stationId);
        ret.setId(r.getIsn()); // 没有id，使用sn
        ret.setName("逆变器");
        ret.setSn(r.getIsn());
        ret.setCollectorsn(psn);
        ret.setState(convState(r.getIstate()));
        return ret;
    }

    /**
     * @param istate 0 离线，1 在线 2 缓存
     *               转换目标逆变器状态:
     *               1 = 在线
     *               2 = 离线
     *               3 = 报警
     */
    public static Integer convState(Integer istate) {
        if (istate != null) {
            if (istate == 0) {
                return 2;
            } else if (istate == 1) {
                return 1;
            } else {
                return istate;
            }
        }
        return null;
    }

}
