# OperatingStatisticsParseServiceByM3.java

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

    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.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.*;
    import cloud.wconnect.sns.http.processor.Sender;
    import cloud.wconnect.workperformance.cons.BusinessEnum;
    import cloud.wconnect.workperformance.cons.EventSubjectEnum;
    import cloud.wconnect.workperformance.pojo.bo.sva.operatingstatistics.OperatingStatisticsListBO;
    import cloud.wconnect.workperformance.service.AmazonS3Service;
    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 jakarta.annotation.Resource;
    import org.apache.commons.collections.CollectionUtils;
    import org.apache.commons.csv.CSVFormat;
    import org.apache.commons.csv.CSVRecord;
    import org.apache.commons.lang3.StringUtils;
    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 java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.math.BigDecimal;
    import java.math.RoundingMode;
    import java.time.LocalDate;
    import java.util.*;
    import java.util.function.Function;
    import java.util.stream.Collectors;

    /**
     * 服务实现类：报告处理
     *
     * @author zc
     * @date 2023/03/19
     */
    @Component
    @DS("work_performance")
    public class OperatingStatisticsParseServiceByM3 implements IOperatingStatisticsParseService {
        @Resource
        private ObjectMapper objectMapper;
        @Resource
        private AmazonS3Service amazonS3Service;
        @Resource
        @Qualifier("3pSender")
        private Sender snsSender;

        @Value("${aws-s3.third-party.key.schedule-vs-actual.operating-statistics}")
        private String s3FilePath;
        @Value("${file-max-size.import-report.sva}")
        private long fileMaxSize;

        /**
         * 判断是否支持
         *
         * @param source 数据源
         * @return boolean
         * @author zc
         * @date 2024/8/19
         */
        @Override
        public boolean supports(String source) {
            return SystemPlatformEnum.M3.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("csv"));
        }

        /**
         * 处理数据
         *
         * @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) {
            try {
                String tenantSymbol = propertyDTOList.get(0).getTenantSymbol();
                List<String> propertyAbbrList = propertyDTOList.stream().map(PropertyDTO::getAbbr).toList();

                String key = tenantSymbol + "/" + StringUtils.join(propertyAbbrList, "_") + "/" + s3FilePath
                        + UploadUtils.getRandomFileName(file.getOriginalFilename());
                // 上传文件到 S3 服务器，用于监听器监听并处理文件
                amazonS3Service.uploadFile(file, key);

                List<Long> dateRangeList = propertyId2DateRange.values().stream().toList().get(0);

                // 封装事件体
                HashMap<String, Object> parameter = Maps.newHashMap();
                parameter.put(EventBodyParamEnum.TENANT_SYMBOL.getDesc(), tenantSymbol);
                parameter.put(EventBodyParamEnum.PROPERTY_ABBR.getDesc(), propertyAbbrList);
                parameter.put(EventBodyParamEnum.ORIGINATE_FROM.getDesc(), BusinessEnum.SVA_OPERATING_STATISTICS.getBusiness());
                parameter.put(EventBodyParamEnum.SOURCE.getDesc(), SystemPlatformEnum.M3.getDesc());
                parameter.put(EventBodyParamEnum.UID.getDesc(), operatorId);
                parameter.put(EventBodyParamEnum.ID.getDesc(), logIds);
                parameter.put(EventBodyParamEnum.START_DATE.getDesc(), dateRangeList.get(0));
                parameter.put(EventBodyParamEnum.END_DATE.getDesc(), dateRangeList.get(1));

                // 手动发送事件通知
                snsSender.publish(EventSubjectEnum.ACCOUNTING_OPERATING_STATISTICS.getSubject(),
                        JsonUtils.convertObjToString(objectMapper, new EventBodyDTO(key, parameter)));
            } catch (Exception e) {
                throw new InternalServerErrorException(BaseErrorCodeEnum.SYSTEM_ERROR.getI18nCode(),
                        BaseErrorCodeEnum.SYSTEM_ERROR.getCode(),
                        "Handle import Sva Operating Statistics M3 report send event exception", e);
            }
        }

        /**
         * 解析报告
         *
         * @param propertyDTOList      资产集合
         * @param in                   报告文件
         * @param propertyId2DateRange 报告数据日期范围(yyyyMMdd)
         * @return OperatingStatisticsListBO 集合
         * @author zc
         * @date 2024/8/19
         */
        @Override
        public List<OperatingStatisticsListBO> 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 (InputStreamReader reader = new InputStreamReader(in)) {
                List<OperatingStatisticsListBO> operatingStatistics = Lists.newArrayList();
                Iterable<CSVRecord> records = CSVFormat.EXCEL.parse(reader);
                for (CSVRecord record : records) {
                    // 跳过第一行的标题行
                    if (record.getRecordNumber() == 1) {
                        continue;
                    }

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

                    String dateStr = record.get(1);
                    if (StringUtils.isBlank(dateStr)) {
                        continue;
                    }

                    // 只提取指定日期范围的数据
                    LocalDate theDate = DateTimeUtils.strToLocalDate(dateStr, BaseConstant.DATE_FORMAT_M_D_YY);
                    long targetDate = Long.parseLong(DateTimeUtils.localDateToStr(theDate, BaseConstant.DATE_FORMAT_YYYYMMDD));
                    if (targetDate < dateRangeList.get(0) || targetDate > dateRangeList.get(1)) {
                        continue;
                    }

                    operatingStatistics.add(convert2Bo(record, propertyDTO));
                }
                return operatingStatistics;
            } catch (IOException e) {
                throw new InternalServerErrorException(BaseErrorCodeEnum.SYSTEM_ERROR.getI18nCode(),
                        BaseErrorCodeEnum.SYSTEM_ERROR.getCode(),
                        "Handle parse Sva Operating statistics M3 report error.", e);
            }
        }

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

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

            String dateStr = record.get(1).trim();
            LocalDate theDate = DateTimeUtils.strToLocalDate(dateStr, BaseConstant.DATE_FORMAT_M_D_YY);
            os.setTheDay(DateTimeUtils.localDateToStr(theDate, BaseConstant.DATE_FORMAT_YYYY_MM_DD));

            String roomsRentedStr = replacePercentiles(record.get(2).trim());
            os.setRoomsRented(StringUtils.isBlank(roomsRentedStr) ? 0 : Integer.parseInt(roomsRentedStr));

            String occPercentStr = replacePercentiles(record.get(3).trim());
            os.setOccPercent(StringUtils.isBlank(occPercentStr) ? BigDecimal.ZERO : new BigDecimal(occPercentStr)
                    .setScale(scale, roundingMode));

            String adrStr = replacePercentiles(record.get(4).trim());
            os.setAdr(StringUtils.isBlank(adrStr) ? BigDecimal.ZERO : new BigDecimal(adrStr)
                    .setScale(scale, roundingMode));

            String revParStr = replacePercentiles(record.get(5).trim());
            os.setRevPar(StringUtils.isBlank(revParStr) ? BigDecimal.ZERO : new BigDecimal(revParStr)
                    .setScale(scale, roundingMode));

            String roomRevStr = replacePercentiles(record.get(6).trim());
            os.setRoomRev(StringUtils.isBlank(roomRevStr) ? BigDecimal.ZERO : new BigDecimal(roomRevStr)
                    .setScale(scale, roundingMode));

            String foodRevStr = replacePercentiles(record.get(7).trim());
            os.setFoodRev(StringUtils.isBlank(foodRevStr) ? BigDecimal.ZERO : new BigDecimal(foodRevStr)
                    .setScale(scale, roundingMode));

            String bevRevStr = replacePercentiles(record.get(8).trim());
            os.setBevRev(StringUtils.isBlank(bevRevStr) ? BigDecimal.ZERO : new BigDecimal(bevRevStr)
                    .setScale(scale, roundingMode));

            String otherRev = replacePercentiles(record.get(9).trim());
            os.setOtherRev(StringUtils.isBlank(otherRev) ? BigDecimal.ZERO : new BigDecimal(otherRev)
                    .setScale(scale, roundingMode));

            String totalRevStr = replacePercentiles(record.get(10).trim());
            os.setTotalRev(StringUtils.isBlank(totalRevStr) ? BigDecimal.ZERO : new BigDecimal(totalRevStr)
                    .setScale(scale, roundingMode));

            return os;
        }

        /**
         * 删除字符串数值千分位
         *
         * @param str 字符串数值
         * @return java.lang.String
         * @author zc
         * @date 2024/8/30
         */
        private String replacePercentiles(String str) {
            return str.replace(",", "");
        }
    }