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

import com.zcxk.charge.api.vo.DataAlarmManageVo;
import com.zcxk.charge.core.dao.YearReportMapper;
import com.zcxk.charge.core.entity.YearReportEntity;
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.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.util.Date;
import java.util.List;

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

    @Resource
    private YearReportMapper yearReportMapper;

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

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

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

    private boolean yearSumIsNull(YearReportEntity report){
        return  report == null || report.getSumValue() == null;
    }
}
