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

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

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

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.entity.BusiOfflineTransformerBrand;
import com.huatek.busi.entity.TransformerEpaAbsIncreaseCache;
import com.huatek.busi.entity.TransformerEpaAbsIncreaseStatistics;
import com.huatek.busi.entity.TransformerEpaDataStatistics;
import com.huatek.busi.entity.TransformerEpaIncreaseCache;
import com.huatek.busi.entity.TransformerEpaIncreaseStatistics;
import com.huatek.busi.service.BusiSensorService;
import com.huatek.busi.service.BusiTransformerCorrectService;
import com.huatek.busi.service.FailureRateService;
import com.huatek.busi.service.SiteUploadCycleService;
import com.huatek.busi.service.transformer.BusiOfflineTransformerBrandService;
import com.huatek.busi.service.transformer.TransformerEpaAbsIncreaseCacheService;
import com.huatek.busi.service.transformer.TransformerEpaAbsIncreaseStatisticsService;
import com.huatek.busi.service.transformer.TransformerEpaDataOriginService;
import com.huatek.busi.service.transformer.TransformerEpaDataStatisticsService;
import com.huatek.busi.service.transformer.TransformerEpaIncreaseCacheService;
import com.huatek.busi.service.transformer.TransformerEpaIncreaseStatisticsService;
import com.huatek.busi.task.base.AbstractBusiTaskExecutor;
import com.huatek.busi.vo.BusiSensorVo;
import com.huatek.busi.vo.epa.EpaOneDataVo;

import lombok.extern.slf4j.Slf4j;

/**
 * 油色谱定时器</br>
 * 统计油色谱一天的数据
 * 
 * @author anker_cheng
 * @date 2019/07/15
 */
@Slf4j
@Component("transfromEqmTask")
public class TransfromEqmTask extends AbstractBusiTaskExecutor {
    @Autowired
    private TransformerEpaDataStatisticsService transformerEpaDataStatisticsService;
    @Autowired
    private TransformerEpaIncreaseStatisticsService transformerEpaIncreaseStatisticsService;
    @Autowired
    private TransformerEpaIncreaseCacheService transformerEpaIncreaseCacheService;
    @Autowired
    private BusiTransformerCorrectService busiTransformerCorrectService;
    @Autowired
    private FailureRateService failureRateService;
    @Autowired
    private TransformerEpaDataOriginService transformerEpaDataOriginService;
    @Autowired
    private SiteUploadCycleService siteUploadCycleService;
    @Autowired
    private TransformerEpaAbsIncreaseStatisticsService transformerEpaAbsIncreaseStatisticsService;
    @Autowired
    private TransformerEpaAbsIncreaseCacheService transformerEpaAbsIncreaseCacheService;
    @Autowired
    private BusiSensorService busiSensorService;
    
    @Autowired
    private BusiOfflineTransformerBrandService busiOfflineTransformerBrandService;
	

