# GuestInHouseTask.java

    package cloud.wconnect.frontoffice.businesstask.clc;

    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.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.clc.CLCNotifyEnum;
    import cloud.wconnect.frontoffice.entity.clc.ClcEmailConfig;
    import cloud.wconnect.frontoffice.entity.clc.ClcEmailTarget;
    import cloud.wconnect.frontoffice.entity.clc.ClcSchedulerJob;
    import cloud.wconnect.frontoffice.pojo.dto.clc.ClcSchedulerDTO;
    import cloud.wconnect.frontoffice.service.clc.IClcEmailConfigService;
    import cloud.wconnect.frontoffice.service.clc.IClcEmailTargetService;
    import com.alibaba.fastjson.JSONObject;
    import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
    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.util.Collections;
    import java.util.List;
    import java.util.Objects;
    import java.util.concurrent.TimeUnit;

    /**
     * Guest In House 定时
     *
     * @author yyt
     * 2023/7/31
     */
    @Slf4j
    @Component
    public class GuestInHouseTask {

        @Autowired
        private IClcEmailConfigService clcEmailConfigService;
        @Autowired
        private PropertyInternalService propertyInternalService;
        @Autowired
        private PropertyI18nRedisService propertyI18nRedisService;
        @Autowired
        private IClcEmailTargetService clcEmailTargetService;
        @Autowired
        private CheckReportMissedService checkReportMissedService;
        @Autowired
        private LineMessageUtil lineMessageUtil;
        @Autowired
        private I18nMessageUtils i18nMessageUtils;
        @Autowired
        private BeanMapper beanMapper;
        @Autowired
        private ObjectMapper objectMapper;
        @Autowired
        private TemplateEngine templateEngine;

        @Value("${here.link.clc-missing-list}")
        private String hereLink;

        @Value("${default.timezone}")
        private String defaultTimezone;

        private static final String SUBJECT = EventSubjectEnum.GUEST_IN_HOUSE_SERVICE.getSubject();

        private static final String BUSINESS = BusinessEnum.CLC_GUEST_IN_HOUSE.getBusiness();

        /**
         * 检查报告是否缺失
         *
         * @param schedulerJob 定时任务
         * @author yyt
         * @date 2023/7/31
         */
        @Async
        public void reportMissCheck(ClcSchedulerJob schedulerJob) {
            log.info("GuestInHouseTask.reportMissCheck start...");

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

            // 查询邮件配置
            ClcEmailConfig emailConfig = clcEmailConfigService.getOne(new QueryWrapper<ClcEmailConfig>().lambda()
                    .eq(ClcEmailConfig::getType, ClcSchedulerDTO.MISSING_GUEST_IN_HOUSE_REPORT)
                    .eq(ClcEmailConfig::getPropertyId, propertyId)
                    .eq(ClcEmailConfig::getStatus, true));
            List<ClcEmailTarget> emailTargets = Collections.emptyList();
            if (Objects.nonNull(emailConfig)) {
                emailTargets = clcEmailTargetService.list(new QueryWrapper<ClcEmailTarget>()
                                .lambda().eq(ClcEmailTarget::getConfigId, emailConfig.getId())
                                .eq(ClcEmailTarget::getPropertyId, propertyId));
            }

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

            //资产配置的阈值集合
            JobParameterDTO jobParameterDTO = JsonUtils.convertStringToObject(objectMapper, schedulerJob.getParameters(), JobParameterDTO.class);
            ThresholdDTO thresholdDTO = new ThresholdDTO(jobParameterDTO.getThreshold(), TimeUnit.MINUTES, defaultTimezone);

            CheckReportMissedDTO check = CheckReportMissedDTO.builder()
                    .subject(SUBJECT)
                    .business(BUSINESS)
                    .propertyDTO(property)
                    .ruleClazzList(Collections.singletonList(MissedRuleByThreshold.class))
                    .notifyDTO(notifyDTO)
                    .thresholdDTO(thresholdDTO)
                    .build();
            checkReportMissedService.doCheck(check);

            log.info("GuestInHouseTask.reportMissCheck end...");
        }

        /**
         * 获取通知配置DTO
         *
         * @param propertyDTO 资产
         * @param emailConfig 邮件配置
         * @param targets     邮件通知人集合
         * @return 通知配置
         * @author lichen
         * @date 2023/12/14
         */
        private NotifyDTO getNotifyDTO(PropertyDTO propertyDTO, ClcEmailConfig emailConfig, List<ClcEmailTarget> targets) {
            if (CollectionUtils.isEmpty(targets)) {
                return null;
            }

            Integer propertyId = propertyDTO.getId();
            String propertyName = propertyDTO.getName();
            String language = propertyDTO.getLanguage();
            String defaultSubject = clcEmailConfigService.getDefaultSubject(propertyId, CLCNotifyEnum.MISSING_REPORT_GUEST_IN_HOUSE.getCode());

            NotifyDTO notifyDTO = new NotifyDTO();
            notifyDTO.setPropertyId(propertyId);
            notifyDTO.setFunctionPoint(FunctionPointEnum.CLC_PMS_REPORT_MISSED.getFunctionPoint());
            notifyDTO.setSubject(StringUtils.isNotBlank(emailConfig.getSubject()) ? emailConfig.getSubject() : defaultSubject);
            notifyDTO.setIdentityList(beanMapper.mapList(targets, NotifyIdentityDTO.class));

            //报告缺失日期 0d
            String timezone = propertyDTO.getTimezone();
            String missDate = InternationalizationUtils.formatDateTime(DateTimeUtils.dateNowTimestamp(timezone),
                    propertyDTO.getInternationalization().getDateTime().getLongDate(),
                    StringUtils.EMPTY, timezone, language);

            String functionName = i18nMessageUtils.message(FunctionCons.CLC_LIST, language);

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

            Context context = new Context();
            context.setVariable("propertyName", propertyName);
            context.setVariable("hereLink", hereLink + "?property=" + propertyDTO.getAbbr() + "&tenant=" + propertyDTO.getTenantSymbol());
            context.setVariable("functionName", functionName);
            context.setVariable("reportName", reportName);
            context.setVariable("reportDate", missDate);
            String emailContent = templateEngine.process(EmailUtil.getMissReportTemplateName(language), context);
            notifyDTO.setEmailContent(EmailUtil.getFullEmailContent(defaultSubject, emailContent, language));

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

    }