# SalesOperatingStatisticsParseServiceByOther.java

    package cloud.wconnect.workperformance.service.mor.operatingstatistics;

    import cloud.wconnect.commonlib.cons.BaseConstant;
    import cloud.wconnect.commonlib.cons.BaseErrorCodeEnum;
    import cloud.wconnect.commonlib.cons.CommonErrorI18nConstant;
    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.*;
    import cloud.wconnect.workperformance.cons.S3BucketFunctionCons;
    import cloud.wconnect.workperformance.cons.operatingstatisticsdaily.OperatingStatisticsDatasourceEnum;
    import cloud.wconnect.workperformance.pojo.bo.mor.sales.SalesSourceOperatingStatisticsListBO;
    import cloud.wconnect.workperformance.service.AmazonS3Service;
    import cloud.wconnect.workperformance.service.mor.ISalesImportLogService;
    import cloud.wconnect.workperformance.service.mor.ISalesService;
    import com.baomidou.dynamic.datasource.annotation.DS;
    import com.google.common.collect.Lists;
    import jakarta.annotation.Resource;
    import org.apache.commons.collections.CollectionUtils;
    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.*;
    import java.util.function.Function;
    import java.util.stream.Collectors;

    /**
     * 服务实现类：报告处理
     *
     * @author zc
     * @date 2024/6/3
     */
    @Component
    @DS("work_performance")
    public class SalesOperatingStatisticsParseServiceByOther implements ISalesOperatingStatisticsParseService {
        @Resource
        private ISalesService salesService;
        @Resource
        private ISalesImportLogService importLogService;
        @Resource
        private I18nMessageUtils i18nMessageUtils;
        @Resource
        private AmazonS3Service amazonS3Service;

        @Value("${aws-s3.third-party.key.monthly-ot-report.sales-sources.operating-statistics}")
        private String s3FilePath;
        @Value("${file-max-size.import-report.sales-source}")
        private long fileMaxSize;

        /**
         * 判断是否支持
         *
         * @param source 数据源
         * @return boolean
         * @author zc
         * @date 2024/7/29
         */
        @Override
        public boolean supports(String source) {
            return SystemPlatformEnum.OTHER.getDesc().equals(source);
        }

        /**
         * 校验文件内容是否合法
         *
         * @param propertyDTOList 资产集合
         * @param file            文件
         * @author zc
         * @date 2024/8/19
         */
        @Override
        public void checkFile(List<PropertyDTO> propertyDTOList, MultipartFile file) {
            // 限制文件大小
            FileCheckUtils.checkFileSize(file, fileMaxSize);
            // 校验文件格式
            UploadUtils.checkFileFormat(file, Lists.newArrayList("xls", "xlsx"));
            Map<String, PropertyDTO> name2PropertyDTO = propertyDTOList.stream()
                    .collect(Collectors.toMap(item -> item.getName().toLowerCase(), Function.identity()));
            try (InputStream in = file.getInputStream(); Workbook workbook = WorkbookFactory.create(in)) {
                Sheet sheet = workbook.getSheetAt(0);
                // 获取最大行数
                int lastRowNum = sheet.getLastRowNum();
                // 若只包含标题，直接返回
                if (lastRowNum < 1) {
                    return;
                }

                // 提取标题
                List<String> titleList = Lists.newArrayList();
                Row titleRow = sheet.getRow(0);
                for (int i = 0; i <= 2; i++) {
                    titleList.add(CellUtils.convertCellStr(titleRow.getCell(i)));
                }

                for (int i = 1; i <= lastRowNum; i++) {
                    Row row = sheet.getRow(i);

                    // Property Name
                    String propertyNameStr = CellUtils.convertCellStr(row.getCell(0));
                    if (StringUtils.isBlank(propertyNameStr)) {
                        throw new BadRequestException(CommonErrorI18nConstant.CANNOT_EMPTY,
                                i18nMessageUtils.getErrorParamMapNotNeedTranslate(titleList.get(0)),
                                BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                "The Property Name cannot be blank");
                    }
                    // 若资产不存在，则跳过校验
                    PropertyDTO propertyDTO = name2PropertyDTO.get(propertyNameStr.toLowerCase());
                    if (Objects.isNull(propertyDTO)) {
                        continue;
                    }

                    // Date
                    String dateStr = CellUtils.convertCellStr(row.getCell(1));
                    if (StringUtils.isBlank(dateStr)) {
                        throw new BadRequestException(CommonErrorI18nConstant.CANNOT_EMPTY,
                                i18nMessageUtils.getErrorParamMapNotNeedTranslate(titleList.get(1)),
                                BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                "The Date cannot be blank");
                    }
                    try {
                        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(BaseConstant.DATE_FORMAT_YYYY_MM_DD, Locale.ENGLISH);
                        LocalDate.parse(dateStr, formatter);
                    } catch (DateTimeParseException e) {
                        throw new BadRequestException(CommonErrorI18nConstant.FORMAT_INCORRECT,
                                i18nMessageUtils.getErrorParamMapNotNeedTranslate(titleList.get(1), BaseConstant.DATE_FORMAT_YYYY_MM_DD),
                                BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                "The date format is incorrect, date = " + dateStr);
                    }

                    // Total Revenue
                    String totalRevenueStr = CellUtils.convertCellStr(row.getCell(2));
                    if (StringUtils.isNotBlank(totalRevenueStr)) {
                        BigDecimal totalRevenue;
                        try {
                            totalRevenue = new BigDecimal(totalRevenueStr);
                        } catch (NumberFormatException e) {
                            throw new BadRequestException(CommonErrorI18nConstant.MUST_NUMBER,
                                    i18nMessageUtils.getErrorParamMapNotNeedTranslate(titleList.get(2)),
                                    BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                    "The Total Revenue format is incorrect, Total Revenue = " + totalRevenueStr);
                        }
                        // 校验整数位是否超过限制
                        int intLength = totalRevenue.abs().toBigInteger().toString().length();
                        if (intLength > 10) {
                            throw new BadRequestException(CommonErrorI18nConstant.NUMBER_INTEGER_OVERLENGTH,
                                    i18nMessageUtils.getErrorParamMapNotNeedTranslate(titleList.get(2), 10),
                                    BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                    "The integer of Total Revenue exceeds the limit, Total Revenue = " + totalRevenueStr);
                        }
                    }
                }
            } catch (IOException e) {
                throw new InternalServerErrorException(BaseErrorCodeEnum.SYSTEM_ERROR.getI18nCode(),
                        BaseErrorCodeEnum.SYSTEM_ERROR.getCode(),
                        "Handle check Sales sources Operating statistics Other report error.", e);
            }
        }

        /**
         * 处理数据
         *
         * @param propertyDTOList      资产集合
         * @param file                 文件
         * @param propertyId2DateRange 报告数据日期范围(yyyyMMdd)
         * @param logIds               日志 id 集合
         * @param operatorId           操作人 id
         * @author zc
         * @date 2024/8/19
         */
        @Override
        public void handleData(List<PropertyDTO> propertyDTOList, MultipartFile file,
                               Map<Integer, List<Long>> propertyId2DateRange, List<Long> logIds, int operatorId) {
            // 处理是否成功
            boolean handleResult = true;
            String tenantSymbol = propertyDTOList.get(0).getTenantSymbol();
            List<String> propertyAbbrList = propertyDTOList.stream().map(PropertyDTO::getAbbr).toList();
            String s3Key = tenantSymbol + "/" + StringUtils.join(propertyAbbrList, "_") + "/" + s3FilePath
                    + UploadUtils.getRandomFileName(file.getOriginalFilename());

            Map<Integer, Integer> propertyId2DataUpdateResult = new HashMap<>();
            try (InputStream in = file.getInputStream()) {
                // 上传报告到 S3，用于导入记录下载报告
                amazonS3Service.uploadFile(S3BucketFunctionCons.SALES_IMPORT_RECORD, file, s3Key);

                // 解析报告
                List<SalesSourceOperatingStatisticsListBO> operatingStatisticsListBOList = parse(propertyDTOList, in, propertyId2DateRange);
                // 处理报告数据
                propertyId2DataUpdateResult = salesService.handleOperatingStatistics(propertyDTOList, operatingStatisticsListBOList, operatorId, propertyId2DateRange,
                        OperatingStatisticsDatasourceEnum.OTHER.getValue());
            } catch (Exception e) {
                handleResult = false;
                throw new InternalServerErrorException(BaseErrorCodeEnum.SYSTEM_ERROR.getI18nCode(),
                        BaseErrorCodeEnum.SYSTEM_ERROR.getCode(),
                        "Handle import Sales sources Operating statistics Other report error.", e);
            } finally {
                importLogService.updateBatch(logIds, handleResult, operatorId, s3Key, propertyId2DataUpdateResult);
            }
        }

        /**
         * 解析报告
         *
         * @param propertyDTOList      资产集合
         * @param in                   文件流
         * @param propertyId2DateRange 报告数据日期范围(yyyyMMdd)
         * @return SalesSourceOperatingStatisticsListBO 集合
         * @author zc
         * @date 2024/8/19
         */
        @Override
        public List<SalesSourceOperatingStatisticsListBO> parse(List<PropertyDTO> propertyDTOList, InputStream in,
                                                                Map<Integer, List<Long>> propertyId2DateRange) throws ParseReportException {
            Map<String, PropertyDTO> name2PropertyDTO = propertyDTOList.stream()
                    .collect(Collectors.toMap(item -> item.getName().toLowerCase(), Function.identity()));

            try (Workbook workbook = WorkbookFactory.create(in)) {
                Sheet sheet = workbook.getSheetAt(0);

                List<SalesSourceOperatingStatisticsListBO> operatingStatistics = Lists.newArrayList();
                // 跳过第 0 行标题
                for (int i = 1; i <= sheet.getLastRowNum(); i++) {
                    Row row = sheet.getRow(i);

                    String propertyName = CellUtils.convertCellStr(row.getCell(0));
                    PropertyDTO propertyDTO = name2PropertyDTO.get(propertyName.toLowerCase());
                    if (Objects.isNull(propertyDTO)) {
                        continue;
                    }

                    String dateStr = CellUtils.convertCellStr(row.getCell(1));
                    if (StringUtils.isEmpty(dateStr)) {
                        continue;
                    }

                    // 数据日期范围配置为空的不处理
                    List<Long> dateRangeList = propertyId2DateRange.getOrDefault(propertyDTO.getId(), Collections.emptyList());
                    if (CollectionUtils.isEmpty(dateRangeList)) {
                        continue;
                    }

                    // 只提取指定日期范围的数据
                    LocalDate localDate = DateTimeUtils.strToLocalDate(dateStr, BaseConstant.DATE_FORMAT_YYYY_MM_DD);
                    int targetDate = Integer.parseInt(DateTimeUtils.localDateToStr(localDate, BaseConstant.DATE_FORMAT_YYYYMMDD));
                    if (targetDate < dateRangeList.get(0) || targetDate > dateRangeList.get(1)) {
                        continue;
                    }

                    operatingStatistics.add(convert2Bo(row, propertyDTO));
                }
                return operatingStatistics;
            } catch (IOException e) {
                throw new InternalServerErrorException(BaseErrorCodeEnum.SYSTEM_ERROR.getI18nCode(),
                        BaseErrorCodeEnum.SYSTEM_ERROR.getCode(),
                        "Handle parse Sales Source Operating Statistics Other report error.", e);
            }
        }

        /**
         * 报告数据转换为 BO
         *
         * @param row         行数据
         * @param propertyDTO 资产
         * @return SalesSourceOperatingStatisticsListBO
         * @author zc
         * @date 2024/7/29
         */
        private SalesSourceOperatingStatisticsListBO convert2Bo(Row row, PropertyDTO propertyDTO) {
            RoundingMode roundingMode = InternationalizationUtils.getRoundingMode(propertyDTO
                    .getInternationalization().getNumber().getCalculationRule());

            SalesSourceOperatingStatisticsListBO os = new SalesSourceOperatingStatisticsListBO();
            os.setProperty(propertyDTO.getAbbr());

            String dateStr = CellUtils.convertCellStr(row.getCell(1));
            os.setTheDay(dateStr);

            String totalRevStr = CellUtils.convertCellStr(row.getCell(2));
            os.setTotalRev(StringUtils.isBlank(totalRevStr) ? null : new BigDecimal(totalRevStr)
                    .setScale(BaseConstant.DATA_PRECISION, roundingMode));

            return os;
        }
    }