package com.zcxk.quartz.service;

import com.zcxk.dao.MonthReportMapper;
import com.zcxk.dto.ReportAttributeDto;
import com.zcxk.entity.MonthReportEntity;
import com.zcxk.entity.alarm.DataAlarmDetailEntity;
import com.zcxk.entity.alarm.DataAlarmManageEntity;
import com.zcxk.enums.DataAlarmTypeEnum;
import com.zcxk.util.DatesUtil;
import com.zcxk.vo.DataAlarmManageVo;
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 DataAlarmDayJobService extends AbstractDataAlarmJobService {

    @Autowired
    private MonthReportMapper monthReportMapper;

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

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

    @Override
    protected DataAlarmDetailEntity getAlarmValue(DataAlarmManageEntity dataAlarmManageEntity) {
        // 获取当前时间
        LocalDate nowDate = DatesUtil.parseLocalDate(new Date());
        MonthReportEntity monthReportEntity = new MonthReportEntity();
        monthReportEntity.setYear(nowDate.getYear());
        monthReportEntity.setMonth(nowDate.getMonthValue());
        monthReportEntity.setDay(nowDate.getDayOfMonth());
        monthReportEntity.setTenantId(dataAlarmManageEntity.getTenantId());
        monthReportEntity.setDeviceId(dataAlarmManageEntity.getBeDeviceId());
        monthReportEntity.setAttributeId(dataAlarmManageEntity.getBeAttributeId());
        ReportAttributeDto report = monthReportMapper.findSumValue(monthReportEntity);
        if (sumIsNull(report)) {
            return null;
        }
        DataAlarmDetailEntity dataAlarmDetailEntity = new DataAlarmDetailEntity();
        BeanUtils.copyProperties(dataAlarmManageEntity, dataAlarmDetailEntity);
        dataAlarmDetailEntity.setBeAlarmValue(super.toBigDecimal(report.getSumValue()));
        // 设置查询条件
        monthReportEntity.setDeviceId(dataAlarmManageEntity.getToDeviceId());
        monthReportEntity.setAttributeId(dataAlarmManageEntity.getToAttributeId());
        report = monthReportMapper.findSumValue(monthReportEntity);
        if (sumIsNull(report)) {
            return null;
        }
        dataAlarmDetailEntity.setToAlarmValue(super.toBigDecimal(report.getSumValue()));
        return dataAlarmDetailEntity;
    }


    private boolean sumIsNull(ReportAttributeDto report){
        return  report == null || report.getSumValue() == null;
    }
}
