package com.huatek.busi.task;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

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

import com.huatek.busi.common.util.DateUtil;
import com.huatek.busi.common.util.DecimalUtil;
import com.huatek.busi.dao.BusiTransformerLoadDao;
import com.huatek.busi.dao.SubstationMicBlqDao;
import com.huatek.busi.dao.SubstationMicGisDao;
import com.huatek.busi.dao.SubstationMicStatisticsDao;
import com.huatek.busi.entity.BusiOfflineArresterBrand;
import com.huatek.busi.entity.BusiOfflineGisBrand;
import com.huatek.busi.entity.BusiOfflineTransformerBrand;
import com.huatek.busi.entity.IecBydworkParam;
import com.huatek.busi.entity.SubstationMicBlq;
import com.huatek.busi.entity.SubstationMicGis;
import com.huatek.busi.entity.SubstationMicStatistics;
import com.huatek.busi.entity.TransformerMeteorological;
import com.huatek.busi.mapper.BusiOfflineArresterBrandMapper;
import com.huatek.busi.mapper.BusiOfflineGisBrandMapper;
import com.huatek.busi.mapper.BusiOfflineTransformerBrandMapper;
import com.huatek.busi.mapper.TransformerMeteorologicalMapper;
import com.huatek.busi.service.IecBydworkParamService;
import com.huatek.busi.task.base.AbstractBusiTaskExecutor;
import com.huatek.torch.util.uuid.Uuid;

import lombok.extern.slf4j.Slf4j;

/**
 * 气象统计任务
 * 
 * @author anker_cheng
 * @date 2019/07/16
 */
@Deprecated
@Slf4j
@Component("substationMicTask")
public class SubstationMicTask extends AbstractBusiTaskExecutor {
    @Autowired
    private IecBydworkParamService iecBydworkParamService;

    @Autowired
    private TransformerMeteorologicalMapper transformerMeteorologicalMapper;
    @Autowired
    private BusiOfflineTransformerBrandMapper busiOfflineTransformerBrandMapper;
    @Autowired
    private BusiOfflineGisBrandMapper busiOfflineGisBrandMapper;
    @Autowired
    private BusiOfflineArresterBrandMapper busiOfflineArresterBrandMapper;

    @Autowired
    private SubstationMicStatisticsDao substationMicStatisticsDao;
    @Autowired
    private BusiTransformerLoadDao busiTransformerLoadDao;
    @Autowired
    private SubstationMicGisDao substationMicGisDao;
    @Autowired
    private SubstationMicBlqDao substationMicBlqDao;

    @Override
    public void execute() {
        LocalDate yesterday = LocalDate.now().minusDays(1);
        execute(yesterday);
    }

    @Override
    public void execute(String params) {
        LocalDate day = toLocalDate(params);
        execute(day);
    }

