package com.zcxk.charge.xxl.service.impl;

import com.zcxk.charge.api.vo.DataAlarmManageVo;
import com.zcxk.charge.core.dao.DayReportMapper;
import com.zcxk.charge.core.entity.DayReportEntity;
import com.zcxk.charge.core.entity.DataAlarmDetailEntity;
import com.zcxk.charge.core.entity.DataAlarmManageEntity;
import com.zcxk.charge.xxl.enums.DataAlarmTypeEnum;
import com.zcxk.charge.xxl.service.AbstractDataAlarmJobService;
import com.zcxk.core.utils.DateUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.Date;
import java.util.List;

/**
 * 数据报警，最新值处理
 *
 * @author lihui
 * @version V1.0
 * @date 2021/6/1
 **/
@Service
public class DataAlarmHourJobService extends AbstractDataAlarmJobService {

    @Autowired
    private DayReportMapper dayReportMapper;

    @Override
    public void execute() {
        super.execute();
    }

    @Override
    protected List<DataAlarmManageVo> listDataAlarmManage() {
        return dataAlarmManageMapper.listByType(DataAlarmTypeEnum.LATEST_VALUE.getType());
    }

    @Override
    protected DataAlarmDetailEntity getAlarmValue(DataAlarmManageEntity dataAlarmManageEntity) {
        // 获取当前时间
        LocalDate nowDate = DateUtil.parseLocalDate(new Date());
        DayReportEntity dayReportEntity = new DayReportEntity();
        dayReportEntity.setYear(nowDate.getYear());
        dayReportEntity.setMonth(nowDate.getMonthValue());
        dayReportEntity.setDay(nowDate.getDayOfMonth());
        dayReportEntity.setTenantId(dataAlarmManageEntity.getTenantId());
        dayReportEntity.setDeviceId(dataAlarmManageEntity.getBeDeviceId());
        dayReportEntity.setAttributeId(dataAlarmManageEntity.getBeAttributeId());
        DayReportEntity dataReport = dayReportMapper.findLastDayValue(dayReportEntity);
        if (latestValueIsNull(dataReport)) {
            return null;
        }
        DataAlarmDetailEntity dataAlarmDetailEntity = new DataAlarmDetailEntity();
        BeanUtils.copyProperties(dataAlarmManageEntity, dataAlarmDetailEntity);
        dataAlarmDetailEntity.setBeAlarmValue(super.toBigDecimal(dataReport.getLatestValue()));
        // 设置查询条件
        dayReportEntity.setDeviceId(dataAlarmManageEntity.getToDeviceId());
        dayReportEntity.setAttributeId(dataAlarmManageEntity.getToAttributeId());
        dataReport = dayReportMapper.findLastDayValue(dayReportEntity);
        if (latestValueIsNull(dataReport)) {
            return null;
        }
        dataAlarmDetailEntity.setToAlarmValue(super.toBigDecimal(dataReport.getLatestValue()));
        return dataAlarmDetailEntity;
    }

    private boolean latestValueIsNull(DayReportEntity report){
        return  report == null || report.getLatestValue() == null;
    }
}
