# SvaOperatingStatisticsDailyTask.java

    package cloud.wconnect.workperformance.businesstask.sva.operatingstatisticsdaily;

    import cloud.wconnect.commonlib.cons.BaseConstant;
    import cloud.wconnect.commonlib.cons.ReportImportResultCons;
    import cloud.wconnect.commonlib.pojo.dto.NotifyDTO;
    import cloud.wconnect.commonlib.pojo.dto.PropertyDTO;
    import cloud.wconnect.commonlib.pojo.dto.scheduler.JobParameterDTO;
    import cloud.wconnect.commonlib.redis.PropertyI18nRedisService;
    import cloud.wconnect.commonlib.service.NotifyInternalService;
    import cloud.wconnect.commonlib.util.DateTimeUtils;
    import cloud.wconnect.commonlib.util.InternationalizationUtils;
    import cloud.wconnect.commonlib.util.JobParameterUtils;
    import cloud.wconnect.commonlib.util.JsonUtils;
    import cloud.wconnect.workperformance.entity.sva.SvaScheduler;
    import cloud.wconnect.workperformance.entity.sva.operatingstatistics.OperStatisImportLog;
    import cloud.wconnect.workperformance.entity.sva.operatingstatistics.OperatingStatistics;
    import cloud.wconnect.workperformance.service.sva.operatingstatistics.IOperStatisImportLogService;
    import cloud.wconnect.workperformance.service.sva.operatingstatistics.IOperatingStatisticsService;
    import cloud.wconnect.workperformance.service.sva.scheduleactual.ISvaSendNotifyService;
    import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
    import com.fasterxml.jackson.databind.ObjectMapper;
    import jakarta.annotation.Resource;
    import lombok.extern.slf4j.Slf4j;
    import org.apache.commons.lang3.StringUtils;
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.scheduling.annotation.Async;
    import org.springframework.stereotype.Component;

    import java.util.Map;
    import java.util.Objects;

    /**
     * 定时任务：Operating Statistics Daily
     *
     * @author zc
     * @date 2023/03/19
     */
    @Slf4j
    @Component
    public class SvaOperatingStatisticsDailyTask {
        @Resource
        private IOperatingStatisticsService operatingStatisticsService;
        @Resource
        private IOperStatisImportLogService importLogService;
        @Resource
        private ISvaSendNotifyService sendNotifyService;
        @Resource
        private PropertyI18nRedisService propertyI18nRedisService;
        @Resource
        private NotifyInternalService notifyInternalService;
        @Resource
        private ObjectMapper objectMapper;

        @Value("${here.link.sva.operating-statistics}")
        private String link;

        /**
         * 检查上个月的报告数据是否缺失
         *
         * @param schedulerJob 调度数据
         * @author zc
         * @date 2024/3/16
         */
        @Async
        public void dataMissingCheck(SvaScheduler schedulerJob) {
            log.info("SvaOperatingStatisticsDailyTask.dataMissingCheck start...");

            int propertyId = schedulerJob.getPropertyId();
            PropertyDTO propertyDTO = propertyI18nRedisService.get(propertyId);
            if (!propertyDTO.getStatus()) {
                log.warn("SvaOperatingStatisticsDailyTask.dataMissingCheck end... the property is closed, no processing required");
                return;
            }

            JobParameterDTO jobParameterDTO = JsonUtils.convertStringToObject(objectMapper,
                    schedulerJob.getParameters(), JobParameterDTO.class);
            // 获取报告日期范围
            Map<String, Long> dateRange = JobParameterUtils.parseDateRange(jobParameterDTO.getDateRange(),
                    jobParameterDTO.getDateRangeUnit(), propertyDTO.getTimezone(), null);

            // 根据日期范围检查是否有数据
            if (checkDataExist(propertyDTO, dateRange)) {
                log.info("SvaOperatingStatisticsDailyTask.dataMissingCheck end... data is empty");
                return;
            }

            // 记录报告缺失日志
            importLogService.save(OperStatisImportLog.builder()
                    .propertyId(propertyId)
                    .theDate(DateTimeUtils.dateNowTimestamp(propertyDTO.getTimezone()))
                    .startDate(dateRange.get(JobParameterDTO.START_DATE))
                    .endDate(dateRange.get(JobParameterDTO.END_DATE))
                    .importResult(ReportImportResultCons.IMPORT_RESULT_MISSED)
                    .url(null)
                    .createdBy(BaseConstant.ZERO)
                    .createdTime(DateTimeUtils.nowTimestamp())
                    .resolvedBy(BaseConstant.ZERO)
                    .resolvedTime(BaseConstant.LONG_ZERO)
                    .build());

            // 获取通知配置
            String reportName = "Operating Statistics Daily";
            String missDate = getMissDate(propertyDTO, dateRange);
            String hereLink = link + "?tenant=" + propertyDTO.getTenantSymbol() + "&property=" + propertyDTO.getAbbr();
            NotifyDTO notify = sendNotifyService.getNotifyDTO(propertyDTO, reportName, missDate, hereLink, schedulerJob.getCategory());
            if (Objects.isNull(notify)) {
                log.info("SvaOperatingStatisticsDailyTask.dataMissingCheck end... notifyDTO is null");
                return;
            }

            // 发送通知
            notifyInternalService.sendNotify(notify);

            log.info("SvaOperatingStatisticsDailyTask.dataMissingCheck end...");
        }

        /**
         * 根据日期范围检查是否有数据
         *
         * @param propertyDTO 资产
         * @param dateRange   日期范围（时间戳）
         * @return true：有数据 false：无数据
         * @author zc
         * @date 2024/3/16
         */
        private boolean checkDataExist(PropertyDTO propertyDTO, Map<String, Long> dateRange) {
            long count = operatingStatisticsService.count(new QueryWrapper<OperatingStatistics>().lambda()
                    .eq(OperatingStatistics::getPropertyId, propertyDTO.getId())
                    .between(OperatingStatistics::getTheDate, dateRange.get(JobParameterDTO.START_DATE),
                            dateRange.get(JobParameterDTO.END_DATE)));
            return count > BaseConstant.LONG_ZERO;
        }

        /**
         * 获取报告缺失日期
         *
         * @param propertyDTO 资产
         * @param dateRange   日期范围（时间戳）
         * @return 缺失日期
         * @author zc
         * @date 2024/3/16
         */
        private String getMissDate(PropertyDTO propertyDTO, Map<String, Long> dateRange) {
            String timezone = propertyDTO.getTimezone();
            String language = propertyDTO.getLanguage();
            String pattern = propertyDTO.getInternationalization().getDateTime().getLongDate();
            String startDateStr = InternationalizationUtils.formatDateTime(dateRange.get(JobParameterDTO.START_DATE),
                    pattern, StringUtils.EMPTY, timezone, language);
            String endDateStr = InternationalizationUtils.formatDateTime(dateRange.get(JobParameterDTO.END_DATE),
                    pattern, StringUtils.EMPTY, timezone, language);
            return startDateStr + " ~ " + endDateStr;
        }
    }