# HistoryAndForecastByShiji.java

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

    import cloud.wconnect.commonlib.cons.BaseConstant;
    import cloud.wconnect.commonlib.cons.BaseErrorCodeEnum;
    import cloud.wconnect.commonlib.cons.ReportImportResultCons;
    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.pojo.dto.internationalization.InternationalizationNumberDTO;
    import cloud.wconnect.commonlib.util.*;
    import cloud.wconnect.workperformance.entity.schedule.ScheduleHistoryAndForecastImportLog;
    import cloud.wconnect.workperformance.pojo.bo.schedule.ScheduleHistoryAndForecastBO;
    import cloud.wconnect.workperformance.service.schedule.IScheduleHandleReportService;
    import cloud.wconnect.workperformance.service.schedule.IScheduleHistoryAndForecastImportLogService;
    import com.baomidou.dynamic.datasource.annotation.DS;
    import com.google.common.collect.Lists;
    import jakarta.annotation.Resource;
    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.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.Objects;

    /**
     * History And Forecast By Shiji Auto
     *
     * @author yyt
     * 2023/7/4
     */
    @Component
    @DS("work_performance")
    public class HistoryAndForecastByShiji implements IHistoryAndForecastFileParse {

        @Resource
        private IScheduleHistoryAndForecastImportLogService scheduleHistoryAndForecastImportLogService;
        @Resource
        private IScheduleHandleReportService scheduleHandleReportService;

        @Value("${file-max-size.import-report.schedule}")
        private Long importReportFileMaxSize;

        private static final String SOURCE = SystemPlatformEnum.SHI_JI.getDesc();

        /**
         * 判断支持的平台
         *
         * @param source 平台数据源
         * @return boolean
         * @author lichen
         * @date 2025/7/29
         */
        @Override
        public boolean supports(String source) {
            return source.equals(SOURCE);
        }

        /**
         * 解析报告数据
         *
         * @param startDate   开始日期
         * @param endDate     结束日期
         * @param inputStream 文件流
         * @param propertyDTO 资产
         * @return history and forecast
         * @author yyt
         * @date 2023/7/4
         */
        @Override
        public List<ScheduleHistoryAndForecastBO> parsReport(Long startDate, Long endDate, InputStream inputStream,
                                                             PropertyDTO propertyDTO) {
            // 最多14天数据
            List<ScheduleHistoryAndForecastBO> historyAndForecasts = Lists.newArrayListWithExpectedSize(14);
            String timeZone = propertyDTO.getTimezone();
            InternationalizationNumberDTO number = propertyDTO.getInternationalization().getNumber();
            RoundingMode roundingMode = InternationalizationUtils.getRoundingMode(number.getCalculationRule());
            DateTimeFormatter dateTimeFormatter2 = DateTimeFormatter.ofPattern("yyyy-MM-dd");

            try (InputStreamReader inputStreamReader = new InputStreamReader(inputStream)) {
                //获取CSV数据迭代器
                Iterable<CSVRecord> iterable = CSVFormat.EXCEL.parse(inputStreamReader);
                Iterator<CSVRecord> iterator = iterable.iterator();

                //跳过第一行标题行
                iterator.next();

                while (iterator.hasNext()) {
                    CSVRecord csvRecord = iterator.next();
                    //日期格式Wed  07/02/25
                    String dateStr = ShijiFileCheckUtils.get(csvRecord, "A");
                    String[] split = dateStr.split("  ");
                    LocalDate localDate = DateTimeUtils.strToLocalDate(split[1], BaseConstant.DATE_TIME_FORMAT_MM_DD_YY);
                    long targetDate = DateTimeUtils.localDateToLong(localDate, timeZone);

                    //判断目标日期是否在范围中
                    if (targetDate >= startDate && targetDate <= endDate) {
                        ScheduleHistoryAndForecastBO historyAndForecast = new ScheduleHistoryAndForecastBO();
                        historyAndForecast.setTargetDate(dateTimeFormatter2.format(localDate));

                        String roomSoldStr = ShijiFileCheckUtils.getAndFormatNumber(csvRecord, "B");
                        historyAndForecast.setSoldRooms(StringUtils.isEmpty(roomSoldStr) ? 0 : Integer.parseInt(roomSoldStr));

                        String arrivalRoomsStr = ShijiFileCheckUtils.getAndFormatNumber(csvRecord, "C");
                        historyAndForecast.setArrivalRooms(StringUtils.isEmpty(arrivalRoomsStr) ? 0 : Integer.parseInt(arrivalRoomsStr));

                        String departureRoomsStr = ShijiFileCheckUtils.getAndFormatNumber(csvRecord, "D");
                        historyAndForecast.setDepartureRooms(StringUtils.isEmpty(departureRoomsStr) ? 0 : Integer.parseInt(departureRoomsStr));

                        String occupancyStr = ShijiFileCheckUtils.getAndFormatNumber(csvRecord, "E");
                        historyAndForecast.setOcc(StringUtils.isEmpty(occupancyStr) ? BigDecimal.ZERO :
                                new BigDecimal(occupancyStr).setScale(BaseConstant.DATA_PRECISION, roundingMode));

                        historyAndForecasts.add(historyAndForecast);
                    }
                    //跳过两行
                    iterator.next();
                    iterator.next();
                }
            } catch (Exception e) {
                throw new ParseReportException(BaseErrorCodeEnum.SYSTEM_ERROR.getI18nCode(),
                        BaseErrorCodeEnum.SYSTEM_ERROR.getCode(),
                        "parse shiji [history and forecast] report error", e);
            }
            return historyAndForecasts;
        }

        /**
         * 检查文件
         *
         * @param propertyDTO 资产
         * @param file        文件
         * @return void
         * @author lichen
         * @date 2025/7/29
         */
        @Override
        public void checkFile(PropertyDTO propertyDTO, MultipartFile file) {
            // 限制文件大小
            FileCheckUtils.checkFileSize(file, importReportFileMaxSize);
            // 校验文件格式
            UploadUtils.checkFileFormat(file, Lists.newArrayList("csv"));

            try (InputStream in = file.getInputStream()) {
                ShijiFileCheckUtils.checkHistoryAndForecast(in);
            } catch (BadRequestException e) {
                throw e;
            } catch (Exception e) {
                throw new InternalServerErrorException(BaseErrorCodeEnum.SYSTEM_ERROR.getI18nCode(),
                        BaseErrorCodeEnum.SYSTEM_ERROR.getCode(), "parsing shiji [history and forecast] file failed.", e);
            }
        }

        /**
         * 处理导入记录
         *
         * @param propertyDTO 资产
         * @param importLog   导入记录
         * @param theDate     指定日期
         * @param startDate   开始日期
         * @param endDate     结束日期
         * @param userId      操作人
         * @return cloud.wconnect.workperformance.entity.schedule.ScheduleHistoryAndForecastImportLog
         * @author lichen
         * @date 2025/7/29
         */
        @Override
        public ScheduleHistoryAndForecastImportLog handleImportLog(PropertyDTO propertyDTO,
                                                                   ScheduleHistoryAndForecastImportLog importLog,
                                                                   Long theDate, Long startDate, Long endDate, int userId) {
            if (Objects.isNull(importLog)) {
                importLog = scheduleHistoryAndForecastImportLogService.saveRecord(propertyDTO.getId(), theDate, startDate,
                        endDate, ReportImportResultCons.IMPORT_IN_PROGRESS, userId);
            } else {
                // 更新异常为修复中
                ScheduleHistoryAndForecastImportLog updateContent = new ScheduleHistoryAndForecastImportLog();
                updateContent.setId(importLog.getId());
                updateContent.setImportResult(ReportImportResultCons.IMPORT_RESULT_REPAIRING);
                scheduleHistoryAndForecastImportLogService.updateById(updateContent);
            }
            return importLog;
        }

        /**
         * 处理文件
         *
         * @param propertyDTO 资产信息
         * @param file        文件
         * @param importLog   导入记录
         * @param userId      操作人
         * @return void
         * @author lichen
         * @date 2025/7/29
         */
        @Override
        public void handleFile(PropertyDTO propertyDTO, MultipartFile file, ScheduleHistoryAndForecastImportLog importLog, Integer userId) {
            scheduleHandleReportService.sendHistoryAndForecastEvent(propertyDTO, SystemPlatformEnum.SHI_JI.getDesc(), file, importLog, userId);
        }

    }