# TaOtaParseServiceByOpera.java

    package cloud.wconnect.finance.service.ta.ota;

    import cloud.wconnect.commonlib.cons.BaseConstant;
    import cloud.wconnect.commonlib.cons.BaseErrorCodeEnum;
    import cloud.wconnect.commonlib.cons.EventBodyParamEnum;
    import cloud.wconnect.commonlib.cons.SystemPlatformEnum;
    import cloud.wconnect.commonlib.exception.BadRequestException;
    import cloud.wconnect.commonlib.exception.InternalServerErrorException;
    import cloud.wconnect.commonlib.exception.ParseReportException;
    import cloud.wconnect.commonlib.pojo.dto.EventBodyDTO;
    import cloud.wconnect.commonlib.pojo.dto.PropertyDTO;
    import cloud.wconnect.commonlib.util.DateTimeUtils;
    import cloud.wconnect.commonlib.util.FileCheckUtils;
    import cloud.wconnect.commonlib.util.JsonUtils;
    import cloud.wconnect.commonlib.util.UploadUtils;
    import cloud.wconnect.finance.cons.BusinessEnum;
    import cloud.wconnect.finance.cons.EventSubjectEnum;
    import cloud.wconnect.finance.pojo.bo.ta.ota.TaOtaListBO;
    import cloud.wconnect.finance.pojo.dto.ta.compare.TaCompareOtaRateCodeDTO;
    import cloud.wconnect.finance.service.AmazonS3Service;
    import cloud.wconnect.finance.service.ta.ITaCompareOtaRateCodeConfigService;
    import cloud.wconnect.sns.http.processor.Sender;
    import com.baomidou.dynamic.datasource.annotation.DS;
    import com.fasterxml.jackson.databind.ObjectMapper;
    import com.google.common.collect.Lists;
    import com.google.common.collect.Maps;
    import lombok.extern.slf4j.Slf4j;
    import org.apache.commons.collections.CollectionUtils;
    import org.apache.commons.lang3.StringUtils;
    import org.dom4j.Document;
    import org.dom4j.DocumentException;
    import org.dom4j.Element;
    import org.dom4j.Node;
    import org.dom4j.io.SAXReader;
    import org.springframework.beans.factory.annotation.Qualifier;
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.stereotype.Component;
    import org.springframework.web.multipart.MultipartFile;

    import jakarta.annotation.Resource;
    import java.io.InputStream;
    import java.time.LocalDate;
    import java.time.format.DateTimeFormatter;
    import java.util.Collections;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Locale;
    import java.util.stream.Collectors;

    /**
     * 解析 Opera 系统的 OTA 报告
     *
     * @author zc
     * @date 2023/07/19
     */
    @Slf4j
    @Component
    @DS("finance")
    public class TaOtaParseServiceByOpera implements ITaOtaParseService {

        @Resource
        private ITaCompareOtaRateCodeConfigService rateCodeConfigService;
        @Resource
        private AmazonS3Service amazonS3Service;
        @Resource
        private ObjectMapper objectMapper;
        @Resource
        @Qualifier("3pSender")
        private Sender snsSender;

        @Value("${aws-s3.third-party.key.ta-commission.ota}")
        private String s3FilePath;
        @Value("${file-max-size.import-report.ta}")
        private long fileMaxSize;

        /**
         * 支持的报告来源
         *
         * @param source 报告来源
         * @return boolean
         * @author zc
         * @date 2023/7/19
         */
        @Override
        public boolean supports(String source) {
            return SystemPlatformEnum.OPERA.getDesc().equals(source);
        }

        /**
         * 校验文件是否合法
         *
         * @param propertyDTO 资产
         * @param file        文件
         * @author zc
         * @date 2024/8/21
         */
        @Override
        public void checkFile(PropertyDTO propertyDTO, MultipartFile file) {
            // 限制文件大小
            FileCheckUtils.checkFileSize(file, fileMaxSize);
            // 校验文件格式
            UploadUtils.checkFileFormat(file, Lists.newArrayList("xml"));
            // 校验文件内容
            try (InputStream inputStream = file.getInputStream()) {
                FileCheckUtils.checkTaOtaFile(inputStream);
            } catch (BadRequestException e) {
                throw e;
            } catch (Exception e) {
                throw new InternalServerErrorException(BaseErrorCodeEnum.SYSTEM_ERROR.getI18nCode(),
                        BaseErrorCodeEnum.SYSTEM_ERROR.getCode(),
                        "Check TA OTA Opera report error", e);
            }
        }

        /**
         * 处理数据
         *
         * @param propertyDTO 资产
         * @param file        文件
         * @param date        报告数据日期(时间戳)
         * @param logId       日志 id
         * @param operatorId  操作人 id
         * @author zc
         * @date 2024/8/21
         */
        @Override
        public void handleData(PropertyDTO propertyDTO, MultipartFile file, long date, long logId, int operatorId) {
            try {
                String key = propertyDTO.getTenantSymbol() + "/" + propertyDTO.getAbbr() + "/" + s3FilePath
                        + UploadUtils.getRandomFileName(file.getOriginalFilename());

                // 上传报告到 S3 服务器，用于事件监听解析报告
                amazonS3Service.uploadFile(file, key);

                // 封装事件体
                HashMap<String, Object> parameter = Maps.newHashMap();
                parameter.put(EventBodyParamEnum.TENANT_SYMBOL.getDesc(), propertyDTO.getTenantSymbol());
                parameter.put(EventBodyParamEnum.PROPERTY_ABBR.getDesc(), Lists.newArrayList(propertyDTO.getAbbr()));
                parameter.put(EventBodyParamEnum.ORIGINATE_FROM.getDesc(), BusinessEnum.TA.getBusiness());
                parameter.put(EventBodyParamEnum.SOURCE.getDesc(), SystemPlatformEnum.OPERA.getDesc());
                parameter.put(EventBodyParamEnum.UID.getDesc(), operatorId);
                parameter.put(EventBodyParamEnum.ID.getDesc(), logId);
                parameter.put(EventBodyParamEnum.DATE.getDesc(), date);

                // 发送事件
                snsSender.publish(EventSubjectEnum.OTA.getSubject(),
                        JsonUtils.convertObjToString(objectMapper, new EventBodyDTO(key, parameter)));
            } catch (Exception e) {
                throw new InternalServerErrorException(BaseErrorCodeEnum.SYSTEM_ERROR.getI18nCode(),
                        BaseErrorCodeEnum.SYSTEM_ERROR.getCode(),
                        "Handle import OTA Opera report exception", e);
            }
        }

        /**
         * 解析报告
         *
         * @param propertyDTO 资产 id
         * @param in          文件流
         * @return TaOtaListBO 集合
         * @author zc
         * @date 2023/7/19
         */
        @Override
        public List<TaOtaListBO> parse(PropertyDTO propertyDTO, InputStream in) throws ParseReportException {
            // 获取过滤条件
            List<String> otaRateCodeList = rateCodeConfigService.list(propertyDTO.getId()).stream()
                    .map(TaCompareOtaRateCodeDTO::getRateCode).collect(Collectors.toList());
            try {
                Document document = new SAXReader().read(in);
                List<Node> nodes = document.selectNodes("//G_C6");
                if (nodes.isEmpty()) {
                    return Collections.emptyList();
                }

                List<TaOtaListBO> taOtaList = Lists.newArrayList();
                for (Node node : nodes) {
                    Element element = (Element) node;

                    if (CollectionUtils.isNotEmpty(otaRateCodeList)
                            && !otaRateCodeList.contains(element.elementText("C30"))) {
                        continue;
                    }

                    TaOtaListBO taOta = new TaOtaListBO();
                    taOta.setName(element.elementText("C24"));
                    taOta.setArrivalDay(transformDateStr(element.elementText("C12")));
                    taOta.setDepartureDay(transformDateStr(element.elementText("C18")));
                    taOtaList.add(taOta);
                }
                return taOtaList;
            } catch (DocumentException e) {
                log.error(e.getMessage(), e);
                throw new InternalServerErrorException(BaseErrorCodeEnum.SYSTEM_ERROR.getI18nCode(),
                        BaseErrorCodeEnum.SYSTEM_ERROR.getCode(),
                        "Handle parse OTA Opera report exception", e);
            }
        }

        /**
         * 转换日期字符串
         *
         * @param dateStr 日期字符串（例：28-FEB-22）
         * @return yyyyMMdd
         * @author zc
         * @date 2023/7/19
         */
        private String transformDateStr(String dateStr) {
            DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(BaseConstant.DATE_FORMAT_DD_MMM_YY, Locale.ENGLISH);
            String[] dateArr = StringUtils.split(dateStr, "-");
            dateArr[1] = DateTimeUtils.capitalize(dateArr[1]);
            return DateTimeUtils.localDateToStr(LocalDate.parse(String.join("-", dateArr), dateTimeFormatter),
                    BaseConstant.DATE_FORMAT_YYYY_MM_DD);
        }
    }