    @Override
    public void execute(LocalDate day) {
        log.info("{} start...", day);
        try {
            Date start = DateUtil.getStartDate();
            Date end = DateUtil.getEndDate();
            // 查询数据
            List<TransformerMeteorological> list = transformerMeteorologicalMapper.getSubstationOneData(start, end);
            if (CollectionUtils.isEmpty(list)) {
                log.debug("substationMicTask: {}-{}数据为0是!", start, end);
                return;
            }
            BigDecimal wd = BigDecimal.ZERO;
            BigDecimal yl = BigDecimal.ZERO;
            BigDecimal sd = BigDecimal.ZERO;
            for (TransformerMeteorological substationMic : list) {
                wd = wd.add(DecimalUtil.getVal(substationMic.getAirTemperature()));
                yl = yl.add(DecimalUtil.getVal(substationMic.getAirPressure()));
                sd = sd.add(DecimalUtil.getVal(substationMic.getHumidity()));
            }
            BigDecimal wd_avg = wd.divide(new BigDecimal(list.size()), 2, RoundingMode.HALF_DOWN);
            BigDecimal yl_avg = yl.divide(new BigDecimal(list.size()), 2, RoundingMode.HALF_DOWN);
            BigDecimal sd_avg = sd.divide(new BigDecimal(list.size()), 2, RoundingMode.HALF_DOWN);
            saveStatistics(wd_avg, yl_avg, sd_avg);
            saveGisSubstationMic(wd_avg, yl_avg, sd_avg);
            saveBiLeiQiSubstationMic(wd_avg, yl_avg, sd_avg);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        log.info("{} end!", day);
    }

    /**
     * 保存统计
     * 
     * @param wd_avg
     * @param yl_avg
     * @param sd_avg
     * @throws Exception
     */
    private void saveStatistics(BigDecimal wd_avg, BigDecimal yl_avg, BigDecimal sd_avg) throws Exception {
        List<BusiOfflineTransformerBrand> findAll = busiOfflineTransformerBrandMapper.findAll();
        if (CollectionUtils.isEmpty(findAll)) {
            return;
        }
        for (BusiOfflineTransformerBrand tmp : findAll) {
            String equipmentCode = tmp.getEquipmentCode();
            if (StringUtils.isEmpty(equipmentCode)) {
                continue;
            }
            BigDecimal loadRate = BigDecimal.ZERO;
            String siteId = tmp.getSiteId();
            // 额定容量
            String ratedCapacity = tmp.getRatedCapacity();
            Date tj = DateUtil.getBeforeDate();
            if (!StringUtils.isEmpty(ratedCapacity)) {
                // 从104 计算负荷率 按天统计
                loadRate = findLoad(siteId, equipmentCode, ratedCapacity);
            }
            // TODO 1111111111
            SubstationMicStatistics statistics = new SubstationMicStatistics();
            statistics.setAirPressure(yl_avg);
            statistics.setAirTemperature(wd_avg);
            statistics.setDTime(DateUtil.toLocalDateTime(tj));
            statistics.setHumidity(sd_avg);
            statistics.setLoadRate(loadRate);
            statistics.setSiteId(siteId);
            statistics.setId(Uuid.getUUID());
            substationMicStatisticsDao.add(statistics);

            /* BusiTransformerLoad load = new BusiTransformerLoad();
            load.setLoadRate(loadRate.toString());
            load.setLoadTime(tj);
            load.setSiteEqmCode(equipmentCode);
            load.setSiteId(siteId);
            busiTransformerLoadDao.saveLoad(load);*/
        }
    }

    /**
     * 统计负荷
     * 
     * @param siteId
     * @param eqmCode
     * @param ratedCapacity
     * @return
     * @throws Exception
     */
    private BigDecimal findLoad(String siteId, String eqmCode, String ratedCapacity) throws Exception {
        double loadRate = 0d;
        Integer stype = 3;
        Date start = DateUtil.getStartDate();
        Date end = DateUtil.getEndDate();

        List<IecBydworkParam> list = new ArrayList<>();
        Date end2 = DateUtil.getCurrentDate();

        double total = 0d;
        double totalCapacity = Double.valueOf(ratedCapacity).doubleValue() * 1000d * 1000d * 24d;
        List<IecBydworkParam> list1 = iecBydworkParamService.getOneData(siteId, eqmCode, stype, start, start, "1");
        List<IecBydworkParam> list2 = iecBydworkParamService.getOneData(siteId, eqmCode, stype, start, end2, "2");
        List<IecBydworkParam> list3 = iecBydworkParamService.getOneData(siteId, eqmCode, stype, start, end2, "3");
        if (!CollectionUtils.isEmpty(list1)) {
            list.addAll(list1);
        }
        if (!CollectionUtils.isEmpty(list2)) {
            list.addAll(list2);
        }
        if (!CollectionUtils.isEmpty(list3)) {
            list.addAll(list3);
        }

        if (!CollectionUtils.isEmpty(list)) {
            for (IecBydworkParam iecBydworkParam : list) {
                double higthCurrent = iecBydworkParam.getHigthCurrent().doubleValue();
                double higthVoltage = iecBydworkParam.getHigthVoltage().doubleValue();
                if (iecBydworkParam.getStopTime().getTime() > end.getTime()) {
                    double diffHour = calcDiffHour(iecBydworkParam.getStopTime(), end2);
                    total += diffHour * higthCurrent * higthVoltage;
                } else {
                    double diffHour = calcDiffHour(iecBydworkParam.getStopTime(), iecBydworkParam.getStartTime());
                    total += diffHour * higthCurrent * higthVoltage;
                }
            }
            loadRate = total / totalCapacity;
        }
        return new BigDecimal(loadRate).setScale(2, RoundingMode.UP);
    }

    private double calcDiffHour(Date begin, Date end) {
        long from = end.getTime();
        long to = begin.getTime();
        long l = to - from;
        double hours = (l) / 3600000d;
        return hours;
    }

    private void saveGisSubstationMic(BigDecimal wd_avg, BigDecimal yl_avg, BigDecimal sd_avg) throws Exception {
        List<BusiOfflineGisBrand> findAll = busiOfflineGisBrandMapper.findAll();
        if (CollectionUtils.isEmpty(findAll)) {
            return;
        }
        for (BusiOfflineGisBrand tmp : findAll) {
            String equipmentCode = tmp.getEquipmentCode();
            if (StringUtils.isEmpty(equipmentCode)) {
                continue;
            }
            BigDecimal loadRate = BigDecimal.ZERO;
            String siteId = tmp.getSiteId();
            // TODO 1111111
            SubstationMicGis staticGis = new SubstationMicGis();
            staticGis.setAirPressure(yl_avg);
            staticGis.setAirTemperature(wd_avg);
            staticGis.setDTime(DateUtil.toLocalDate(DateUtil.getBeforeDate()));
            staticGis.setHumidity(sd_avg);
            staticGis.setLoadRate(loadRate);
            staticGis.setSiteId(siteId);
            staticGis.setId(Uuid.getUUID());
            substationMicGisDao.add(staticGis);
        }
    }

    private void saveBiLeiQiSubstationMic(BigDecimal wd_avg, BigDecimal yl_avg, BigDecimal sd_avg) throws Exception {
        List<BusiOfflineArresterBrand> findAll = busiOfflineArresterBrandMapper.findAll();
        if (CollectionUtils.isEmpty(findAll)) {
            return;
        }
        for (BusiOfflineArresterBrand tmp : findAll) {
            String equipmentCode = tmp.getEquipmentCode();
            if (StringUtils.isEmpty(equipmentCode)) {
                continue;
            }
            BigDecimal loadRate = BigDecimal.ZERO;
            String siteId = tmp.getSiteId();
            // TODO 1111111
            SubstationMicBlq staticBlq = new SubstationMicBlq();
            staticBlq.setAirPressure(yl_avg);
            staticBlq.setAirTemperature(wd_avg);
            // staticBlq.setDTime(DateUtil.toLocalDateTime(DateUtil.getBeforeDate()));
            staticBlq.setHumidity(sd_avg);
            staticBlq.setLoadRate(loadRate);
            staticBlq.setSiteId(siteId);
            staticBlq.setId(Uuid.getUUID());
            substationMicBlqDao.add(staticBlq);
        }
    }
}
