# ParseReservationsEnteredOnAndByServiceByShiji.java

    package cloud.wconnect.frontoffice.parsereport.badguest.impl;

    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.BadRequestException;
    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.frontoffice.cons.EventSubjectEnum;
    import cloud.wconnect.frontoffice.cons.badguest.BgReportTypeEnum;
    import cloud.wconnect.frontoffice.parsereport.badguest.IParseFileService;
    import cloud.wconnect.frontoffice.pojo.dto.badguest.GuestInHouseDTO;
    import cloud.wconnect.frontoffice.service.AmazonS3Service;
    import cloud.wconnect.sns.http.processor.Sender;
    import com.fasterxml.jackson.databind.ObjectMapper;
    import com.google.common.collect.Lists;
    import com.google.common.collect.Maps;
    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.dom4j.Document;
    import org.dom4j.DocumentException;
    import org.dom4j.Element;
    import org.dom4j.Node;
    import org.dom4j.io.SAXReader;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.beans.factory.annotation.Qualifier;
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.stereotype.Service;
    import org.springframework.web.multipart.MultipartFile;

    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.time.LocalDate;
    import java.time.ZoneId;
    import java.time.format.DateTimeFormatter;
    import java.util.*;
    import java.util.stream.Collectors;

    /**
     * 解析Shiji系统的Reservations Entered on and by
     */
    @Slf4j
    @Service
    public class ParseReservationsEnteredOnAndByServiceByShiji implements IParseFileService {

        @Autowired
        private AmazonS3Service amazonS3Service;
        @Autowired
        @Qualifier("3pSender")
        private Sender snsSender;
        @Autowired
        private ObjectMapper objectMapper;
        @Value("${aws-s3.third-party.key.guests-blacklist.reservations-made-yesterday}")
        private String reservationsMadeYesterdayS3FilePath;

        /**
         * 支持的文件来源 、文件类型
         *
         * @param source 来源
         * @param type   报告类型
         * @return boolean
         * @author lichen
         * @date 2025/7/26
         */
        @Override
        public boolean supports(String source, int type) {
            return SystemPlatformEnum.SHI_JI.getDesc().equals(source) && BgReportTypeEnum.RESERVATIONS_MADE_YESTERDAY_SERVICE.getType() == type;
        }

        /**
         * 解析报告
         *
         * @param in          文件流
         * @param propertyDTO 资产对象
         * @return java.util.List<cloud.wconnect.frontoffice.pojo.dto.badguest.GuestInHouseDTO>
         * @author lichen
         * @date 2025/7/26
         */
        @Override
        public List<GuestInHouseDTO> parse(InputStream in, PropertyDTO propertyDTO) throws ParseReportException {
            try (InputStreamReader inputStreamReader = new InputStreamReader(in)) {
                //获取CSV数据迭代器
                Iterable<CSVRecord> iterable = CSVFormat.EXCEL.parse(inputStreamReader);

                ArrayList<CSVRecord> allRows = Lists.newArrayList();
                iterable.forEach(record -> {
                    if (record.getRecordNumber() == 1) {
                        return;
                    }
                    allRows.add(record);
                });

                //构建返回集合
                List<GuestInHouseDTO> guestInHouseList = Lists.newArrayListWithExpectedSize(allRows.size());

                long currentTimestamp = DateTimeUtils.nowTimestamp();

                for (int i = 0; i < allRows.size(); i++) {
                    CSVRecord csvRecord = allRows.get(i);
                    //客人姓名
                    String guestName = ShijiFileCheckUtils.get(csvRecord, "A");
                    if(StringUtils.isBlank(guestName)){
                        continue;
                    }
                    guestName = guestName.trim();

                    //入住日期
                    String arrivalDateStr = ShijiFileCheckUtils.get(csvRecord, "E");
                    if(StringUtils.isBlank(arrivalDateStr)){
                        continue;
                    }
                    arrivalDateStr = arrivalDateStr.trim().substring(0,8);
                    long arrivalDate = DateTimeUtils.dateStrToEpochSecond(arrivalDateStr, BaseConstant.DATE_TIME_FORMAT_MM_DD_YY, propertyDTO.getTimezone());

                    //离店日期所在的行
                    CSVRecord departureCsvRecord = allRows.get(i + 2);
                    String departureDateStr = ShijiFileCheckUtils.get(departureCsvRecord, "E");
                    if(StringUtils.isBlank(departureDateStr)){
                        continue;
                    }
                    departureDateStr = departureDateStr.trim().substring(0,8);
                    long departureDate = DateTimeUtils.dateStrToEpochSecond(departureDateStr, BaseConstant.DATE_TIME_FORMAT_MM_DD_YY, propertyDTO.getTimezone());

                    GuestInHouseDTO guestInHouse = new GuestInHouseDTO();
                    guestInHouse.setPropertyId(propertyDTO.getId());
                    //设置First Name Last Name
                    String[] fullNames = guestName.split(", ");
                    if (fullNames.length >= 2) {
                        guestInHouse.setFirstName(fullNames[1]);
                        guestInHouse.setLastName(fullNames[0]);
                    } else {
                        guestInHouse.setLastName(fullNames[0]);
                        guestInHouse.setFirstName("");
                    }
                    guestInHouse.setCreatedTime(currentTimestamp);
                    guestInHouse.setCreatedBy(BaseConstant.ZERO);
                    guestInHouse.setCheckInDate(arrivalDate);
                    guestInHouse.setCheckOutDate(departureDate);
                    guestInHouseList.add(guestInHouse);
                }

                //去重返回
                return guestInHouseList.stream()
                        .collect(
                                Collectors.collectingAndThen(
                                        Collectors.toCollection(() -> new TreeSet<>(
                                                Comparator.comparing(GuestInHouseDTO::getInHouseRecordStr))), ArrayList::new
                                )
                        );
            } catch (IOException e) {
                log.error(e.getMessage(), e);
                throw new ParseReportException(BaseErrorCodeEnum.SYSTEM_ERROR.getI18nCode(),
                        BaseErrorCodeEnum.SYSTEM_ERROR.getCode(), "parse shiji [Reservations Entered on and by] report error", e);
            }
        }

        /**
         * 校验文件内容是否合法
         *
         * @param file 文件
         * @return void
         * @author lichen
         * @date 2025/7/26
         */
        @Override
        public void checkFile(MultipartFile file) {
            //校验文件格式
            UploadUtils.checkFileFormat(file, Lists.newArrayList("csv"));
            try (InputStream in = file.getInputStream()) {
                //校验文件内容
                ShijiFileCheckUtils.checkReservationsEnteredOnAndByFile(in);
            } catch (BadRequestException e) {
                throw e;
            } catch (Exception e2) {
                throw new InternalServerErrorException(BaseErrorCodeEnum.SYSTEM_ERROR.getI18nCode(),
                        BaseErrorCodeEnum.SYSTEM_ERROR.getCode(), "parse shiji [Reservations Entered on and by] report error", e2);
            }
        }

        /**
         * 处理数据
         *
         * @param propertyDTO 资产DTO
         * @param file        文件
         * @param userId      操作人ID
         * @param type        文件类型
         * @return void
         * @author lichen
         * @date 2025/7/26
         */
        @Override
        public void handleData(PropertyDTO propertyDTO, MultipartFile file, int userId, int type) {
            String tenantSymbol = propertyDTO.getTenantSymbol();
            String abbr = propertyDTO.getAbbr();

            try {
                // 设置事件体
                Map<String, Object> params = Maps.newHashMapWithExpectedSize(3);
                params.put(EventBodyParamEnum.TENANT_SYMBOL.getDesc(), tenantSymbol);
                params.put(EventBodyParamEnum.PROPERTY_ABBR.getDesc(), Lists.newArrayList(abbr));
                params.put(EventBodyParamEnum.SOURCE.getDesc(), SystemPlatformEnum.SHI_JI.getDesc());

                //上传文件
                String key = tenantSymbol + "/" + abbr + "/" + reservationsMadeYesterdayS3FilePath + UploadUtils.getRandomFileName(file.getOriginalFilename());
                amazonS3Service.uploadFile(file, key);

                //发布事件
                snsSender.publish(EventSubjectEnum.RESERVATIONS_MADE_YESTERDAY_SERVICE.getSubject(),
                        JsonUtils.convertObjToString(objectMapper, new EventBodyDTO(key, params)));
            } catch (BadRequestException badRequestException) {
                throw badRequestException;
            } catch (Exception e) {
                throw new InternalServerErrorException(BaseErrorCodeEnum.SYSTEM_ERROR.getI18nCode(),
                        BaseErrorCodeEnum.SYSTEM_ERROR.getCode(), "import shiji [Reservations Entered on and by] report exception", e);
            }
        }

    }