# ArrivalsDetailedServiceTask.java

    package cloud.wconnect.frontoffice.businesstask.badguest;

    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.cons.PmsReportEnum;
    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.redis.PropertyI18nRedisService;
    import cloud.wconnect.commonlib.service.PropertyInternalService;
    import cloud.wconnect.commonlib.util.*;
    import cloud.wconnect.frontoffice.cons.BusinessEnum;
    import cloud.wconnect.frontoffice.cons.EventSubjectEnum;
    import cloud.wconnect.frontoffice.cons.FunctionPointEnum;
    import cloud.wconnect.frontoffice.cons.badguest.BlacklistNotifyConfigTypeEnum;
    import cloud.wconnect.frontoffice.entity.badguest.BgEmailConfig;
    import cloud.wconnect.frontoffice.entity.badguest.BgEmailTarget;
    import cloud.wconnect.frontoffice.entity.badguest.BgScheduler;
    import cloud.wconnect.frontoffice.service.badguest.IBgEmailConfigService;
    import cloud.wconnect.frontoffice.service.badguest.IBgEmailTargetService;
    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.Objects;
    import java.util.concurrent.TimeUnit;

    /**
     * @author lichen
     * @description 定时任务：检查 Arrivals Detailed/service 报告 是否存在数据缺失
     * 报告生成频率是：每小时 15 分
     * @date 2023/3/24 11:19
     */
    @Slf4j
    @Component
    public class ArrivalsDetailedServiceTask {

        @Autowired
        private CheckReportMissedService checkReportMissedService;
        @Autowired
        private IBgEmailConfigService emailConfigService;
        @Value("${default.timezone}")
        private String defaultTimezone;
        @Autowired
        private PropertyInternalService propertyInternalService;
        @Autowired
        private PropertyI18nRedisService propertyI18nRedisService;
        @Autowired
        private LineMessageUtil lineMessageUtil;
        @Autowired
        private I18nMessageUtils i18nMessageUtils;
        @Autowired
        private IBgEmailTargetService emailTargetService;
        @Autowired
        private BeanMapper beanMapper;
        @Autowired
        private ObjectMapper objectMapper;
        @Autowired
        private TemplateEngine templateEngine;
        @Value("${here.link.bad-guest}")
        private String hereLink;
        /**
         * 业务名称
         */
        private final static String BUSINESS = BusinessEnum.GUESTS_BLACKLIST.getBusiness();
        /**
         * subject
         */
        private final static String SUBJECT = EventSubjectEnum.ARRIVALS_DETAILED_SERVICE.getSubject();

        /**
         * 检查Arrivals Detailed/service 报告 是否存在数据缺失
         *
         * @param scheduler 调度任务
         * @return void
         * @author lichen
         * @date 2024/3/15
         */
        @Async
        public void dataMissingCheck(BgScheduler scheduler) {
            log.info("ArrivalsDetailedServiceTask.start....");
            //查询资产集合
            Integer propertyId = scheduler.getPropertyId();
            PropertyDTO propertyDTO = propertyI18nRedisService.get(propertyId);
            if (!propertyDTO.getStatus()) return;

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

            //获取通知配置DTO
            NotifyDTO notifyDTO = convertNotifyDTO(propertyDTO, emailConfig, emailTargets);

            //阈值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("ArrivalsDetailedServiceTask.dataMissingCheck end");
        }

        /**
         * 转化为通知DTO
         *
         * @param propertyDTO  资产DTO
         * @param emailConfig  邮件配置
         * @param emailTargets 邮件通知对象集合
         * @return cloud.wconnect.commonlib.pojo.dto.NotifyDTO
         * @author lichen
         * @date 2024/3/16
         */
        private NotifyDTO convertNotifyDTO(PropertyDTO propertyDTO, BgEmailConfig emailConfig, List<BgEmailTarget> emailTargets) {
            if (Objects.isNull(emailConfig)) return null;
            if (!emailConfig.getStatus()) return null;
            if (CollectionUtils.isEmpty(emailTargets)) return null;

            String language = propertyDTO.getLanguage();
            String functionName = i18nMessageUtils.message(FunctionCons.GUEST_BLACK_LIST, language);

            //默认主题的国际化code
            String defaultSubjectI18nCode = BlacklistNotifyConfigTypeEnum.getDefaultSubjectI18nCode(emailConfig.getType());
            String defaultSubject = i18nMessageUtils.message(defaultSubjectI18nCode, language, functionName, propertyDTO.getName());
            //自定义主体优先，其次默认主题
            String subject = StringUtils.isNotBlank(emailConfig.getSubject()) ? emailConfig.getSubject() : defaultSubject;

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

            //报告下发的是全量数据，缺失日期记录为当前时间
            InternationalizationDateTimeDTO dateTime = propertyDTO.getInternationalization().getDateTime();
            String missDate = InternationalizationUtils.formatDateTime(DateTimeUtils.dateNowTimestamp(propertyDTO.getTimezone()),
                    dateTime.getLongDate(), StringUtils.EMPTY, propertyDTO.getTimezone(), propertyDTO.getLanguage());

            // 获取资产配置的 PMS 报告名称
            String reportName = propertyInternalService.getPmsReportConfig(propertyDTO.getId(),
                    propertyDTO.getPmsType(), PmsReportEnum.ARRIVAL_DETAILED.getSymbol()).getReportName();

            //跳转链接
            String linkUrl = MessageFormat.format(hereLink + "?fromPage=email&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;
        }

    }