# HistoryAndForecastServiceTask.java

    package cloud.wconnect.rateshop.businesstask.rateshop;

    import cloud.wconnect.commonlib.businesstask.CheckReportMissedService;
    import cloud.wconnect.commonlib.businesstask.rule.MissedRuleByThreshold;
    import cloud.wconnect.commonlib.component.BeanMapper;
    import cloud.wconnect.commonlib.cons.FunctionCons;
    import cloud.wconnect.commonlib.pojo.dto.*;
    import cloud.wconnect.commonlib.pojo.dto.internationalization.InternationalizationDateTimeDTO;
    import cloud.wconnect.commonlib.pojo.dto.line.ReportMissedMsgParm;
    import cloud.wconnect.commonlib.pojo.dto.scheduler.JobParameterDTO;
    import cloud.wconnect.commonlib.service.PropertyInternalService;
    import cloud.wconnect.commonlib.util.*;
    import cloud.wconnect.rateshop.cons.BusinessEnum;
    import cloud.wconnect.rateshop.cons.EventSubjectEnum;
    import cloud.wconnect.rateshop.cons.FunctionPointEnum;
    import cloud.wconnect.rateshop.cons.rateshop.RateShopNotifyConfigTypeEnum;
    import cloud.wconnect.rateshop.entity.rateshop.RateShopEmailConfig;
    import cloud.wconnect.rateshop.entity.rateshop.RateShopEmailTarget;
    import cloud.wconnect.rateshop.entity.rateshop.RateShopScheduler;
    import cloud.wconnect.rateshop.service.rateshop.IRateShopEmailConfigService;
    import cloud.wconnect.rateshop.service.rateshop.IRateShopEmailTargetService;
    import com.alibaba.fastjson.JSONObject;
    import com.fasterxml.jackson.databind.ObjectMapper;
    import com.google.common.collect.Lists;
    import lombok.extern.slf4j.Slf4j;
    import org.apache.commons.collections.CollectionUtils;
    import org.apache.commons.lang3.StringUtils;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.scheduling.annotation.Async;
    import org.springframework.stereotype.Component;
    import org.thymeleaf.TemplateEngine;
    import org.thymeleaf.context.Context;

    import java.text.MessageFormat;
    import java.util.Collections;
    import java.util.List;
    import java.util.Map;
    import java.util.Objects;
    import java.util.concurrent.TimeUnit;

    /**
     * 定时任务：检查 HistoryAndForecast/Service 报告 是否存在数据缺失
     * 报告生成频率是：每小时 20 分
     *
     * @author lichen
     * @date 2023/06/16
     */
    @Slf4j
    @Component
    public class HistoryAndForecastServiceTask {

        @Autowired
        private CheckReportMissedService checkReportMissedService;
        @Autowired
        private IRateShopEmailConfigService emailConfigService;
        @Autowired
        private IRateShopEmailTargetService emailTargetService;
        @Value("${default.timezone}")
        private String defaultTimezone;
        @Autowired
        private PropertyInternalService propertyInternalService;
        @Autowired
        private LineMessageUtil lineMessageUtil;
        @Autowired
        private I18nMessageUtils i18nMessageUtils;
        @Autowired
        private BeanMapper beanMapper;
        @Autowired
        private ObjectMapper objectMapper;
        @Autowired
        private TemplateEngine templateEngine;
        @Value("${here.link.rate-shop}")
        private String hereLink;
        /**
         * 业务名称
         */
        private final static String BUSINESS = BusinessEnum.RATE_SHOP.getBusiness();
        /**
         * subject
         */
        private final static String SUBJECT = EventSubjectEnum.HISTORY_AND_FORECAST_SERVICE_YESTERDAY_NINETY_DAY.getSubject();

        /**
         * 检查是否存在数据缺失
         * 报告下发时间为每小时20分钟，每天23点检查当天的报告是否缺失
         *
         * @return void
         * @author lichen
         * @date 2023/6/15
         */
        @Async
        public void dataMissingCheck(RateShopScheduler scheduler) {
            log.info("HistoryAndForecastServiceTask.dataMissingCheck start...");
            Integer propertyId = scheduler.getPropertyId();
            PropertyDTO propertyDTO = propertyInternalService.getOne(propertyId);
            if (!propertyDTO.getStatus()) {
                log.warn("HistoryAndForecastServiceTask.dataMissingCheck end... the property is closed, no processing required");
                return;
            }

            //查询邮件配置
            RateShopEmailConfig emailConfig = emailConfigService.getByPropertyIdAndType(propertyId, scheduler.getCategory());
            List<RateShopEmailTarget> emailTargets = Collections.emptyList();
            if (Objects.nonNull(emailConfig)) {
                emailTargets = emailTargetService.listByConfigIds(Lists.newArrayList(emailConfig.getId()));
            }

            //通知DTO
            NotifyDTO notifyDTO = convertNotifyDTO(propertyDTO, emailConfig, emailTargets, scheduler);

            //阈值DTO
            JobParameterDTO jobParameterDTO = JsonUtils.convertStringToObject(objectMapper, scheduler.getParameters(), JobParameterDTO.class);
            ThresholdDTO thresholdDTO = new ThresholdDTO(jobParameterDTO.getThreshold(), TimeUnit.MINUTES, defaultTimezone);

            // 封装 CheckReportMissedDTO 对象
            CheckReportMissedDTO job = CheckReportMissedDTO.builder()
                    .business(BUSINESS)
                    .subject(SUBJECT)
                    .ruleClazzList(List.of(MissedRuleByThreshold.class))
                    .propertyDTO(propertyDTO)
                    .notifyDTO(notifyDTO)
                    .thresholdDTO(thresholdDTO)
                    .build();
            checkReportMissedService.doCheck(job);
            log.info("HistoryAndForecastServiceTask.dataMissingCheck end");
        }

        /**
         * 转换成通知DTO
         *
         * @param propertyDTO       资产DTO
         * @param emailConfig       邮件配置
         * @param emailTargets      邮件通知对象
         * @param rateShopScheduler 调度任务
         * @return cloud.wconnect.commonlib.pojo.dto.NotifyDTO
         * @author lichen
         * @date 2024/3/15
         */
        private NotifyDTO convertNotifyDTO(PropertyDTO propertyDTO, RateShopEmailConfig emailConfig,
                                           List<RateShopEmailTarget> emailTargets, RateShopScheduler rateShopScheduler) {
            //校验
            if (Objects.isNull(emailConfig)) return null;
            if (!emailConfig.getStatus()) return null;
            if (CollectionUtils.isEmpty(emailTargets)) return null;

            //获取国际化配置
            String language = propertyDTO.getLanguage();
            String timezone = propertyDTO.getTimezone();
            InternationalizationDateTimeDTO dateTime = propertyDTO.getInternationalization().getDateTime();
            String longDate = dateTime.getLongDate();

            String functionName = i18nMessageUtils.message(FunctionCons.RATE_SHOP_FUNCTION, language);
            //通知主题
            String defaultSubjectI18nCode = RateShopNotifyConfigTypeEnum.getDefaultSubjectI18nCode(rateShopScheduler.getCategory());
            String defaultSubject = i18nMessageUtils.message(defaultSubjectI18nCode, language, functionName, propertyDTO.getName());
            //自定义主体优先，其次默认主题
            String subject = StringUtils.isNotBlank(emailConfig.getSubject()) ? emailConfig.getSubject() : defaultSubject;

            //构建NotifyDTO
            NotifyDTO notifyDTO = new NotifyDTO();
            notifyDTO.setPropertyId(propertyDTO.getId());
            notifyDTO.setFunctionPoint(FunctionPointEnum.RATE_SHOP_PMS_REPORT_MISSED.getFunctionPoint());
            notifyDTO.setSubject(subject);
            notifyDTO.setIdentityList(beanMapper.mapList(emailTargets, NotifyIdentityDTO.class));

            //报告数据日期
            String missDate = "";
            String parameters = rateShopScheduler.getParameters();
            if (StringUtils.isNotBlank(parameters) && !parameters.equals("{}")) {
                JobParameterDTO jobParameterDTO = JsonUtils.convertStringToObject(objectMapper, parameters, JobParameterDTO.class);
                Map<String, Long> dateRange = JobParameterUtils.parseDateRange(jobParameterDTO.getDateRange(), jobParameterDTO.getDateRangeUnit(), propertyDTO.getTimezone(), null);
                String startDateStr = InternationalizationUtils.formatDateTime(dateRange.get(JobParameterDTO.START_DATE),
                        longDate, StringUtils.EMPTY, timezone, language);
                String endDateStr = InternationalizationUtils.formatDateTime(dateRange.get(JobParameterDTO.END_DATE),
                        longDate, StringUtils.EMPTY, timezone, language);
                //报告缺失日期
                missDate = startDateStr + " ~ " + endDateStr;
            }

            String reportName = "History and forecast";
            //跳转链接
            String linkUrl = MessageFormat.format(hereLink + "?property={0}&tenant={1}", propertyDTO.getAbbr(), propertyDTO.getTenantSymbol());
            Context context = new Context();
            context.setVariable("propertyName", propertyDTO.getName());
            context.setVariable("hereLink", linkUrl);
            context.setVariable("functionName", functionName);
            context.setVariable("reportName", reportName);
            context.setVariable("reportDate", missDate);
            //获取邮件body
            String mailBody = templateEngine.process(EmailUtil.getMissReportTemplateName(language), context);
            //设置邮件通知内容
            notifyDTO.setEmailContent(EmailUtil.getFullEmailContent(defaultSubject, mailBody, language));

            //line通知内容
            ReportMissedMsgParm reportMissedMsgParm = ReportMissedMsgParm.builder()
                    .propertyId(propertyDTO.getId())
                    .propertyName(propertyDTO.getName())
                    .functionName(functionName)
                    .reportName(reportName)
                    .missDate(missDate)
                    .build();
            JSONObject lineMsg = lineMessageUtil.generateReportMissedMsg(reportMissedMsgParm);
            notifyDTO.setLineContent(Lists.newArrayList(lineMsg));
            return notifyDTO;
        }

    }