    @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) {
        LocalDateTime startTime = day.atStartOfDay();
        LocalDateTime endTime = day.plusDays(1).atStartOfDay();
        LocalDateTime dateTime = startTime;
        log.info("{} start...", day);
        try {
            List<BusiSensorVo> sensorList = this.findSensorList(TransfromerTreeEnum.YSP_EQM.getValue());
            if (CollectionUtils.isEmpty(sensorList)) {
                return;
            }
            // 2. 保存记录：油色谱统计数据表
            // 2.1 保存记录：增长率缓存
            // 2.2 保存记录：变压器例行修正值（按天）
            // 3. 保存记录：数据缺失率
            for (BusiSensorVo sensor : sensorList) {
                // 上传周期
                BigDecimal cycle = siteUploadCycleService.getCycle(sensor.getSiteId(), ConfigField.yspzz).multiply(BigDecimal.valueOf(60));
                // 数据统计
                EpaOneDataVo item =
                    transformerEpaDataOriginService.getOneData(startTime, endTime, sensor.getSensorCode());
                // 保存缺失率
                failureRateService.saveSensorFailureRate(sensor, day, cycle, item == null ? 0 : item.getTotalCount().intValue());
                // TODO 保存日平均值
                if(item != null) {
                    saveTransformerEpaDataStatistics(dateTime, item);
                }
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        log.info("{} end!", day);
    }

    /**
     * 保存日平均值
     * 
     * @param beforeDate
     * @param epaOneDataVo
     */
    private void saveTransformerEpaDataStatistics(LocalDateTime dateTime, EpaOneDataVo epaOneDataVo) throws Exception {
        TransformerEpaDataStatistics temp =
            transformerEpaDataStatisticsService.saveTransformerEpaDataStatistics(dateTime, epaOneDataVo);
        // 相对产气速率
        saveIncreaseRate(dateTime, temp);
        // 绝对产气速率
        saveAbsIncreaseRate(dateTime, temp);
        // 例行修正（按天）
        busiTransformerCorrectService.saveBusiTransformerCorrect(dateTime, temp);
    }

    /**
     * 保存增长率
     * 
     * @param dateTime
     * @param temp
     */
    private void saveIncreaseRate(LocalDateTime dateTime, TransformerEpaDataStatistics temp) {
        BigDecimal h2Increase = BigDecimal.ZERO;
        BigDecimal ch4Increase = BigDecimal.ZERO;
        BigDecimal c2h2Increase = BigDecimal.ZERO;
        BigDecimal c2h4Increase = BigDecimal.ZERO;
        BigDecimal c2h6Increase = BigDecimal.ZERO;
        BigDecimal coIncrease = BigDecimal.ZERO;
        BigDecimal co2Increase = BigDecimal.ZERO;
        BigDecimal h2oIncrease = BigDecimal.ZERO;
        BigDecimal totalHydrocarbon = BigDecimal.ZERO;

        // 获取30天前的数据或者前七天数据
        LocalDateTime intervalDate = dateTime.minusDays(29);
        TransformerEpaDataStatistics earlyData = transformerEpaDataStatisticsService.findIntervalDate(temp.getSiteId(),
            temp.getMainEquipmentId(), temp.getSubEquipmentId(), intervalDate);
        if (earlyData == null) {
            intervalDate = dateTime.minusDays(6);
            earlyData = transformerEpaDataStatisticsService.findIntervalDate(temp.getSiteId(),
                temp.getMainEquipmentId(), temp.getSubEquipmentId(), intervalDate);
        }
        if (earlyData != null) {
            h2Increase = calcIncrease(temp.getH2(), earlyData.getH2());
            ch4Increase = calcIncrease(temp.getCh4(), earlyData.getCh4());
            c2h2Increase = calcIncrease(temp.getC2h2(), earlyData.getC2h2());
            c2h4Increase = calcIncrease(temp.getC2h4(), earlyData.getC2h4());
            c2h6Increase = calcIncrease(temp.getC2h6(), earlyData.getC2h6());
            coIncrease = calcIncrease(temp.getCo(), earlyData.getCo());
            co2Increase = calcIncrease(temp.getCo2(), earlyData.getCo2());
            totalHydrocarbon = calcIncrease(temp.getTotalHydrocarbon(), earlyData.getTotalHydrocarbon());
            h2oIncrease = calcIncrease(temp.getH2o(), earlyData.getH2o());
        }

        TransformerEpaIncreaseStatistics epaIncreaseStatisticsParam = new TransformerEpaIncreaseStatistics();
        epaIncreaseStatisticsParam.setSiteId(temp.getSiteId());
        epaIncreaseStatisticsParam.setMainEquipmentId(temp.getMainEquipmentId());
        epaIncreaseStatisticsParam.setSubEquipmentId(temp.getSubEquipmentId());
        epaIncreaseStatisticsParam.setEquipmentId(temp.getEquipmentId());
        epaIncreaseStatisticsParam.setMainTreeId(temp.getMainTreeId());
        epaIncreaseStatisticsParam.setSubTreeId(temp.getSubTreeId());
        epaIncreaseStatisticsParam.setSensorCode(temp.getSensorId());
        epaIncreaseStatisticsParam.setC2h2Increase(c2h2Increase);
        epaIncreaseStatisticsParam.setC2h4Increase(c2h4Increase);
        epaIncreaseStatisticsParam.setC2h6Increase(c2h6Increase);
        epaIncreaseStatisticsParam.setCh4Increase(ch4Increase);
        epaIncreaseStatisticsParam.setCoIncrease(coIncrease);
        epaIncreaseStatisticsParam.setCo2Increase(co2Increase);
        epaIncreaseStatisticsParam.setH2Increase(h2Increase);
        epaIncreaseStatisticsParam.setH2oIncrease(h2oIncrease);
        epaIncreaseStatisticsParam.setN2Increase(BigDecimal.ZERO);
        epaIncreaseStatisticsParam.setO2Increase(BigDecimal.ZERO);
        epaIncreaseStatisticsParam.setTotalHydrocarbonIncrease(totalHydrocarbon);
        epaIncreaseStatisticsParam.setDTime(dateTime);
        transformerEpaIncreaseStatisticsService.saveTransformerEpaIncreaseStatistics(dateTime,
            epaIncreaseStatisticsParam);

        TransformerEpaIncreaseCache eqpIncreaseCacheParam = new TransformerEpaIncreaseCache();
        eqpIncreaseCacheParam.setSiteId(temp.getSiteId());
        eqpIncreaseCacheParam.setMainEquipmentId(temp.getMainEquipmentId());
        eqpIncreaseCacheParam.setSubEquipmentId(temp.getSubEquipmentId());
        eqpIncreaseCacheParam.setEquipmentId(temp.getEquipmentId());
        eqpIncreaseCacheParam.setMainTreeId(temp.getMainTreeId());
        eqpIncreaseCacheParam.setSubTreeId(temp.getSubTreeId());
        eqpIncreaseCacheParam.setSensorCode(temp.getSensorId());
        eqpIncreaseCacheParam.setC2h2(c2h2Increase);
        eqpIncreaseCacheParam.setC2h4(c2h4Increase);
        eqpIncreaseCacheParam.setC2h6(c2h6Increase);
        eqpIncreaseCacheParam.setCh4(ch4Increase);
        eqpIncreaseCacheParam.setCo(coIncrease);
        eqpIncreaseCacheParam.setCo2(co2Increase);
        eqpIncreaseCacheParam.setH2(h2Increase);
        eqpIncreaseCacheParam.setH2o(h2oIncrease);
        eqpIncreaseCacheParam.setTotalHydrocarbon(totalHydrocarbon);
        eqpIncreaseCacheParam.setDTime(dateTime);
        transformerEpaIncreaseCacheService.saveTransformerEpaIncreaseCache(dateTime, eqpIncreaseCacheParam);
    }

    private void saveAbsIncreaseRate(LocalDateTime dateTime, TransformerEpaDataStatistics temp) {
        BigDecimal h2Increase = BigDecimal.ZERO;
        BigDecimal ch4Increase = BigDecimal.ZERO;
        BigDecimal c2h2Increase = BigDecimal.ZERO;
        BigDecimal c2h4Increase = BigDecimal.ZERO;
        BigDecimal c2h6Increase = BigDecimal.ZERO;
        BigDecimal coIncrease = BigDecimal.ZERO;
        BigDecimal co2Increase = BigDecimal.ZERO;
        BigDecimal h2oIncrease = BigDecimal.ZERO;
        BigDecimal totalHydrocarbon = BigDecimal.ZERO;
        
        String pkj = temp.getMainEquipmentId();
        BusiOfflineTransformerBrand find = busiOfflineTransformerBrandService.getByPK(pkj);
        BigDecimal tmp2 = BigDecimal.ZERO;//油重
        BigDecimal tmp1 = new BigDecimal("0.869"); //油重比
        if(null != find) {
        	String oilWeight = find.getOilWeight();
        	String specificGravity = find.getSpecificGravity();
        	if(StringUtils.isNotBlank(oilWeight)){
        		tmp2 = new BigDecimal(oilWeight);
            }
        	if(StringUtils.isNotBlank(specificGravity)){
        		tmp1 = new BigDecimal(specificGravity);
            }
        }
        // 获取前一天的数据
        LocalDateTime intervalDate = dateTime.minusDays(1);
        TransformerEpaDataStatistics earlyData = transformerEpaDataStatisticsService.findIntervalDate(temp.getSiteId(),
            temp.getMainEquipmentId(), temp.getSubEquipmentId(), intervalDate);
        if (earlyData != null) {
        	 h2Increase = calcIncrease2(temp.getH2(), earlyData.getH2(),tmp1,tmp2);
             ch4Increase = calcIncrease2(temp.getCh4(), earlyData.getCh4(),tmp1,tmp2);
             c2h2Increase = calcIncrease2(temp.getC2h2(), earlyData.getC2h2(),tmp1,tmp2);
             c2h4Increase = calcIncrease2(temp.getC2h4(), earlyData.getC2h4(),tmp1,tmp2);
             c2h6Increase = calcIncrease2(temp.getC2h6(), earlyData.getC2h6(),tmp1,tmp2);
             coIncrease = calcIncrease2(temp.getCo(), earlyData.getCo(),tmp1,tmp2);
             co2Increase = calcIncrease2(temp.getCo2(), earlyData.getCo2(),tmp1,tmp2);
             totalHydrocarbon = calcIncrease2(temp.getTotalHydrocarbon(), earlyData.getTotalHydrocarbon(),tmp1,tmp2);
             h2oIncrease = calcIncrease2(temp.getH2o(), earlyData.getH2o(),tmp1,tmp2);
             log.info("h2绝对增长率{}",h2Increase);
             log.info("ch4绝对增长率{}",ch4Increase);
             log.info("c2h2绝对增长率{}",c2h2Increase);
             log.info("c2h4绝对增长率{}",c2h4Increase);
             log.info("c2h6绝对增长率{}",c2h6Increase);
             log.info("co绝对增长率{}",coIncrease);
             log.info("co绝对增长率{}",co2Increase);
             log.info("zt绝对增长率{}",totalHydrocarbon);
             log.info("h2o绝对增长率{}",h2oIncrease);
             
        }

        TransformerEpaAbsIncreaseStatistics epaIncreaseStatisticsParam = new TransformerEpaAbsIncreaseStatistics();
        epaIncreaseStatisticsParam.setSiteId(temp.getSiteId());
        epaIncreaseStatisticsParam.setMainEquipmentId(temp.getMainEquipmentId());
        epaIncreaseStatisticsParam.setSubEquipmentId(temp.getSubEquipmentId());
        epaIncreaseStatisticsParam.setEquipmentId(temp.getEquipmentId());
        epaIncreaseStatisticsParam.setMainTreeId(temp.getMainTreeId());
        epaIncreaseStatisticsParam.setSubTreeId(temp.getSubTreeId());
        epaIncreaseStatisticsParam.setSensorCode(temp.getSensorId());
        epaIncreaseStatisticsParam.setC2h2Increase(c2h2Increase);
        epaIncreaseStatisticsParam.setC2h4Increase(c2h4Increase);
        epaIncreaseStatisticsParam.setC2h6Increase(c2h6Increase);
        epaIncreaseStatisticsParam.setCh4Increase(ch4Increase);
        epaIncreaseStatisticsParam.setCoIncrease(coIncrease);
        epaIncreaseStatisticsParam.setCo2Increase(co2Increase);
        epaIncreaseStatisticsParam.setH2Increase(h2Increase);
        epaIncreaseStatisticsParam.setH2oIncrease(h2oIncrease);
        epaIncreaseStatisticsParam.setN2Increase(BigDecimal.ZERO);
        epaIncreaseStatisticsParam.setO2Increase(BigDecimal.ZERO);
        epaIncreaseStatisticsParam.setTotalHydrocarbonIncrease(totalHydrocarbon);
        epaIncreaseStatisticsParam.setDTime(dateTime);
        transformerEpaAbsIncreaseStatisticsService.saveTransformerEpaAbsIncreaseStatistics(dateTime,
            epaIncreaseStatisticsParam);

        TransformerEpaAbsIncreaseCache eqpIncreaseCacheParam = new TransformerEpaAbsIncreaseCache();
        eqpIncreaseCacheParam.setSiteId(temp.getSiteId());
        eqpIncreaseCacheParam.setMainEquipmentId(temp.getMainEquipmentId());
        eqpIncreaseCacheParam.setSubEquipmentId(temp.getSubEquipmentId());
        eqpIncreaseCacheParam.setEquipmentId(temp.getEquipmentId());
        eqpIncreaseCacheParam.setMainTreeId(temp.getMainTreeId());
        eqpIncreaseCacheParam.setSubTreeId(temp.getSubTreeId());
        eqpIncreaseCacheParam.setSensorCode(temp.getSensorId());
        eqpIncreaseCacheParam.setC2h2(c2h2Increase);
        eqpIncreaseCacheParam.setC2h4(c2h4Increase);
        eqpIncreaseCacheParam.setC2h6(c2h6Increase);
        eqpIncreaseCacheParam.setCh4(ch4Increase);
        eqpIncreaseCacheParam.setCo(coIncrease);
        eqpIncreaseCacheParam.setCo2(co2Increase);
        eqpIncreaseCacheParam.setH2(h2Increase);
        eqpIncreaseCacheParam.setH2o(h2oIncrease);
        eqpIncreaseCacheParam.setTotalHydrocarbon(totalHydrocarbon);
        eqpIncreaseCacheParam.setDTime(dateTime);
        transformerEpaAbsIncreaseCacheService.saveTransformerEpaAbsIncreaseCache(dateTime, eqpIncreaseCacheParam);
    }

    private static BigDecimal calcIncrease(BigDecimal newVal, BigDecimal originalVal) {
        if (newVal == null || originalVal == null) {
            return BigDecimal.ZERO;
        }
        if (BigDecimal.ZERO.compareTo(newVal) == 0 || BigDecimal.ZERO.compareTo(originalVal) == 0) {
            return BigDecimal.ZERO;
        }
        return newVal.subtract(originalVal).divide(originalVal, 4, BigDecimal.ROUND_HALF_DOWN);
    }

    private static BigDecimal calcIncrease(String newVal, String originalVal) {
        if (StringUtils.isBlank(newVal) || StringUtils.isBlank(originalVal)) {
            return BigDecimal.ZERO;
        }
        return calcIncrease(new BigDecimal(newVal), new BigDecimal(originalVal));
    }

    private List<BusiSensorVo> findSensorList(String equipmentType) {
        return busiSensorService.findSensorList(SiteTreeEnum.BYQ, new String[] {equipmentType});
    }
    
    private static BigDecimal calcIncrease2(String newVal, String originalVal,  BigDecimal tmp1 ,  BigDecimal tmp2 ) {
        if (StringUtils.isBlank(newVal) || StringUtils.isBlank(originalVal)) {
            return BigDecimal.ZERO;
        }
        if(tmp2.compareTo(BigDecimal.ZERO) == 0){
        	return BigDecimal.ZERO;
        }
        return calcIncrease2(new BigDecimal(newVal), new BigDecimal(originalVal), tmp1, tmp2);
    }
    
    /** 
    * @Title: calcIncrease2 
    * @Description: TODO 
    * @createDate: Dec 11, 2019 4:35:14 PM
    * @param    currentValue 当前值
    * @param    beforeValue  前一天的值
    * @param    oilWeight  油比重
    * @param    oil  油重（吨 
    * 
    * @return   BigDecimal    
    * @throws 
    */ 
    public static BigDecimal calcIncrease2(BigDecimal currentValue, BigDecimal beforeValue, BigDecimal oilWeight ,  BigDecimal oil) {
        if (currentValue == null || beforeValue == null) {
            return BigDecimal.ZERO;
        }
        if (BigDecimal.ZERO.compareTo(currentValue) == 0 || BigDecimal.ZERO.compareTo(beforeValue) == 0) {
            return BigDecimal.ZERO;
        }
        BigDecimal t0 = currentValue.subtract(beforeValue);
		BigDecimal t1 = t0.divide(new BigDecimal("24"), 8, BigDecimal.ROUND_HALF_DOWN);
		BigDecimal t2 = oil.divide(oilWeight, 8, BigDecimal.ROUND_HALF_DOWN);
        BigDecimal t3 = t1.multiply(t2);
        BigDecimal t4 = t3.multiply(new BigDecimal("0.001")).setScale(8,  BigDecimal.ROUND_HALF_DOWN);
		return t4;
    }
    
    public static void main(String [] args){
    	BigDecimal currentValue = new BigDecimal("242.96000000"); 
    	BigDecimal beforeValue= new BigDecimal("244.99000000");  
    	BigDecimal oilWeight = new BigDecimal("0.869"); 
    	BigDecimal oil= new BigDecimal("67.26"); 
    	BigDecimal calcIncrease2 = calcIncrease2(currentValue,beforeValue,oilWeight,oil);
    	System.out.print(calcIncrease2);
    }
}
