# ApiOtaParseServiceByOpera.java

    package cloud.wconnect.finance.service.api.acota;

    import cloud.wconnect.commonlib.cons.BaseConstant;
    import cloud.wconnect.commonlib.cons.BaseErrorCodeEnum;
    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.PropertyDTO;
    import cloud.wconnect.commonlib.util.DateTimeUtils;
    import cloud.wconnect.commonlib.util.FileCheckUtils;
    import cloud.wconnect.commonlib.util.InternationalizationUtils;
    import cloud.wconnect.commonlib.util.UploadUtils;
    import cloud.wconnect.finance.pojo.bo.api.ota.AcOtaBO;
    import cloud.wconnect.finance.pojo.bo.api.ota.AcOtaListBO;
    import cloud.wconnect.finance.service.api.IAcApiService;
    import com.baomidou.dynamic.datasource.annotation.DS;
    import com.google.common.collect.Lists;
    import jakarta.annotation.Resource;
    import lombok.extern.slf4j.Slf4j;
    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.Value;
    import org.springframework.stereotype.Component;
    import org.springframework.web.multipart.MultipartFile;

    import java.io.InputStream;
    import java.math.BigDecimal;
    import java.math.RoundingMode;
    import java.time.LocalDate;
    import java.time.format.DateTimeFormatter;
    import java.util.Collections;
    import java.util.List;
    import java.util.Locale;

    /**
     * OTA opera 报告
     *
     * @author zc
     * @date 2023/08/09
     */
    @Slf4j
    @Component
    @DS("finance")
    public class ApiOtaParseServiceByOpera implements IApiOtaParseService {
        @Resource
        private IAcApiService acApiService;

        @Value("${file-max-size.import-report.api}")
        private long fileMaxSize;

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

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

        /**
         * 处理数据
         *
         * @param propertyDTO 资产
         * @param files        文件
         * @param batchNo     批次编号
         * @author zc
         * @date 2024/8/22
         */
        @Override
        public void handleData(PropertyDTO propertyDTO, MultipartFile[] files, String batchNo) {
            List<AcOtaListBO> otaList = Lists.newArrayList();
            for (MultipartFile file : files) {
                try (InputStream inputStream = file.getInputStream()) {
                    otaList.addAll(parse(propertyDTO, inputStream));
                } catch (ParseReportException e) {
                    throw e;
                } catch (Exception e) {
                    throw new InternalServerErrorException(BaseErrorCodeEnum.SYSTEM_ERROR.getI18nCode(),
                            BaseErrorCodeEnum.SYSTEM_ERROR.getCode(),
                            "Parse API Commission OTA Opera report error", e);
                }
            }

            AcOtaBO otaBO = AcOtaBO.builder()
                    .batchNo(batchNo)
                    .list(otaList)
                    .build();
            acApiService.handleImportOtaReport(propertyDTO, otaBO);
        }

        /**
         * 解析报告
         *
         * @param propertyDTO 资产
         * @param in          报告
         * @return AcOtaListBO 集合
         * @author zc
         * @date 2023/8/9
         */
        @Override
        public List<AcOtaListBO> parse(PropertyDTO propertyDTO, InputStream in) throws ParseReportException {
            try {
                Document document = new SAXReader().read(in);
                List<Node> nodes = document.selectNodes("//G_C30");
                if (nodes.isEmpty()) {
                    return Collections.emptyList();
                }

                RoundingMode roundingMode = InternationalizationUtils.getRoundingMode(propertyDTO
                        .getInternationalization().getNumber().getCalculationRule());

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

                    AcOtaListBO acOtaListBo = new AcOtaListBO();
                    // crs no
                    acOtaListBo.setCrsNo(element.elementText("C57"));
                    // arrival date
                    acOtaListBo.setArrivalDateStr(transformDateStr(element.elementText("C63")));
                    // departure date
                    acOtaListBo.setDepartureDateStr(transformDateStr(element.elementText("C69")));
                    // last name
                    acOtaListBo.setLastName(element.elementText("C75"));
                    // first name
                    acOtaListBo.setFirstName(element.elementText("C78"));
                    // room revenue
                    String roomRevenueStr = element.elementText("C108").trim();
                    acOtaListBo.setRoomRevenue(StringUtils.isBlank(roomRevenueStr) ?
                            BigDecimal.ZERO : new BigDecimal(roomRevenueStr).setScale(BaseConstant.DATA_PRECISION, roundingMode));
                    // nights
                    acOtaListBo.setNights(Integer.parseInt(element.elementText("C114")));

                    resultList.add(acOtaListBo);
                }
                return resultList;
            } catch (DocumentException e) {
                log.error(e.getMessage(), e);
                throw new InternalServerErrorException(BaseErrorCodeEnum.SYSTEM_ERROR.getI18nCode(),
                        BaseErrorCodeEnum.SYSTEM_ERROR.getCode(),
                        "Handle parse API Commission OTA Opera report error", e);
            }
        }

        /**
         * 转换日期字符串
         *
         * @param dateStr 日期字符串（例：28-FEB-22）
         * @return yyyy-MM-dd
         * @author zc
         * @date 2023/8/9
         */
        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);
        }

    }