# ParseArrivalsDetailedServiceByShiji.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.cons.shiji.ArrivalsDetailedTitleCons;
    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.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.util.*;
    import java.util.stream.Collectors;

    /**
     * 解析Shiji系统的Arrivals Report Detailed
     */
    @Slf4j
    @Service
    public class ParseArrivalsDetailedServiceByShiji implements IParseFileService {

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

        /**
         * 支持的文件来源 、文件类型
         *
         * @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.ARRIVALS_DETAILED_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);
                //标题列
                CSVRecord titleRecord = iterable.iterator().next();
                //获取标题对应的索引
                Map<String, Integer> title2Index = ShijiFileCheckUtils.getTitleIndex(titleRecord, ArrivalsDetailedTitleCons.TITLE_LIST);
                //获取所有的数据列
                ArrayList<CSVRecord> allRows = Lists.newArrayList();
                iterable.forEach(allRows::add);

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

                long currentTimestamp = DateTimeUtils.nowTimestamp();

                Integer indexByGuestName = title2Index.get(ArrivalsDetailedTitleCons.NAME);
                Integer indexByArrivalDate = title2Index.get(ArrivalsDetailedTitleCons.ARRIVAL);
                Integer indexByDepartureDate = title2Index.get(ArrivalsDetailedTitleCons.ARRIVAL);

                for (int i = 0; i < allRows.size(); i++) {
                    CSVRecord csvRecord = allRows.get(i);

                    String guestName = ShijiFileCheckUtils.getByIndex(csvRecord, indexByGuestName).trim();
                    if(!isGuestName(guestName)){
                        continue;
                    }

                    //入住日期
                    String arrivalDateStr = ShijiFileCheckUtils.getByIndex(csvRecord, indexByArrivalDate);
                    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.getByIndex(departureCsvRecord, indexByDepartureDate);
                    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 [Arrivals Report Detailed] 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.checkArrivalsReportDetailedFile(in);
            } catch (BadRequestException e) {
                throw e;
            } catch (Exception e2) {
                throw new InternalServerErrorException(BaseErrorCodeEnum.SYSTEM_ERROR.getI18nCode(),
                        BaseErrorCodeEnum.SYSTEM_ERROR.getCode(), "parse shiji [Arrivals Report Detailed] 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 + "/" + arrivalsDetailedS3FilePath +
                        UploadUtils.getRandomFileName(file.getOriginalFilename());
                amazonS3Service.uploadFile(file, key);

                //发布事件
                snsSender.publish(EventSubjectEnum.ARRIVALS_DETAILED_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 [Arrivals Report Detailed] report exception", e);
            }
        }

        /**
         * 校验是否客人姓名
         *
         * @param guestName 客人姓名
         * @return boolean
         * @author lichen
         * @date 2025/8/12
         */
        private boolean isGuestName(String guestName) {
            if (StringUtils.isBlank(guestName)) return false;

            //正则表达式
            //1.可以包含字母、点、逗号、空格 2.必须是字母开头
            String regex = "^[a-zA-Z ][ ,.a-zA-Z]*$";

            return guestName.matches(regex);
        }
    }