# ApiParseServiceByApi.java

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

    import cloud.wconnect.commonlib.cons.BaseConstant;
    import cloud.wconnect.commonlib.cons.BaseErrorCodeEnum;
    import cloud.wconnect.commonlib.cons.SystemPlatformEnum;
    import cloud.wconnect.commonlib.exception.InternalServerErrorException;
    import cloud.wconnect.commonlib.exception.ParseReportException;
    import cloud.wconnect.commonlib.pojo.dto.PropertyDTO;
    import cloud.wconnect.commonlib.util.*;
    import cloud.wconnect.finance.pojo.bo.api.api.AcApiBO;
    import cloud.wconnect.finance.pojo.bo.api.api.AcApiListBO;
    import cloud.wconnect.finance.pojo.dto.api.ConflictApiDTO;
    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.apache.poi.ss.usermodel.Row;
    import org.apache.poi.ss.usermodel.Sheet;
    import org.apache.poi.ss.usermodel.Workbook;
    import org.apache.poi.ss.usermodel.WorkbookFactory;
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.stereotype.Component;
    import org.springframework.web.multipart.MultipartFile;

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

    /**
     * API 报告
     *
     * @author zc
     * @date 2023/08/08
     */
    @Slf4j
    @Component
    @DS("finance")
    public class ApiParseServiceByApi implements IApiParseService {
        @Resource
        private IAcApiService acApiService;

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

        /**
         * 支持的报告来源
         *
         * @param source 报告来源
         * @return boolean
         * @author zc
         * @date 2023/8/8
         */
        @Override
        public boolean supports(String source) {
            return SystemPlatformEnum.API.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, com.google.common.collect.Lists.newArrayList("xls", "xlsx"));
        }

        /**
         * 处理数据
         *
         * @param propertyDTO 资产
         * @param file        文件
         * @param batchNo     批次编号
         * @return ConflictApiDTO
         * @author zc
         * @date 2024/8/22
         */
        @Override
        public ConflictApiDTO handleData(PropertyDTO propertyDTO, MultipartFile file, String batchNo) {
            try (InputStream in = file.getInputStream()) {
                // 处理 API 报告数据
                List<AcApiListBO> apiList = parse(propertyDTO, in);

                AcApiBO apiBO = AcApiBO.builder()
                        .batchNo(batchNo)
                        .list(apiList)
                        .build();
                return acApiService.handleImportApiReport(propertyDTO, apiBO);
            } catch (IOException e) {
                throw new InternalServerErrorException(BaseErrorCodeEnum.SYSTEM_ERROR.getI18nCode(),
                        BaseErrorCodeEnum.SYSTEM_ERROR.getCode(),
                        "Handle import API report error.", e);
            }
        }

        /**
         * 解析报告
         *
         * @param propertyDTO 资产
         * @param in          报告
         * @return ApiListBO 集合
         * @author zc
         * @date 2023/8/8
         */
        @Override
        public List<AcApiListBO> parse(PropertyDTO propertyDTO, InputStream in) throws ParseReportException {
            try(Workbook workbook = WorkbookFactory.create(in)) {
                List<AcApiListBO> resultList = Lists.newArrayList();

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

                for (int i = 0; i < workbook.getNumberOfSheets(); i++) {
                    Sheet sheet = workbook.getSheetAt(i);
                    // 跳过第一行的标题
                    for (int r = 1; r <= sheet.getLastRowNum(); r++) {
                        Row row = sheet.getRow(r);

                        AcApiListBO api = new AcApiListBO();
                        api.setInvoiceNo(sheet.getSheetName());
                        api.setAirline(CellUtils.convertCellStr(row.getCell(0)));
                        api.setConfNo(CellUtils.convertCellStr(row.getCell(1)));
                        api.setCheckInStr(formatDateStr(CellUtils.convertCellStr(row.getCell(2))));
                        api.setLastName(CellUtils.convertCellStr(row.getCell(3)));
                        api.setFirstName(CellUtils.convertCellStr(row.getCell(4)));

                        String roomCosts = CellUtils.convertCellStr(row.getCell(5)).trim();
                        api.setRoomCosts(StringUtils.isBlank(roomCosts) ?
                                BigDecimal.ZERO : new BigDecimal(roomCosts).setScale(BaseConstant.DATA_PRECISION, roundingMode));

                        String nights = CellUtils.convertCellStr(row.getCell(6));
                        api.setNights(StringUtils.isBlank(nights) ? BaseConstant.ZERO : Integer.parseInt(nights));

                        String totalRoom = CellUtils.convertCellStr(row.getCell(7));
                        api.setTotalRoom(StringUtils.isBlank(totalRoom) ? BaseConstant.ZERO : Integer.parseInt(totalRoom));

                        resultList.add(api);
                    }
                }
                return resultList;
            } catch (IOException e) {
                log.error(e.getMessage(), e);
                throw new InternalServerErrorException(BaseErrorCodeEnum.SYSTEM_ERROR.getI18nCode(),
                        BaseErrorCodeEnum.SYSTEM_ERROR.getCode(),
                        "Handle parse API report error", e);
            }
        }

        /**
         * 转换日期字符串
         *
         * @param dateStr 日期字符串
         * @return yyyyMMdd
         * @author zc
         * @date 2023/08/08
         */
        private String formatDateStr(String dateStr) {
            try {
                if (dateStr.contains("/")) {
                    LocalDate localDate = DateTimeUtils.strToLocalDate(StringUtils.substringBefore(dateStr, " "),
                            BaseConstant.DATE_FORMAT_M_D_YY);
                    return DateTimeUtils.localDateToStr(localDate, BaseConstant.DATE_FORMAT_YYYYMMDD);
                } else {
                    DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(BaseConstant.DATE_FORMAT_DD_MMM_YYYY, 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);
                }
            } catch (DateTimeParseException e) {
                log.error(e.getMessage(), e);
                throw new InternalServerErrorException(BaseErrorCodeEnum.SYSTEM_ERROR.getI18nCode(),
                        BaseErrorCodeEnum.SYSTEM_ERROR.getCode(),
                        "Handle parse API report error", e);
            }
        }

    }