# HotelKpiHistoryAndForecastParseServiceByShiji.java

    package cloud.wconnect.workperformance.service.hotelkpi.historyandforecast;

    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.*;
    import cloud.wconnect.workperformance.pojo.bo.hotelkpi.HotelKpiHistoryAndForecastBO;
    import cloud.wconnect.workperformance.service.hotelkpi.IHotelKpiHandleReportService;
    import com.baomidou.dynamic.datasource.annotation.DS;
    import com.google.common.collect.Lists;
    import lombok.RequiredArgsConstructor;
    import lombok.extern.slf4j.Slf4j;
    import org.apache.commons.csv.CSVFormat;
    import org.apache.commons.csv.CSVRecord;
    import org.apache.commons.lang3.StringUtils;
    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.time.format.DateTimeFormatter;
    import java.util.Iterator;
    import java.util.List;
    import java.util.Locale;

    /**
     * 解析 Shiji 系统的 History And Forecast 报告
     */
    @RequiredArgsConstructor
    @Slf4j
    @Component
    @DS("work_performance")
    public class HotelKpiHistoryAndForecastParseServiceByShiji implements IHotelKpiHistoryAndForecastParseService {

        private final IHotelKpiHandleReportService hotelKpiHandleReportService;;

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

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

        /**
         * 校验文件内容是否合法
         *
         * @param propertyDTO 资产
         * @param file        文件
         * @author zc
         * @date 2025/7/23
         */
        @Override
        public void checkFile(PropertyDTO propertyDTO, MultipartFile file) {
            // 限制文件大小
            FileCheckUtils.checkFileSize(file, fileMaxSize);
            // 校验文件格式
            UploadUtils.checkFileFormat(file, Lists.newArrayList("csv"));
            // 校验文件内容
            try (InputStream inputStream = file.getInputStream()) {
                ShijiFileCheckUtils.checkHistoryAndForecast(inputStream);
            } catch (BadRequestException e) {
                throw e;
            } catch (Exception e) {
                throw new InternalServerErrorException(BaseErrorCodeEnum.SYSTEM_ERROR.getI18nCode(),
                        BaseErrorCodeEnum.SYSTEM_ERROR.getCode(),
                        "Check Hotel KPI History and forecast Shiji report error", e);
            }
        }

        /**
         * 处理数据
         *
         * @param propertyDTO 资产
         * @param file        文件
         * @param dateRange   报告数据日期范围(yyyyMMdd)
         * @param logId       日志 id
         * @param operatorId  操作人 id
         * @author zc
         * @date 2025/7/23
         */
        @Override
        public void handleData(PropertyDTO propertyDTO, MultipartFile file, List<Long> dateRange, long logId, int operatorId) {
            hotelKpiHandleReportService.sendHistoryAndForecastEvent(propertyDTO, SystemPlatformEnum.SHI_JI.getDesc(), file, dateRange, logId, operatorId);
        }

        /**
         * 解析报告
         *
         * @param propertyDTO 资产
         * @param in          报告文件流
         * @param dateRange   报告数据日期范围(yyyyMMdd)
         * @return HotelKpiHistoryAndForecastBO 集合
         * @author zc
         * @date 2025/7/23
         */
        @Override
        public List<HotelKpiHistoryAndForecastBO> parse(PropertyDTO propertyDTO, InputStream in, List<Long> dateRange) throws ParseReportException {
            DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("EEE  MM/dd/yy", Locale.ENGLISH);
            RoundingMode roundingMode = InternationalizationUtils.getRoundingMode(propertyDTO
                    .getInternationalization().getNumber().getCalculationRule());
            long startDate = dateRange.get(0);
            long endDate = dateRange.get(1);
            try (InputStreamReader inputStreamReader = new InputStreamReader(in)) {
                List<HotelKpiHistoryAndForecastBO> boList = Lists.newArrayList();
                Iterable<CSVRecord> records = CSVFormat.EXCEL.parse(inputStreamReader);
                Iterator<CSVRecord> iterator = records.iterator();
                // 跳过第一行的标题行
                iterator.next();
                while (iterator.hasNext()) {
                    CSVRecord record = iterator.next();
                    String dateStr = ShijiFileCheckUtils.get(record, "A");
                    LocalDate dataLocalDate = LocalDate.parse(dateStr, dateTimeFormatter);
                    long targetDate = Long.parseLong(DateTimeUtils.localDateToStr(dataLocalDate, BaseConstant.DATE_FORMAT_YYYYMMDD));
                    if (targetDate < startDate || targetDate > endDate) {
                        // 跳过 Individual
                        iterator.next();
                        // 跳过 Group
                        iterator.next();
                        continue;
                    }

                    boList.add(convert2Bo(dataLocalDate, record, roundingMode));
                    // 跳过 Individual
                    iterator.next();
                    // 跳过 Group
                    iterator.next();
                }
                return boList;
            } catch (IOException e) {
                log.error(e.getMessage(), e);
                throw new InternalServerErrorException(BaseErrorCodeEnum.SYSTEM_ERROR.getI18nCode(),
                        BaseErrorCodeEnum.SYSTEM_ERROR.getCode(),
                        "Handle parse Hotel KPI History and forecast Shiji report error.", e);
            }
        }

        /**
         * 将报告中的信息转换为实体类
         *
         * @param dataLocalDate 数据日期
         * @param recordTotal   CSVRecord Total
         * @param roundingMode  舍入模式
         * @return HotelKpiHistoryAndForecastBO
         * @author zc
         * @date 2025/7/23
         */
        private HotelKpiHistoryAndForecastBO convert2Bo(LocalDate dataLocalDate, CSVRecord recordTotal, RoundingMode roundingMode) {
            HotelKpiHistoryAndForecastBO bo = new HotelKpiHistoryAndForecastBO();

            bo.setDateStr(DateTimeUtils.localDateToStr(dataLocalDate, BaseConstant.DATE_FORMAT_YYYY_MM_DD));

            // Rooms Sold
            String roomsSoldStr = ShijiFileCheckUtils.getAndFormatNumber(recordTotal, "B");
            bo.setRoomsSold(StringUtils.isBlank(roomsSoldStr) ? 0 : Integer.parseInt(roomsSoldStr));

            // Arrival Rooms
            String arrivalRoomsStr = ShijiFileCheckUtils.getAndFormatNumber(recordTotal, "C");
            bo.setArrivalRooms(StringUtils.isBlank(arrivalRoomsStr) ? 0 : Integer.parseInt(arrivalRoomsStr));

            // Departure Rooms
            String departureRoomsStr = ShijiFileCheckUtils.getAndFormatNumber(recordTotal, "D");
            bo.setDepartureRooms(StringUtils.isBlank(departureRoomsStr) ? 0 : Integer.parseInt(departureRoomsStr));

            // Room Revenue
            String revenueStr = ShijiFileCheckUtils.getAndFormatNumber(recordTotal, "N");
            bo.setRoomRevenue(StringUtils.isBlank(revenueStr) ? null : new BigDecimal(revenueStr)
                    .setScale(BaseConstant.DATA_PRECISION, roundingMode));

            // ADR
            String adrStr = ShijiFileCheckUtils.getAndFormatNumber(recordTotal, "P");
            bo.setAdr(StringUtils.isBlank(adrStr) ? null : new BigDecimal(adrStr)
                    .setScale(BaseConstant.DATA_PRECISION, roundingMode));

            return bo;
        }

    }