# GmwrHistoryAndForecastParseServiceByShiji.java

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

    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.DateTimeUtils;
    import cloud.wconnect.commonlib.util.InternationalizationUtils;
    import cloud.wconnect.commonlib.util.ShijiFileCheckUtils;
    import cloud.wconnect.workperformance.pojo.bo.gmwr.GmwrHistoryAndForecastBO;
    import cloud.wconnect.workperformance.service.gmwr.IGmwrHistoryAndForecastService;
    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.stereotype.Component;
    import org.springframework.transaction.annotation.Transactional;

    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 GmwrHistoryAndForecastParseServiceByShiji implements IGmwrHistoryAndForecastParseService {

        private final IGmwrHistoryAndForecastService gmwrHistoryAndForecastService;

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

        /**
         * 解析报告
         *
         * @param propertyDTO 资产
         * @param in          报告文件流
         * @param dateRange   报告数据日期范围(yyyyMMdd)
         * @return GmwrHistoryAndForecastBO 集合
         * @author zc
         * @date 2025/7/23
         */
        @Override
        public List<GmwrHistoryAndForecastBO> 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<GmwrHistoryAndForecastBO> 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 GM Weekly Report History and forecast Shiji report error.", e);
            }
        }

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

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

            // OOO Rooms
            String oooRoomsStr = ShijiFileCheckUtils.getAndFormatNumber(recordTotal, "S");
            bo.setOoo(StringUtils.isBlank(oooRoomsStr) ? 0 : Integer.parseInt(oooRoomsStr));

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

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

            return bo;
        }

        /**
         * 处理 History And Forecast 数据
         *
         * @param propertyDTO              资产
         * @param historyAndForecastBOList 报告数据
         * @author yyt
         * @date 2026/2/5
         **/
        @Override
        @Transactional(rollbackFor = Exception.class)
        public void handleHistoryAndForecast(PropertyDTO propertyDTO, List<GmwrHistoryAndForecastBO> historyAndForecastBOList) {
            gmwrHistoryAndForecastService.handleHistoryAndForecast(propertyDTO, historyAndForecastBOList);
        }

    }