package com.huatek.busi.service.impl;

import java.time.LocalDate;
import java.time.LocalDateTime;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.dubbo.config.annotation.Service;
import com.huatek.busi.common.util.DecimalUtil;
import com.huatek.busi.dao.HwTemperIncreaseRateDao;
import com.huatek.busi.entity.HwTemperIncreaseRate;
import com.huatek.busi.mapper.HwTemperIncreaseRateMapper;
import com.huatek.busi.service.HwTemperIncreaseRateService;
import com.huatek.busi.vo.InfraredTemperatureStatisticsVo;

/**
 * 红外测温温度增长率表 ServiceImpl
 *
 * @author anker_cheng
 * @date Oct 24, 2019 10:41:09 AM
 */
@Component
@Service(interfaceClass = HwTemperIncreaseRateService.class)
@Transactional(rollbackFor = Exception.class)
public class HwTemperIncreaseRateServiceImpl implements HwTemperIncreaseRateService {

    @Autowired
    private HwTemperIncreaseRateMapper hwTemperIncreaseRateMapper;
    @Autowired
    private HwTemperIncreaseRateDao hwTemperIncreaseRateDao;

    @Override
    public void saveInfraredTemperatureGrowthRate(InfraredTemperatureStatisticsVo item, LocalDate day) {
        // 删除当天记录
        hwTemperIncreaseRateMapper.deleteItem(item.getMainTreeId(), item.getSensorCode(), day);
        // 保存新记录
        HwTemperIncreaseRate entity = new HwTemperIncreaseRate();
        entity.setSiteId(item.getSiteId());
        entity.setSensorId(item.getSensorCode());
        entity.setMainTreeId(item.getMainTreeId());
        entity.setSubTreeId(item.getSubTreeId());
        entity.setDTime(day);
        entity.setType(item.getCacMonitorTypeCode());
        entity.setCreateTime(LocalDateTime.now());
        entity.setMinTmpAvg(DecimalUtil.toStr(item.getAvgMinTmp()));
        entity.setMaxTmpAvg(DecimalUtil.toStr(item.getAvgMaxTmp()));
        entity.setAvgTmpAvg(DecimalUtil.toStr(item.getAvgAvgTmp()));
        entity.setMinTmpIncrease("0");
        entity.setMaxTmpIncrease("0");
        entity.setAvgTmpIncrease("0");
        // 获取前一天的
        HwTemperIncreaseRate previous = hwTemperIncreaseRateMapper.getItem(item.getMainTreeId(), item.getSensorCode(), day.minusDays(1));
        if (previous != null) {
            entity.setMinTmpIncrease(DecimalUtil.calIncrease(item.getAvgMinTmp(), previous.getMinTmpAvg()));
            entity.setMaxTmpIncrease(DecimalUtil.calIncrease(item.getAvgMaxTmp(), previous.getMaxTmpAvg()));
            entity.setAvgTmpIncrease(DecimalUtil.calIncrease(item.getAvgAvgTmp(), previous.getAvgTmpAvg()));
        }
        hwTemperIncreaseRateDao.saveOrUpdate(entity);
    }
}