# GuestsInHouseComplimentaryTask.java

    package cloud.wconnect.frontoffice.businesstask.comproom;

    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.comproom.CompRoomNotifyConfigTypeEnum;
    import cloud.wconnect.frontoffice.entity.comproom.CompRoomEmailConfig;
    import cloud.wconnect.frontoffice.entity.comproom.CompRoomEmailTarget;
    import cloud.wconnect.frontoffice.entity.comproom.CompRoomScheduler;
    import cloud.wconnect.frontoffice.service.comproom.ICompRoomEmailConfigService;
    import cloud.wconnect.frontoffice.service.comproom.ICompRoomEmailTargetService;
    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;

    /**
     * 定时任务：检查Guests In-House Complimentary报告 是否存在数据缺失
     * 报告生成频率是：9:30 AM、11:30 AM、11:30 PM
     * @author lichen
     * @date 2023/8/7
     */
    @Slf4j
    @Component
    public class GuestsInHouseComplimentaryTask {

        @Autowired
        private CheckReportMissedService checkReportMissedService;
        @Value("${default.timezone}")
        private String defaultTimezone;
        @Autowired
        private PropertyInternalService propertyInternalService;
        @Autowired
        private PropertyI18nRedisService propertyI18nRedisService;
        @Autowired
        private ICompRoomEmailConfigService compRoomEmailConfigService;
        @Autowired
        private LineMessageUtil lineMessageUtil;
        @Autowired
        private I18nMessageUtils i18nMessageUtils;
        @Autowired
        private ICompRoomEmailTargetService emailTargetService;
        @Autowired
        private BeanMapper beanMapper;
        @Autowired
        private ObjectMapper objectMapper;
        @Autowired
        private TemplateEngine templateEngine;
        @Value("${here.link.comp-room}")
        private String hereLink;

        /**
         * 检查报告是否缺失
         */
        @Async
        public void dataMissingCheck(CompRoomScheduler scheduler) {
            log.info("GuestsInHouseComplimentaryTask.dataMissingCheck start...");
            //查询资产集合
            Integer propertyId = scheduler.getPropertyId();
            PropertyDTO propertyDTO = propertyI18nRedisService.get(propertyId);
            if (!propertyDTO.getStatus()) return;

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

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

            //阈值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(BusinessEnum.COMP_ROOM.getBusiness())
                    .subject(EventSubjectEnum.GUESTS_IN_HOUSE_COMPLIMENTARY.getSubject())
                    .ruleClazzList(List.of(MissedRuleByThreshold.class))
                    .propertyDTO(propertyDTO)
                    .notifyDTO(notifyDTO)
                    .thresholdDTO(thresholdDTO)
                    .build();
            checkReportMissedService.doCheck(job);
            log.info("GuestsInHouseComplimentaryTask.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, CompRoomEmailConfig emailConfig, List<CompRoomEmailTarget> emailTargets, int notifyType) {
            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.COMP_ROOM, language);

            //默认主题的国际化code
            String defaultSubjectI18nCode = CompRoomNotifyConfigTypeEnum.getDefaultSubjectI18nCode(notifyType);
            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.COMP_ROOM_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.GUEST_INH_COMPLIMENTARY.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();

            //line通知内容
            JSONObject lineMsg = lineMessageUtil.generateReportMissedMsg(reportMissedMsgParm);
            notifyDTO.setLineContent(Lists.newArrayList(lineMsg));
            return notifyDTO;
        }

    }