# ScheduleEmployeeListener.java

    package cloud.wconnect.workperformance.messagelistener.schedule;

    import cloud.wconnect.commonlib.cons.EventBodyParamEnum;
    import cloud.wconnect.commonlib.cons.EventRedisKeyPrefixEnum;
    import cloud.wconnect.commonlib.cons.FunctionIdConstant;
    import cloud.wconnect.commonlib.cons.ReportImportResultCons;
    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.sns.http.entity.SnsHttpEvent;
    import cloud.wconnect.workperformance.cons.BusinessEnum;
    import cloud.wconnect.workperformance.cons.EventSubjectEnum;
    import cloud.wconnect.workperformance.cons.S3BucketFunctionCons;
    import cloud.wconnect.workperformance.entity.schedule.ScheduleDepartmentEmployeeImportLog;
    import cloud.wconnect.workperformance.pojo.bo.schedule.ScheduleDepartmentEmployeeBO;
    import cloud.wconnect.workperformance.service.AmazonS3Service;
    import cloud.wconnect.workperformance.service.schedule.IScheduleDepartmentEmployeeImportLogService;
    import cloud.wconnect.workperformance.service.schedule.IScheduleDepartmentEmployeeService;
    import cloud.wconnect.workperformance.service.schedule.employee.IEmployeeFileParse;
    import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
    import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
    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.collections.CollectionUtils;
    import org.apache.commons.lang3.StringUtils;
    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.Component;

    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.text.MessageFormat;
    import java.util.List;
    import java.util.Map;
    import java.util.Objects;
    import java.util.concurrent.TimeUnit;
    import java.util.stream.Collectors;

    /**
     * Employee 报告事件处理
     *
     * @author yyt
     * 2023/7/6
     */
    @Slf4j
    @Component
    public class ScheduleEmployeeListener {

        @Resource
        private ObjectMapper objectMapper;
        @Resource
        private ApplicationContext applicationContext;
        @Resource
        private RedisTemplate<String, Object> jsonRedisTemplate;
        @Resource
        private PropertyInternalService propertyInternalService;
        @Resource
        private MailInternalService mailInternalService;
        @Resource
        private AmazonS3Service amazonS3Service;
        @Resource
        private IScheduleDepartmentEmployeeService scheduleDepartmentEmployeeService;
        @Resource
        private IScheduleDepartmentEmployeeImportLogService scheduleDepartmentEmployeeImportLogService;
        @Resource
        private CommonService commonService;

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

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

        private final String BUSINESS = BusinessEnum.SCHEDULE_EMPLOYEE.getBusiness();

        /**
         * 监听 employee 报告
         *
         * @param event 事件
         * @author yyt
         * @date 2023/7/7
         */
        @Async
        @EventListener
        public void handle(SnsHttpEvent event) {
            // 校验 subject
            if (!StringUtils.equals(event.getSubject(), SUBJECT)) {
                return;
            }
            log.info("ScheduleEmployeeListener.start...");
            // 防止并发
            if (!preventConcurrency(event.getMessageId())) {
                log.warn("ScheduleEmployeeListener.end... a machine has been executed.");
                return;
            }
            // 校验 事件体 信息
            if (StringUtils.isBlank(event.getBody())) {
                log.warn("ScheduleEmployeeListener.end... event body is blank.");
                return;
            }

            EventBodyDTO eventBodyDTO = JsonUtils.convertStringToObject(objectMapper, event.getBody(), EventBodyDTO.class);
            Map<String, Object> parameter = eventBodyDTO.getParameter();

            String tenantAbbrName = (String) parameter.get(EventBodyParamEnum.TENANT_SYMBOL.getDesc());
            List<String> propertyAbbrNameList = (List<String>) parameter.get(EventBodyParamEnum.PROPERTY_ABBR.getDesc());
            List<PropertyDTO> properties = propertyInternalService.getProperty(propertyAbbrNameList, tenantAbbrName);
            if (CollectionUtils.isEmpty(properties)) {
                log.warn("ScheduleEmployeeListener.end... the property is not exist;property:{}", propertyAbbrNameList);
                return;
            }
            properties = properties.stream().filter(PropertyDTO::getStatus).collect(Collectors.toList());
            if (properties.isEmpty()) {
                log.warn("ScheduleEmployeeListener.end... the property is closed;property:{}", propertyAbbrNameList);
                return;
            }
            properties = properties.stream().filter(item-> commonService.checkOpenFunction(item, FunctionIdConstant.SCHEDULE)).toList();
            if (CollectionUtils.isEmpty(properties)) {
                log.warn("ScheduleEmployeeListener.end... the property has not opened schedule function;property:{}", propertyAbbrNameList);
                return;
            }

            int operatorId = Integer.parseInt(parameter.get(EventBodyParamEnum.UID.getDesc()).toString());
            boolean handleResult = true;
            String path = eventBodyDTO.getPath();
            try {

                try (InputStream inputStream = amazonS3Service.getFile(path)) {
                    amazonS3Service.uploadFile(S3BucketFunctionCons.SCHEDULE_IMPORT_RECORD, inputStream, path);
                }

                // 解析报告数据
                Map<Integer, List<ScheduleDepartmentEmployeeBO>> employeeInfoByPropertyId = parseReport(eventBodyDTO,
                        properties.stream().map(PropertyDTO::getId).collect(Collectors.toList()));
                scheduleDepartmentEmployeeService.handleEmployeeReportData(properties, employeeInfoByPropertyId, operatorId);
            } catch (Exception e) {
                handleResult = false;
                String propertyAbbrs = propertyAbbrNameList.stream().sorted().collect(Collectors.joining(","));
                if (RateLimitUtils.tryAcquire(this, propertyAbbrs)) {
                    sendAlertEmail(propertyAbbrs, e.getMessage(), eventBodyDTO.getPath());
                }
                log.error("ScheduleEmployeeListener.end... parse report error.");
            } finally {
                // 自动导入报告时插入处理时机，用于定时检查报告缺失逻辑
                if (operatorId == 0) {
                    properties.forEach(item -> updateLastTime(item.getAbbr()));
                }

                // 系统自动导入
                if (operatorId == 0) {
                    int importResult = handleResult ? ReportImportResultCons.IMPORT_RESULT_SUCCESS :
                            ReportImportResultCons.IMPORT_RESULT_FAIL;
                    scheduleDepartmentEmployeeImportLogService.addBatch(properties.stream().map(PropertyDTO::getId).toList(),
                            path, importResult, operatorId);
                } else {
                    String eventBusiness = parameter.get(EventBodyParamEnum.ORIGINATE_FROM.getDesc()).toString();
                    if (BUSINESS.equals(eventBusiness)) {
                        List<Integer> importLogIds = JsonUtils.convertStringToList(objectMapper, parameter.get(EventBodyParamEnum.ID.getDesc())
                                .toString(), Integer.class);
                        if (CollectionUtils.isNotEmpty(importLogIds)) {
                            int status = handleResult ? ReportImportResultCons.IMPORT_RESULT_SUCCESS : ReportImportResultCons.IMPORT_RESULT_FAIL;
                            LambdaUpdateWrapper<ScheduleDepartmentEmployeeImportLog> sql = new UpdateWrapper<ScheduleDepartmentEmployeeImportLog>().lambda()
                                    .in(ScheduleDepartmentEmployeeImportLog::getId, importLogIds)
                                    .set(ScheduleDepartmentEmployeeImportLog::getUrl, path)
                                    .set(ScheduleDepartmentEmployeeImportLog::getImportResult, status);

                            ScheduleDepartmentEmployeeImportLog importLog = scheduleDepartmentEmployeeImportLogService.getById(importLogIds.get(0));
                            if (importLog.getImportResult() == ReportImportResultCons.IMPORT_RESULT_REPAIRING) {
                                sql.set(ScheduleDepartmentEmployeeImportLog::getResolvedBy, handleResult ? operatorId : 0)
                                        .set(ScheduleDepartmentEmployeeImportLog::getResolvedTime, handleResult ? DateTimeUtils.nowTimestamp() : 0L);
                            }

                            scheduleDepartmentEmployeeImportLogService.update(sql);
                        }
                    } else {
                        scheduleDepartmentEmployeeImportLogService.addBatch(properties.stream().map(PropertyDTO::getId).toList(),
                                path, handleResult ? ReportImportResultCons.IMPORT_RESULT_SUCCESS :
                                        ReportImportResultCons.IMPORT_RESULT_FAIL, operatorId);
                    }
                }
            }

            log.info("ScheduleEmployeeListener.end...");
        }

        /**
         * 解析报告数据
         *
         * @param eventBodyDTO 事件体
         * @param propertyIds  资产 id
         * @return department employee
         * @author yyt
         * @date 2023/7/7
         */
        private Map<Integer, List<ScheduleDepartmentEmployeeBO>> parseReport(EventBodyDTO eventBodyDTO, List<Integer> propertyIds) {
            Map<String, Object> parameter = eventBodyDTO.getParameter();
            String source = (String) parameter.get(EventBodyParamEnum.SOURCE.getDesc());
            String path = eventBodyDTO.getPath();

            Map<Integer, List<ScheduleDepartmentEmployeeBO>> departmentEmployees = null;
            Map<String, IEmployeeFileParse> beansOfType = applicationContext.getBeansOfType(IEmployeeFileParse.class);
            for (IEmployeeFileParse bean : beansOfType.values()) {
                if (bean.supports(source)) {
                    try (InputStreamReader inputStreamReader = new InputStreamReader(amazonS3Service.getFile(path), "GBK")) {
                        departmentEmployees = bean.parsReport(inputStreamReader, propertyIds);
                    } catch (Exception e) {
                        throw new ListenerException("parse employee report error", e);
                    }
                    break;
                }
            }
            if (Objects.isNull(departmentEmployees)) {
                throw new ListenerException("the source is not exist; source: " + source);
            }

            return departmentEmployees;
        }

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

        /**
         * 发送预警邮件
         *
         * @param abbrName property abbr
         * @param content  邮件内容
         * @param path     文件路径
         * @author yyt
         * @date 2023/7/7
         */
        private void sendAlertEmail(String abbrName, String content, String path) {
            String subject = "[Warning] - Handle Employee Report Exception";
            String mailContent = MessageFormat.format("SNS Subject:{0}<br/>Business:{1}<br/>Property:{2}<br/>Content:{3}<br/>S3Key:{4}",
                    SUBJECT, BUSINESS, abbrName, content, path);
            mailInternalService.sendAlertEmail(subject, mailContent);
        }

        /**
         * 保存事件最近处理时刻
         *
         * @param propertyAbbr 资产缩写
         * @author yyt
         * @date 2023/11/20
         */
        private void updateLastTime(String propertyAbbr) {
            String key = EventRedisKeyPrefixEnum.KEY_PREFIX_FOR_PROCESSING.getDesc() +
                    StringUtils.join(Lists.newArrayList(SUBJECT, BUSINESS, propertyAbbr), ".");
            String value = String.valueOf(DateTimeUtils.dateTimeNow(defaultTimezone).toEpochSecond());
            jsonRedisTemplate.opsForValue().set(key, value);
        }

    }