# HouseStatusServiceListener.java

    package cloud.wconnect.frontoffice.messagelistener.endofshift;

    import cloud.wconnect.commonlib.cons.EventBodyParamEnum;
    import cloud.wconnect.commonlib.cons.FunctionIdConstant;
    import cloud.wconnect.commonlib.exception.ListenerException;
    import cloud.wconnect.commonlib.pojo.dto.EventBodyDTO;
    import cloud.wconnect.commonlib.pojo.dto.PropertyDTO;
    import cloud.wconnect.commonlib.service.CommonService;
    import cloud.wconnect.commonlib.service.MailInternalService;
    import cloud.wconnect.commonlib.service.PropertyInternalService;
    import cloud.wconnect.commonlib.util.DateTimeUtils;
    import cloud.wconnect.commonlib.util.JsonUtils;
    import cloud.wconnect.commonlib.util.RateLimitUtils;
    import cloud.wconnect.frontoffice.cons.BusinessEnum;
    import cloud.wconnect.frontoffice.cons.EventSubjectEnum;
    import cloud.wconnect.frontoffice.parsereport.endofshift.IParseHouseStatusService;
    import cloud.wconnect.frontoffice.pojo.dto.endofshift.report.HouseStatusServiceDTO;
    import cloud.wconnect.frontoffice.service.endofshift.IShiftReportInfoService;
    import cloud.wconnect.sns.http.entity.SnsHttpEvent;
    import com.fasterxml.jackson.databind.ObjectMapper;
    import com.google.common.collect.Lists;
    import jakarta.annotation.Resource;
    import lombok.extern.slf4j.Slf4j;
    import org.apache.commons.lang3.StringUtils;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.event.EventListener;
    import org.springframework.data.redis.core.RedisTemplate;
    import org.springframework.scheduling.annotation.Async;
    import org.springframework.stereotype.Service;

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

    /**
     * @author lichen
     * @description 《house staus/service 0d》 报告处理
     * 获取每个酒店Opera系统中的House Status报告，用于End of Shift Report功能
     * 每小时 20 分	当天数据
     * @date 2023/3/9 9:28
     */
    @Slf4j
    @Service
    public class HouseStatusServiceListener {

        @Autowired
        private RedisTemplate<String, Object> redisTemplate;
        @Autowired
        private PropertyInternalService propertyInternalService;
        @Autowired
        private IShiftReportInfoService shiftReportInfoService;
        @Autowired
        private ObjectMapper objectMapper;
        @Autowired
        private MailInternalService mailInternalService;
        @Autowired
        private ApplicationContext applicationContext;
        @Resource
        private CommonService commonService;
        /**
         * subject
         */
        private final static String SUBJECT = EventSubjectEnum.HOUSE_STATUS.getSubject();
        /**
         * 业务名称
         */
        private final static String BUSINESS = BusinessEnum.END_OF_SHIFT_REPORT.getBusiness();
        private static final String KEY_PREFIX_FOR_MESSAGE = "wconnect:event:message:";
        private static final String KEY_PREFIX_FOR_PROCESSING = "wconnect:event:processing:";
        @Value("${default.timezone}")
        private String defaultTimezone;

        /**
         * @param event
         * @return void
         * @description 一个资产一个报告，投递一份消息
         * @author lichen
         * @date 2023/3/9 14:40
         */
        @Async
        @EventListener
        public void handle(SnsHttpEvent event) {
            if (!StringUtils.equals(SUBJECT, event.getSubject())) {
                return;
            }

            if (!preventConcurrency(event.getMessageId())) {
                return;
            }

            if (StringUtils.isBlank(event.getBody())) {
                return;
            }
            String propertyAbbrName = "";
            EventBodyDTO eventBodyDTO = JsonUtils.convertStringToObject(objectMapper, event.getBody(), EventBodyDTO.class);
            try {
                //资产简称
                Map<String, Object> parameter = eventBodyDTO.getParameter();
                List<String> abbrNameList = (List<String>) parameter.get(EventBodyParamEnum.PROPERTY_ABBR.getDesc());
                propertyAbbrName = abbrNameList.get(0);
                //获取租户标识
                String tenantAbbr = (String) parameter.get(EventBodyParamEnum.TENANT_SYMBOL.getDesc());
                //远程调用basic模块查询资产信息
                PropertyDTO propertyDTO = propertyInternalService.getOne(propertyAbbrName, tenantAbbr);
                if (Objects.isNull(propertyDTO)) {
                    log.warn("The property is not exist; abbr name: {}", propertyAbbrName);
                    return;
                }
                if (!propertyDTO.getStatus()) {
                    log.warn("HouseStatusServiceListener.end The property is off; abbr name: {}", propertyAbbrName);
                    return;
                }

                String source = (String) parameter.get(EventBodyParamEnum.SOURCE.getDesc());
                if(!propertyDTO.getPmsType().equals(source)){
                    log.warn("HouseStatusServiceListener.handle end... property not support this pms type, propertyId:{}, supportPmsType:{}, currentPmsType:{}",
                            propertyDTO.getId(), propertyDTO.getPmsType(), source);
                    return;
                }

                if (!commonService.checkOpenFunction(propertyDTO, FunctionIdConstant.END_OF_SHIFT)) {
                    log.warn("HouseStatusServiceListener.end... the property has not opened the end of shift function;property:{}", propertyAbbrName);
                    return;
                }
                //将报告中的数据映射为House Status/Service实体类
                HouseStatusServiceDTO houseStatusServiceDTO = parseReport(eventBodyDTO);

                //更新House Status/Service数据
                shiftReportInfoService.updateHouseStatusData(propertyDTO, houseStatusServiceDTO);

                //保存报告最新处理时刻
                updateLastTime(propertyAbbrName);
            } catch (Exception e) {
                if (RateLimitUtils.tryAcquire(this, propertyAbbrName)) {
                    sendAlertEmail(propertyAbbrName, e.getMessage(), eventBodyDTO.getPath());
                }
                log.error("HouseStatusServiceListener error ", e);
            }
        }

        /**
         * 保存事件最近处理时刻
         *
         * @param abbrName 资产标识
         * @return void
         * @author lichen
         * @date 2023/5/20
         */
        private void updateLastTime(String abbrName) {
            //DateTimeUtils.nowTimestamp() 返回long 类型，存储进redis后，再获取是Integer类型。两边类型不一致，所以直接存储String类型
            redisTemplate.opsForValue().set(
                    KEY_PREFIX_FOR_PROCESSING + StringUtils.join(Lists.newArrayList(SUBJECT, BUSINESS, abbrName), "."),
                    String.valueOf(DateTimeUtils.dateTimeNowOfSecond(defaultTimezone)));
        }

        /**
         * 防止并发操作
         *
         * @param messageId 消息事件 id
         * @return boolean true：未并发，当前线程可以执行；false：检测到并发，当前线程应放弃执行
         * @author zc
         * @date 2023/2/8
         */
        private Boolean preventConcurrency(String messageId) {
            return redisTemplate.opsForValue().setIfAbsent(
                    KEY_PREFIX_FOR_MESSAGE + StringUtils.join(Lists.newArrayList(SUBJECT, BUSINESS, messageId), "."),
                    0L, 1, TimeUnit.DAYS);
        }

        /**
         * 发送预警邮件
         *
         * @param propertyAbbr 资产简称
         * @param exceptionMsg 报错内容
         * @param s3Key        s3路径
         * @return void
         * @author lichen
         * @date 2024/2/22
         */
        private void sendAlertEmail(String propertyAbbr, String exceptionMsg, String s3Key) {
            String subject = "[Warning] - Handle house staus/service report error";
            //邮件内容
            String mailContent = MessageFormat.format("SNS Subject:{0}<br/>Business:{1}<br/>Property:{2}<br/>Content:{3}<br/>S3Key:{4}",
                    SUBJECT, BUSINESS, propertyAbbr, exceptionMsg, s3Key);
            //发送alert
            mailInternalService.sendAlertEmail(subject, mailContent);
        }

        /**
         * @param eventBodyDTO 事件对象
         * @return cloud.wconnect.frontoffice.pojo.dto.endofshiftreport.report.HouseStatusServiceDTO
         * @description 解析House Status/Service 报告
         * @author lichen
         * @date 2023/3/10 11:11
         */
        private HouseStatusServiceDTO parseReport(EventBodyDTO eventBodyDTO) {
            Map<String, IParseHouseStatusService> parseHouseStatusServiceMap = applicationContext.getBeansOfType(IParseHouseStatusService.class);
            Collection<IParseHouseStatusService> parseHouseStatusServiceList = parseHouseStatusServiceMap.values();
            for (IParseHouseStatusService parser : parseHouseStatusServiceList) {
                String source = (String) eventBodyDTO.getParameter().get(EventBodyParamEnum.SOURCE.getDesc());
                if (parser.supports(source)) {
                    return parser.parse(eventBodyDTO.getPath());
                }
            }
            throw new ListenerException("not find report parser");
        }

    }