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

import cn.hutool.core.math.MathUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springblade.common.constant.NhConstants;
import org.springblade.common.utils.CommonUtil;
import org.springblade.modules.nh.factory.aiswei.AisweiApi;
import org.springblade.modules.nh.factory.aiswei.AisweiRet;
import org.springblade.modules.nh.factory.aiswei.dto.getlasttsdatapro.GetLastTsDataProR;
import org.springblade.modules.nh.factory.aiswei.dto.getlasttsdatapro.GetLastTsDataProReq;
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 java.io.IOException;
import java.util.*;

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

    @Autowired
    AisweiApi aisweiApi;
    @Autowired
	IMonitorInverterStatService monitorInverterStatService;

    @Override
    public void handle(String sns, Map<String, Object> ctx) throws IOException {
        GetLastTsDataProReq req = new GetLastTsDataProReq();
        req.setIsnos(sns);
        AisweiRet<List<GetLastTsDataProR>> resp = aisweiApi.getLastTsDataPro(req);
        if (!Objects.equals(resp.getStatus(), 200)) {
            log.error("aiswei 获取逆变器最新信息失败,info:{},sns:{}", resp.getInfo(), sns);
            return;
        }
        List<GetLastTsDataProR> data = resp.getData();
        List<GetInverterDetailR> list = new ArrayList<>();
        for (GetLastTsDataProR datum : data) {
            list.add(convR(datum));
        }
        Set<String> updateFields = new HashSet<>();
        updateFields.add("name");
        updateFields.add("fac");
        updateFields.add("etd");
        updateFields.add("eto");
        updateFields.add("sync_time");
        updateFields.add("reactive_power");
        updateFields.add("reactive_power_str");
        updateFields.add("apparent_power");
        updateFields.add("apparent_power_str");
        updateFields.add("pac");
        updateFields.add("temperature");
        updateFields.add("dc_pac");
        updateFields.add("full_hour");
        updateFields.add("full_hour_str");
        if (!list.isEmpty()) {
            monitorInverterStatService.syncInverterDetails(list, NhConstants.SYS_TYPE_AISWEI, updateFields);
        }
    }

    private GetInverterDetailR convR(GetLastTsDataProR datum) {
        GetInverterDetailR ret = new GetInverterDetailR();
        ret.setDataTimestamp(Long.valueOf(datum.getTmstp()));
        ret.setStationId(datum.getApikey());
        ret.setId(datum.getSn()); // 没有id，使用sn
        ret.setName("逆变器");
        ret.setFac(Double.parseDouble(datum.getFac()) * 0.01);
        ret.setFacStr("HZ");
        ret.setEToday(Double.parseDouble(datum.getEtd()) * 0.1);
        ret.setETodayStr("kwh");
        ret.setETotal(Double.parseDouble(datum.getEto()) * 0.1);
        ret.setETotalStr("kwh");
        ret.setPac(Double.parseDouble(datum.getPac()));
        ret.setPacStr("w");
        ret.setReactivePower(Double.parseDouble(datum.getPrc()));
        ret.setReactivePowerStr("W");
        ret.setApparentPower(Double.parseDouble(datum.getSac()));
        ret.setApparentPowerStr("W");
        ret.setSn(datum.getSn());
        ret.setInverterTemperature(Double.parseDouble(datum.getCf()) * 0.1); // 使用散热片温度当做逆变器温度，这个和aiswei确认过
        // 由于aiswei没有直流总收入字段，通过mqtt电流和电压计算而来
        ret.setDcPac(calcDc(datum));
        ret.setDcPacStr("w");
        ret.setFullHour(Double.parseDouble(datum.getHto())); // 跟aiswei确认并网持续时间就是满发小时
        ret.setFullHourStr("H");

		try{
			for(int i=1;i<=3;i++){
				Object uPv = CommonUtil.reflectGetField(datum,"v"+i);
				Object iPv = CommonUtil.reflectGetField(datum,"i"+i);
				if(uPv==null || iPv==null){
					break;
				}
				CommonUtil.reflectSetField(ret,"uPv"+i, Double.parseDouble((String) uPv)/10);
				CommonUtil.reflectSetField(ret,"iPv"+i, Double.parseDouble((String) iPv)/10);
			}
			for(int i=1;i<=3;i++){
				Object uAc = CommonUtil.reflectGetField(datum,"va"+i);
				Object iAc = CommonUtil.reflectGetField(datum,"ia"+i);
				if(uAc==null || iAc==null){
					break;
				}
				CommonUtil.reflectSetField(ret,"uAc"+i, Double.parseDouble((String) uAc)/10);
				CommonUtil.reflectSetField(ret,"iAc"+i, Double.parseDouble((String) iAc)/10);
			}
		}catch (Exception e){
			log.error("aiswei 转化电流数据失败,info:{}",e.getMessage());
		}


        return ret;
    }

    private Double calcDc(GetLastTsDataProR datum) {
        return calc(datum.getV1(), datum.getI1()) + calc(datum.getV2(), datum.getI2()) + calc(datum.getV3(), datum.getI3());
    }

    private Double calc(String v1, String i1) {
        if (StringUtils.isAnyBlank(v1, i1)) {
            return 0d;
        }
        return Double.parseDouble(v1) * 0.1 * Double.parseDouble(i1) * 0.01;
    }

}
