# NotifyDraftNumberSummaryTask.java

    package cloud.wconnect.frontoffice.businesstask.adjustment;

    import cloud.wconnect.commonlib.component.BeanMapper;
    import cloud.wconnect.commonlib.cons.BaseConstant;
    import cloud.wconnect.commonlib.cons.FunctionCons;
    import cloud.wconnect.commonlib.pojo.dto.NotifyDTO;
    import cloud.wconnect.commonlib.pojo.dto.NotifyIdentityDTO;
    import cloud.wconnect.commonlib.pojo.dto.PropertyDTO;
    import cloud.wconnect.commonlib.pojo.dto.UserDTO;
    import cloud.wconnect.commonlib.pojo.dto.internationalization.InternationalizationDateTimeDTO;
    import cloud.wconnect.commonlib.pojo.dto.internationalization.InternationalizationNumberDTO;
    import cloud.wconnect.commonlib.pojo.dto.line.PublicFlexMsgParm;
    import cloud.wconnect.commonlib.redis.PropertyI18nRedisService;
    import cloud.wconnect.commonlib.service.MailInternalService;
    import cloud.wconnect.commonlib.service.NotifyInternalService;
    import cloud.wconnect.commonlib.service.UserInternalService;
    import cloud.wconnect.commonlib.util.*;
    import cloud.wconnect.frontoffice.cons.FunctionPointEnum;
    import cloud.wconnect.frontoffice.cons.I18nConstant;
    import cloud.wconnect.frontoffice.cons.adjustment.*;
    import cloud.wconnect.frontoffice.entity.adjustment.*;
    import cloud.wconnect.frontoffice.pojo.dto.adjustment.AdjEmailDTO;
    import cloud.wconnect.frontoffice.pojo.dto.adjustment.NotifyDraftNumSummaryDTO;
    import cloud.wconnect.frontoffice.service.adjustment.IAdRequestService;
    import cloud.wconnect.frontoffice.service.adjustment.IAdjEmailConfigService;
    import cloud.wconnect.frontoffice.service.adjustment.IAdjEmailTargetService;
    import cloud.wconnect.frontoffice.service.adjustment.IAdjNotifyRuleService;
    import com.alibaba.fastjson.JSONObject;
    import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
    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.*;
    import java.util.stream.Collectors;

    /**
     * draft数量汇总通知:每日通知部门负责人，责任人有多少draft数据需要处理
     *
     * @author lichen
     * @date 2024/8/23
     */
    @Slf4j
    @Component
    public class NotifyDraftNumberSummaryTask {

        @Autowired
        private PropertyI18nRedisService propertyI18nRedisService;
        @Autowired
        private IAdjEmailConfigService emailConfigService;
        @Autowired
        private IAdjEmailTargetService emailTargetService;
        @Autowired
        private IAdRequestService adRequestService;
        @Autowired
        private TemplateEngine templateEngine;
        @Autowired
        private NotifyInternalService notifyInternalService;
        @Autowired
        private LineMessageUtil lineMessageUtil;
        @Autowired
        private I18nMessageUtils i18nMessageUtils;
        @Value("${here.link.adjustment-requests}")
        private String adjustmentHereLink;
        @Value("${here.link.adjustment-requests-other}")
        private String adjustmentOtherHereLink;
        @Autowired
        private MailInternalService mailInternalService;
        @Autowired
        private UserInternalService userInternalService;
        @Autowired
        private BeanMapper beanMapper;
        @Autowired
        private IAdjNotifyRuleService notifyRuleService;

        /**
         * draft数量汇总通知:每日通知部门负责人，责任人有多少draft数据需要处理
         *
         * @param schedulerJob 调度任务
         * @author lichen
         * @date 2024/8/23
         */
        @Async
        public void notifyDraftNumberSummary(SchedulerJob schedulerJob) {
            try {
                PropertyDTO propertyDTO = propertyI18nRedisService.get(schedulerJob.getPropertyId());
                if (!propertyDTO.getStatus()) return;

                //查询邮件配置信息
                AdjEmailConfig emailConfig = emailConfigService.getByPropertyIdAndType(schedulerJob.getPropertyId(), schedulerJob.getCategory());
                if (Objects.isNull(emailConfig)) return;
                if (!emailConfig.getStatus()) {
                    log.info("NotifyDraftNumberSummaryTask.end, email config status is false, propertyId:{},schedulerJobId:{},type:{}",
                            propertyDTO.getId(), schedulerJob.getId(), schedulerJob.getCategory());
                    return;
                }

                List<AdjEmailTarget> emailTargets = emailTargetService.listByConfigId(Collections.singletonList(emailConfig.getId()));
                if (CollectionUtils.isEmpty(emailTargets)) return;
                //按照requestType分组
                Map<Integer, List<AdjEmailTarget>> requestType2EmailTargets = emailTargets.stream().collect(Collectors.groupingBy(AdjEmailTarget::getRequestType));

                //查询通知规则
                Long startDate = null;
                AdjNotifyRule notifyRule = notifyRuleService.getByPropertyIdAndType(propertyDTO.getId(), schedulerJob.getCategory());
                if (Objects.nonNull(notifyRule)) {
                    Object startDateObj = JSONObject.parseObject(notifyRule.getRule()).get(AdjNotifyRule.START_DATE);
                    if (Objects.nonNull(startDateObj)) {
                        startDate = DateTimeUtils.dateStrToEpochSecond(startDateObj.toString(), BaseConstant.DATE_FORMAT_YYYYMMDD, propertyDTO.getTimezone());
                    }
                }

                //查询draft的数据
                List<AdRequest> adRequests = adRequestService.list(new LambdaQueryWrapper<AdRequest>()
                        .eq(AdRequest::getPropertyId, propertyDTO.getId())
                        .eq(AdRequest::getFlowStatus, FlowStatusEnum.DRAFT.getFlowStatus())
                        .ne(AdRequest::getStatus, AdjustmentStatusEnum.CANCEL.getStatus())
                        .ge(Objects.nonNull(startDate), AdRequest::getCreateTime, startDate)
                        .orderByDesc(AdRequest::getId));
                //没有数据时，无需通知
                if (CollectionUtils.isEmpty(adRequests)) return;

                //查询用户姓名
                List<Integer> dutyUserIds = adRequests.stream().map(AdRequest::getDutyUser).toList();
                Map<Integer, String> userId2Name = userInternalService.getUsers(propertyDTO.getTenantId(), dutyUserIds)
                        .stream().collect(Collectors.toMap(UserDTO::getId, UserDTO::getName));

                Map<Integer, List<AdRequest>> requestType2AdRequests = adRequests.stream().collect(Collectors.groupingBy(AdRequest::getRequestType));
                for (Map.Entry<Integer, List<AdRequest>> entry : requestType2AdRequests.entrySet()) {
                    Integer requestType = entry.getKey();
                    List<AdRequest> adRequestByRequestType = entry.getValue();

                    //获取指定requestType下的邮件通知人
                    List<AdjEmailTarget> emailTargetsByRequestType = requestType2EmailTargets.get(requestType);

                    //指定requestType下的通知人、adjustment数据不为空时，才需要通知
                    if (CollectionUtils.isNotEmpty(emailTargetsByRequestType) && CollectionUtils.isNotEmpty(adRequestByRequestType)) {
                        //发送通知
                        sendNotify(propertyDTO, requestType, adRequestByRequestType, emailConfig, emailTargetsByRequestType, userId2Name, schedulerJob.getCategory());
                    }
                }
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                String alertEmailSubject = "[Warning] - Notify Draft number summary task";
                String alertEmailContent = MessageFormat.format("<p>propertyId:{0}</p>", schedulerJob.getPropertyId()) +
                        "<p>Exception occurred when notify Draft number summary task</p>" +
                        e.getMessage();
                mailInternalService.sendAlertEmail(alertEmailSubject, alertEmailContent);
            }
        }

        /**
         * 发送通知
         *
         * @param propertyDTO            资产DTO
         * @param requestType            调账类型
         * @param adRequestByRequestType 指定调账类型下的调账数据
         * @param emailConfig            邮件配置
         * @param emailTargets           邮件通知人集合
         * @param userId2Name            用户姓名
         * @param notifyType             通知类型
         * @author lichen
         * @date 2024/8/24
         */
        private void sendNotify(PropertyDTO propertyDTO, Integer requestType, List<AdRequest> adRequestByRequestType,
                                AdjEmailConfig emailConfig, List<AdjEmailTarget> emailTargets, Map<Integer, String> userId2Name, int notifyType) {
            //功能名称
            String functionName = i18nMessageUtils.message(FunctionCons.ADJUSTMENT_REQUESTS, propertyDTO.getLanguage());
            //构造NotifyDraftNumSummaryDTO对象
            ArrayList<NotifyDraftNumSummaryDTO> notifyDraftNumSummaryDTOS = Lists.newArrayList();
            if (requestType != 0) {//有责任人的数据
                //按照责任人分组
                Map<Integer, Long> dutyUser2Count = adRequestByRequestType.stream().collect(Collectors.groupingBy(AdRequest::getDutyUser, Collectors.counting()));

                dutyUser2Count.forEach((dutyUserId, count) -> {
                    notifyDraftNumSummaryDTOS.add(new NotifyDraftNumSummaryDTO(userId2Name.get(dutyUserId), count));
                });
            }

            //默认主题的国际化code
            String defaultSubjectI18nCode = AdjNotifyConfigTypeEnum.getDefaultSubjectI18nCode(notifyType);
            String defaultSubject = i18nMessageUtils.message(defaultSubjectI18nCode, propertyDTO.getLanguage(), functionName, propertyDTO.getName());

            //自定义主体优先，其次默认主题
            String subject = StringUtils.isNotBlank(emailConfig.getSubject()) ? emailConfig.getSubject() : defaultSubject;

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

            //生成邮件通知内容
            String link;
            if (requestType != 0) {
                link = adjustmentHereLink + MessageFormat.format("?fromPage=email&property={0}&tenant={1}&requestTypeList={2}&queryStatusList={3}",
                        propertyDTO.getAbbr(), propertyDTO.getTenantSymbol(), requestType, 1);
            } else {//other页面
                link = adjustmentOtherHereLink + MessageFormat.format("?property={0}&tenant={1}&activeKey=3",
                        propertyDTO.getAbbr(), propertyDTO.getTenantSymbol());
            }

            Context context = new Context();
            context.setVariable("propertyName", propertyDTO.getName());
            context.setVariable("functionName", functionName);
            context.setVariable("notifyDraftNumSummaryDTOS", notifyDraftNumSummaryDTOS);
            context.setVariable("hereLink", link);
            context.setVariable("requestTypeDesc", i18nMessageUtils.message(AdjTypeEnum.getI18nCode(requestType), propertyDTO.getLanguage()));
            context.setVariable("requestType", requestType);
            context.setVariable("total", adRequestByRequestType.size());
            //截取前10条数据
            List<AdRequest> subList = adRequestByRequestType.subList(0, Math.min(adRequestByRequestType.size(), 10));
            context.setVariable("adjList", convert(subList, propertyDTO, userId2Name));
            String mailBody = templateEngine.process("adjustment/adjustment-draft-all_" + propertyDTO.getLanguage(), context);
            notifyDTO.setEmailContent(EmailUtil.getFullEmailContent(defaultSubject, mailBody, propertyDTO.getLanguage()));

            LinkedHashMap<String, String> businessMap = new LinkedHashMap<>();
            businessMap.put(i18nMessageUtils.message(I18nConstant.I18N_TOTAL, propertyDTO.getLanguage()), adRequestByRequestType.size() + "");

            PublicFlexMsgParm publicFlexMsgParm = PublicFlexMsgParm.builder()
                    .propertyName(propertyDTO.getName())
                    .propertyId(propertyDTO.getId())
                    .functionName(functionName)
                    .title("Number of drafts statistics of each type")
                    .link(link)
                    .businessMap(businessMap)
                    .build();
            JSONObject lineContent = lineMessageUtil.generatePublicFlexMsg(publicFlexMsgParm);
            notifyDTO.setLineContent(Lists.newArrayList(lineContent));

            notifyInternalService.sendNotify(notifyDTO);
        }

        /**
         * AdRequest -> AdjEmailDTO
         *
         * @param adRequests  adjustment 集合
         * @param propertyDTO 资产信息
         * @return cloud.wconnect.frontoffice.pojo.dto.adjustment.AdjEmailDTO
         * @author lichen
         * @date 2024/9/11
         */
        private List<AdjEmailDTO> convert(List<AdRequest> adRequests, PropertyDTO propertyDTO, Map<Integer, String> userId2Name) {
            String timezone = propertyDTO.getTimezone();
            //配置的日期格式
            InternationalizationDateTimeDTO dateTime = propertyDTO.getInternationalization().getDateTime();
            String longDateFormat = dateTime.getLongDate();
            String hourClock = dateTime.getHourClock();
            InternationalizationNumberDTO number = propertyDTO.getInternationalization().getNumber();
            //获取货币符号
            String currency = number.getCurrency();
            //语言
            String language = propertyDTO.getLanguage();

            String matched = i18nMessageUtils.message(AdjFieldI18nConstant.MATCHED, language);
            String unMatched = i18nMessageUtils.message(AdjFieldI18nConstant.UN_MATCHED, language);
            return beanMapper.mapList(adRequests, AdjEmailDTO.class, (adRequest, adjEmailDTO) -> {
                if (StringUtils.isBlank(adRequest.getRoomNumber())) {
                    adjEmailDTO.setRoomNumber("--");
                }
                if (StringUtils.isBlank(adRequest.getGuestName())) {
                    adjEmailDTO.setGuestName("--");
                }
                //格式化金额
                String totalAmountStr = InternationalizationUtils.formatAmountViewValue(adRequest.getAdjustedDollar(), number.getCalculationRule(), currency);
                adjEmailDTO.setFormatAdjustedDollar(totalAmountStr);
                //拼装dutyUser
                Integer dutyUser = adRequest.getDutyUser();
                adjEmailDTO.setDutyByName(userId2Name.getOrDefault(dutyUser, "--"));
                //拼装createTimeStr
                adjEmailDTO.setCreateTimeStr(InternationalizationUtils.formatDateTime(adRequest.getCreateTime(),
                        longDateFormat, hourClock, timezone, language));
                //拼装businessDateStr
                if (adRequest.getBusinessDate() > 0) {
                    adjEmailDTO.setBusinessDateStr(InternationalizationUtils.formatDateTime(
                            DateTimeUtils.dateStrToEpochSecond(adRequest.getBusinessDate().toString(), BaseConstant.DATE_FORMAT_YYYYMMDD, timezone),
                            longDateFormat, "", timezone, language));
                } else {
                    adjEmailDTO.setBusinessDateStr("--");
                }
                //设置匹配状态
                adjEmailDTO.setMatchStatusStr(adRequest.getBusinessDate() > 0 ? matched : unMatched);
            });
        }

    }