# HistoryBARRateNextNDaysServiceImpl.java

    package cloud.wconnect.rateshop.service.revenue.impl;

    import cloud.wconnect.commonlib.component.BeanMapper;
    import cloud.wconnect.commonlib.cons.BaseConstant;
    import cloud.wconnect.commonlib.pojo.dto.UpdateLog;
    import cloud.wconnect.commonlib.util.DateTimeUtils;
    import cloud.wconnect.commonlib.util.JsonUtils;
    import cloud.wconnect.commonlib.util.UpdateLogUtil;
    import cloud.wconnect.rateshop.cons.rateshop.RateTypeEnum;
    import cloud.wconnect.rateshop.entity.rateshop.PropertyHotel;
    import cloud.wconnect.rateshop.entity.revenue.HistoryBARRateNextNDays;
    import cloud.wconnect.rateshop.entity.revenue.HistoryRatePropertyMapping;
    import cloud.wconnect.rateshop.mapper.revenue.HistoryBARRateNextNDaysMapper;
    import cloud.wconnect.rateshop.pojo.MergeDayHotelPriceDTO;
    import cloud.wconnect.rateshop.pojo.dto.revenue.DayHotelPriceDTO;
    import cloud.wconnect.rateshop.service.IHistoryRateNextNDaysByRateTypeService;
    import cloud.wconnect.rateshop.service.revenue.IHistoryBARRateNextNDaysService;
    import cloud.wconnect.rateshop.service.revenue.IHistoryRatePropertyMappingService;
    import com.baomidou.dynamic.datasource.annotation.DS;
    import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
    import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
    import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
    import com.fasterxml.jackson.databind.ObjectMapper;
    import com.google.common.collect.Lists;
    import org.apache.commons.collections.CollectionUtils;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;

    import java.util.*;
    import java.util.function.Function;
    import java.util.stream.Collectors;

    /**
     * <p>
     * 酒店当日的未来N天的历史BAR房价 服务实现类
     * </p>
     *
     * @author lichen
     * @since 2024-05-14
     */
    @Service
    @DS("rate_shop")
    public class HistoryBARRateNextNDaysServiceImpl extends ServiceImpl<HistoryBARRateNextNDaysMapper, HistoryBARRateNextNDays> implements IHistoryBARRateNextNDaysService, IHistoryRateNextNDaysByRateTypeService {

        @Autowired
        private ObjectMapper objectMapper;
        @Autowired
        private UpdateLogUtil updateLogUtil;
        @Autowired
        private IHistoryRatePropertyMappingService historyRatePropertyMappingService;
        @Autowired
        private BeanMapper beanMapper;

        //当前类对应的房价类型
        public static final int BEST_AVAILABLE_RATE = RateTypeEnum.BEST_AVAILABLE_RATE.getRateType();

        /**
         * 是否支持
         *
         * @param rateType 房价类型 1:早鸟价 2:BAR房价
         * @return java.lang.Boolean
         * @author lichen
         * @date 2024/5/15
         */
        @Override
        public Boolean supports(int rateType) {
            return rateType == BEST_AVAILABLE_RATE;
        }

        /**
         * 保存未来14天的房价
         *
         * @param hotelId           酒店ID
         * @param currencyId        币种ID
         * @param queryDate         采集房价的时刻
         * @param dayHotelPriceDTOS 房价数据集合
         * @param propertyHotels    酒店关联的资产
         * @param pos               销售地区
         * @return java.lang.Long 未来14天房价表的数据ID
         * @author lichen
         * @date 2024/5/15
         */
        @Override
        public Long save(Integer hotelId, Integer currencyId, Long queryDate, List<DayHotelPriceDTO> dayHotelPriceDTOS, List<PropertyHotel> propertyHotels, String pos) {
            //版本号(系统默认时区下的yyyyMMdd)
            Integer version = Integer.valueOf(DateTimeUtils.timestampToStr(queryDate, BaseConstant.DATE_FORMAT_YYYYMMDD, null));
            HistoryBARRateNextNDays oriHistoryBARRateNextNDays = get(version, hotelId, currencyId, pos);
            if (Objects.isNull(oriHistoryBARRateNextNDays)) {
                //updateLog
                String updateLogStr = JsonUtils.convertObjListToString(objectMapper, Lists.newArrayList(new UpdateLog(0, DateTimeUtils.nowTimestamp())));
                HistoryBARRateNextNDays insertEntity = new HistoryBARRateNextNDays().setHotelId(hotelId)
                        .setCurrencyId(currencyId).setVersion(version)
                        .setData(JsonUtils.convertObjListToString(objectMapper, dayHotelPriceDTOS))
                        .setPos(pos)
                        .setUpdateLog(updateLogStr);
                //保存房价
                save(insertEntity);
                return insertEntity.getId();
            } else {
                //原房价
                List<DayHotelPriceDTO> oriHistoryBARRateNextNDaysDataList = JsonUtils.convertStringToList(objectMapper, oriHistoryBARRateNextNDays.getData(),
                        DayHotelPriceDTO.class);
                Map<String, DayHotelPriceDTO> key2OriDayHotelPriceDTO = oriHistoryBARRateNextNDaysDataList.stream()
                        .collect(Collectors.toMap(DayHotelPriceDTO::generateKey, Function.identity()));
                Set<String> oriKey = key2OriDayHotelPriceDTO.keySet();

                //最新的房价
                Map<String, DayHotelPriceDTO> key2LatestDayHotelPriceDTO = dayHotelPriceDTOS.stream()
                        .collect(Collectors.toMap(DayHotelPriceDTO::generateKey, Function.identity()));
                Set<String> latestKey = key2LatestDayHotelPriceDTO.keySet();

                Set<String> allKey = new HashSet<>();
                allKey.addAll(oriKey);
                allKey.addAll(latestKey);

                List<DayHotelPriceDTO> historyBARRateNextNDaysDataListByUpdate = Lists.newArrayListWithCapacity(oriHistoryBARRateNextNDaysDataList.size());
                for (String key : allKey) {
                    DayHotelPriceDTO latest = key2LatestDayHotelPriceDTO.get(key);
                    if (Objects.nonNull(latest)) {
                        historyBARRateNextNDaysDataListByUpdate.add(latest);
                        continue;
                    }
                    historyBARRateNextNDaysDataListByUpdate.add(key2OriDayHotelPriceDTO.get(key));
                }
                //更新房价
                updateById(new HistoryBARRateNextNDays()
                        .setId(oriHistoryBARRateNextNDays.getId())
                        .setData(JsonUtils.convertObjListToString(objectMapper, historyBARRateNextNDaysDataListByUpdate))
                        .setUpdateLog(updateLogUtil.append(oriHistoryBARRateNextNDays.getUpdateLog(), 0)));
                return oriHistoryBARRateNextNDays.getId();
            }
        }

        /**
         * 查询指定版本号指定酒店指定币种的BAR房价信息
         *
         * @param version    版本号
         * @param hotelId    酒店ID
         * @param currencyId 币种ID
         * @param pos        销售地区
         * @return cloud.wconnect.rateshop.entity.revenue.HistoryBARRateNextNDays
         * @author lichen
         * @date 2024/5/15
         */
        @Override
        public HistoryBARRateNextNDays get(Integer version, Integer hotelId, Integer currencyId, String pos) {
            return getOne(new LambdaQueryWrapper<HistoryBARRateNextNDays>().eq(HistoryBARRateNextNDays::getVersion, version)
                    .eq(HistoryBARRateNextNDays::getHotelId, hotelId)
                    .eq(HistoryBARRateNextNDays::getCurrencyId, currencyId)
                    .eq(HistoryBARRateNextNDays::getPos, pos));
        }

        /**
         * 查询酒店在 指定资产的指定原点日期，未来14天的BAR房价
         *
         * @param tenantId   租户 id
         * @param propertyId 资产 id
         * @param hotelId    酒店 id
         * @param targetDate 指定日期(yyyyMMdd)
         * @param currencyId 币种ID
         * @param pos        销售地区
         * @return cloud.wconnect.rateshop.entity.revenue.HistoryBARRateNextNDays
         * @author lichen
         * @date 2024/5/16
         */
        @Override
        public HistoryBARRateNextNDays getNext14DaysRate(Integer tenantId, Integer propertyId, Integer hotelId, Integer targetDate, Integer currencyId, String pos) {
            List<HistoryRatePropertyMapping> propertyMappings = historyRatePropertyMappingService.list(new QueryWrapper<HistoryRatePropertyMapping>().lambda()
                    .eq(HistoryRatePropertyMapping::getTenantId, tenantId)
                    .eq(HistoryRatePropertyMapping::getPropertyId, propertyId)
                    .eq(HistoryRatePropertyMapping::getHotelId, hotelId)
                    .eq(HistoryRatePropertyMapping::getTargetDate, targetDate)
                    .eq(HistoryRatePropertyMapping::getRateType, BEST_AVAILABLE_RATE));
            if (CollectionUtils.isEmpty(propertyMappings)) return null;

            List<Long> rate14Ids = propertyMappings.stream().map(HistoryRatePropertyMapping::getRate14Id).toList();

            List<HistoryBARRateNextNDays> historyBARRateNextNDays = listByIdAndCurrencyIdAndPos(rate14Ids, currencyId, pos);
            if (CollectionUtils.isEmpty(historyBARRateNextNDays)) {
                return null;
            } else if (historyBARRateNextNDays.size() == 1) {
                return historyBARRateNextNDays.get(0);
            } else {
                Map<Integer, HistoryBARRateNextNDays> version2HistoryBARRateNextNDays = historyBARRateNextNDays.stream()
                        .collect(Collectors.toMap(HistoryBARRateNextNDays::getVersion, Function.identity()));
                Set<Integer> versions = version2HistoryBARRateNextNDays.keySet();
                //所有的房价数据
                List<MergeDayHotelPriceDTO> mergeDayHotelPriceDTOList = version2HistoryBARRateNextNDays.values().stream().map(item -> {
                    //把房价数据转化为集合
                    return JsonUtils.convertStringToList(objectMapper, item.getData(), MergeDayHotelPriceDTO.class)
                            .stream().peek(dayHotelPriceDTO -> dayHotelPriceDTO.setVersion(item.getVersion())).toList();
                }).flatMap(Collection::stream).toList();

                //version越大越优先，合并房价数据
                List<DayHotelPriceDTO> dayHotelPriceDTOList = mergeDayHotelPriceDTOList.stream()
                        .collect(Collectors.toMap(MergeDayHotelPriceDTO::generateKey, Function.identity(),
                                MergeDayHotelPriceDTO::merge, TreeMap::new)).values().stream()
                        .map(mergeDTO -> beanMapper.map(mergeDTO, DayHotelPriceDTO.class))
                        .toList();

                //获取最大的版本
                Integer maxVersion = versions.stream().max(Integer::compareTo).get();
                HistoryBARRateNextNDays historyBARRateNextNDaysByMaxVersion = version2HistoryBARRateNextNDays.get(maxVersion);
                historyBARRateNextNDaysByMaxVersion.setData(JsonUtils.convertObjListToString(objectMapper, dayHotelPriceDTOList));
                return historyBARRateNextNDaysByMaxVersion;
            }
        }

        /**
         * 根据ID、币种、销售地区查询酒店的房价
         *
         * @param rate14Ids  主键ID
         * @param currencyId 币种
         * @param pos        销售地区
         * @return java.util.List<cloud.wconnect.rateshop.entity.revenue.HistoryBARRateNextNDays>
         * @author lichen
         * @date 2024/7/11
         */
        private List<HistoryBARRateNextNDays> listByIdAndCurrencyIdAndPos(List<Long> rate14Ids, Integer currencyId, String pos) {
            return list(new LambdaQueryWrapper<HistoryBARRateNextNDays>().in(HistoryBARRateNextNDays::getId, rate14Ids)
                    .eq(HistoryBARRateNextNDays::getCurrencyId, currencyId)
                    .eq(HistoryBARRateNextNDays::getPos, pos));
        }
    }