package com.huatek.busi.task.transformer.part;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import com.huatek.busi.common.CacMonitorTypeCode;
import com.huatek.busi.common.SiteConstants.SiteTreeEnum;
import com.huatek.busi.common.SiteConstants.TransfromerTreeEnum;
import com.huatek.busi.common.UploadCycle.ConfigField;
import com.huatek.busi.service.BusiSensorService;
import com.huatek.busi.service.FailureRateService;
import com.huatek.busi.service.SiteUploadCycleService;
import com.huatek.busi.service.transformer.TransformerIcgeService;
import com.huatek.busi.service.transformer.TransformerIcgeStatisticsService;
import com.huatek.busi.task.base.AbstractBusiTaskExecutor;
import com.huatek.busi.vo.BusiSensorVo;
import com.huatek.busi.vo.TransformerIcgeCountVo;

/**
 * 变压器铁芯装置、夹件装置定时任务
 * 
 * @author anker_cheng
 * @date 2019/07/29
 */
@Component("transfromIcgeTask")
public class TransfromIcgeTask extends AbstractBusiTaskExecutor {
    @Autowired
    private TransformerIcgeService transformerIcgeService;
    @Autowired
    private FailureRateService failureRateService;
    @Autowired
    private SiteUploadCycleService siteUploadCycleService;
    @Autowired
    private TransformerIcgeStatisticsService transformerIcgeStatisticsService;
    @Autowired
    private BusiSensorService busiSensorService;

    @Override
    public void execute(LocalDate day) {
        execute(day, TransfromerTreeEnum.TX_EQM.getValue(), ConfigField.txzz);
        execute(day, TransfromerTreeEnum.JJ_EQM.getValue(), ConfigField.jjzz);
    }

    public void execute(LocalDate day, String equipmentType, ConfigField configField) {
        List<BusiSensorVo> sensorList = this.findSensorList(equipmentType);
        if (CollectionUtils.isEmpty(sensorList)) {
            return;
        }
        String cacMonitorTypeCode = CacMonitorTypeCode.TRANSFORMER_ICGE.getCode();
        for (BusiSensorVo sensor : sensorList) {
            // 上传周期
            BigDecimal cycle = siteUploadCycleService.getCycle(sensor.getSiteId(), configField);
            // 数据统计
            TransformerIcgeCountVo item =
                transformerIcgeService.getListEquInfo(day, cacMonitorTypeCode, sensor.getSensorCode());
            // 保存缺失率
            failureRateService.saveSensorFailureRate(sensor, day, cycle, item == null ? 0 : item.getDataCount());
            // TODO 保存日统计信息
            if (item != null) {
                transformerIcgeStatisticsService.saveTransformerIcgeStatistics(day, item);
            }
        }
    }

    private List<BusiSensorVo> findSensorList(String equipmentType) {
        return busiSensorService.findSensorList(SiteTreeEnum.BYQ, new String[] {equipmentType});
    }
}
