package com.zcxk.charge.xxl.service.impl;
import com.zcxk.charge.api.vo.DataAlarmManageVo;
import com.zcxk.charge.api.vo.ReportAttributeVo;
import com.zcxk.charge.core.dao.MonthReportMapper;
import com.zcxk.charge.core.entity.MonthReportEntity;
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 DataAlarmDayJobService extends AbstractDataAlarmJobService {

    @Resource
    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 = DateUtil.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());
        ReportAttributeVo 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(ReportAttributeVo report){
        return  report == null || report.getSumValue() == null;
    }
}
