# HkOperatingStatisticsTask.java

    package cloud.wconnect.workperformance.businesstask.hkefficiency;

    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.hkefficiency.HkEfficiencyImportLog;
    import cloud.wconnect.workperformance.entity.hkefficiency.HkEfficiencyScheduler;
    import cloud.wconnect.workperformance.entity.sva.operatingstatistics.OperatingStatistics;
    import cloud.wconnect.workperformance.pojo.dto.hkefficiency.HkEfficiencyImportReportDTO;
    import cloud.wconnect.workperformance.service.hkefficiency.IHkEfficiencyImportLogService;
    import cloud.wconnect.workperformance.service.hkefficiency.IHkEfficiencySendNotifyService;
    import cloud.wconnect.workperformance.service.sva.operatingstatistics.IOperatingStatisticsService;
    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.scheduling.annotation.Async;
    import org.springframework.stereotype.Component;

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

    /**
     * 定时任务：HK Operating Statistics Daily
     *
     * @author zc
     * @date 2024/2/19
     */
    @Slf4j
    @Component
    public class HkOperatingStatisticsTask {
        @Resource
        private IHkEfficiencySendNotifyService sendNotifyService;
        @Resource
        private IHkEfficiencyImportLogService importLogService;
        @Resource
        private IOperatingStatisticsService operatingStatisticsService;
        @Resource
        private PropertyI18nRedisService propertyI18nRedisService;
        @Resource
        private NotifyInternalService notifyInternalService;
        @Resource
        private ObjectMapper objectMapper;

        /**
         * 检查上个月的报告数据是否缺失
         *
         * <p>
         * 检查报告缺失：每月月初 01:00:00
         * </p>
         *
         * @param schedulerJob 调度数据
         * @author zc
         * @date 2024/3/16
         */
        @Async
        public void dataMissingCheck(HkEfficiencyScheduler schedulerJob) {
            log.info("HKOperatingStatisticsTask.dataMissingCheck start...");

            int propertyId = schedulerJob.getPropertyId();
            PropertyDTO propertyDTO = propertyI18nRedisService.get(propertyId);
            if (!propertyDTO.getStatus()) {
                log.warn("HKOperatingStatisticsTask.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)) {
                return;
            }

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

            // 获取通知配置
            String reportName = "Operating Statistics Daily";
            String missDate = getMissDate(propertyDTO, dateRange);
            NotifyDTO notifyDTO = sendNotifyService.getNotifyDTO(propertyDTO, reportName, missDate, schedulerJob.getCategory());
            if (Objects.isNull(notifyDTO)) {
                log.info("HKOperatingStatisticsTask.dataMissingCheck end... notifyDTO is null");
                return;
            }

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

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

        /**
         * 根据日期范围检查是否有数据
         *
         * @param propertyDTO 资产
         * @param dateRange   日期范围（yyyyMMdd）
         * @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   日期范围（yyyyMMdd）
         * @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;
        }
    }