package com.izouma.nineth.service;

import com.izouma.nineth.config.Constants;
import com.izouma.nineth.config.RedisKeys;
import com.izouma.nineth.config.SysConstants;
import com.izouma.nineth.domain.Collection;
import com.izouma.nineth.domain.*;
import com.izouma.nineth.dto.PageQuery;
import com.izouma.nineth.enums.*;
import com.izouma.nineth.exception.BusinessException;
import com.izouma.nineth.lock.RedisLockable;
import com.izouma.nineth.repo.*;
import com.izouma.nineth.utils.JpaUtils;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.transaction.Transactional;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
@AllArgsConstructor
public class ActivityOrderService {

    private final ActivityOrderRepo         activityOrderRepo;
    private final ActivityCollectionRepo    activityCollectionRepo;
    private final ActivityCollectionService activityCollectionService;
    private final AssetRepo                 assetRepo;
    private final OrderRepo                 orderRepo;
    private final CollectionRepo            collectionRepo;
    private final ActivityMaterialRepo      activityMaterialRepo;
    private final CollectionService         collectionService;
    private final AssetService              assetService;
    private final UserRepo                  userRepo;
    private final SysConfigService          sysConfigService;
    private final AirDropService            airDropService;
    private final AwardActivityCollectionService awardActivityCollectionService;
    private final ActivitySurpriseBoxRepo   activitySurpriseBoxRepo;
    private final ProjectService            projectService;

    public Page<ActivityOrder> all(PageQuery pageQuery) {
        return activityOrderRepo.findAll(JpaUtils.toSpecification(pageQuery, ActivityOrder.class), JpaUtils.toPageRequest(pageQuery));
    }

    /**
     * 活动领取
     * @param user 用户
     * @param mintActivityId  兑换活动Id
     * @param collectionId  兑换藏品Id
     * @param assetIds  消耗的资产Id
     * @return 是否成功
     */
    @RedisLockable(prefix = RedisKeys.ACTIVITY_ORDER_CREATE_LOCK, key = "#mintActivityId", expiration = 360)
    @Transactional
    public Asset create(User user, Long mintActivityId,Integer projectId, Long collectionId, Set<Long> assetIds) {
        if (projectId == null){
            projectId = projectService.getProjectId();
        }
        //库存
        Integer activityStock = activityCollectionService.getStock(mintActivityId , collectionId);

        //锁定活动记录，防止其他操作修改库存
        ActivityCollection activity = activityCollectionRepo.findByIdForUpdate(mintActivityId)
                .orElseThrow(new BusinessException("当前活动不存在"));
        //获取活动消耗的库存
        int exchangeNum = getExchangeNum(activity, collectionId);
        if (activityStock - exchangeNum < 0) {
            throw new BusinessException("活动剩余库存不足");
        }

        boolean activityNotStart = activity.getStartTime() != null && activity.getStartTime().isAfter(LocalDateTime.now());
        //测试人员Id
        Long testerUserId = (long) sysConfigService.getInt(SysConstants.TESTER_USER_ID);
        //判断收集活动未开始
        if (activityNotStart && !testerUserId.equals(user.getId())) {
            throw new BusinessException("当前活动还未开始");
        }
        //判断收集活动已结束
        boolean activityClosed = activity.getEndTime()!=null && LocalDateTime.now().isAfter(activity.getEndTime());
        if (activityClosed){
            throw new BusinessException("很遗憾，本次收集活动已结束");
        }
        //如果是多个单个藏品兑换单个藏品 则需要进行转换 因为单个没记录入藏品表
        if (activity.getType() == null || activity.getType().equals(ActivityCollectionType.DEFAULT)){
            List<ActivityCollectionInfo> list =  new ArrayList<>(1);
            //消耗品加入个人藏品
            list.add(ActivityCollectionInfo.builder().collectionId(activity.getCollectionId()).num(activity.getNum()).build());
            activity.setActivities(list);
        }
        //拼装消耗藏品列表
        List<Asset> assetList = new ArrayList<>();
        if (ActivityCollectionType.MANY_TO_MANY.equals(activity.getType())) {
            manyToManyAssetList(user, assetIds, activity, assetList);
        }else {
            List<Asset> assets = assetRepo
                    .findAllByProjectIdAndUserIdAndStatus(projectId,user.getId(), AssetStatus.NORMAL).stream().filter(item-> !item.isVariableType()).collect(Collectors.toList());
            //单一集齐可兑换和 任意集齐可兑换 计算消耗量需要分开处理
            if (ActivityCollectionType.ONE_TO_MANY.equals(activity.getType()) ||ActivityCollectionType.DEFAULT.equals(activity.getType())) {
                oneToManyAssetList(assetIds, activity, assetList, assets);
            }
            if (ActivityCollectionType.ANY_TO_ONE.equals(activity.getType())) {
                anyToOneAssetList(assetIds, activity, assetList, assets);
            }
            if (ActivityCollectionType.SOME_TO_ANY.equals(activity.getType())) {
                someToAnyAssetList(assetIds, activity, assetList, assets);
            }
        }
        if (assetList.isEmpty()){
            throw new BusinessException("参数非法");
        }

        //指定账户,黑洞账户
        long blackUserId = sysConfigService.getBigDecimal(SysConstants.BLACK_USER_ID).longValue();
        if(blackUserId == 0){
            blackUserId = Long.parseLong(Constants.DEFAULT_BLACK_USER);
        }

        User newOwner = userRepo.findByIdAndDelFalse(blackUserId).orElseThrow(new BusinessException("管理员未配置目标管理账户，无法兑换"));
        Set<Long> notDestroyAssets = activity.getActivities().stream().filter(ActivityCollectionInfo::isNotDestroy).map(ActivityCollectionInfo::getCollectionId).collect(Collectors.toSet());
        assetList = assetList.stream().filter(item -> !notDestroyAssets.contains(item.getCollectionId())).collect(Collectors.toList());
        if (assetList.isEmpty()){
            throw new BusinessException("请确认您兑换所消耗的藏品");
        }
        //消耗资产
        assetList.forEach(asset -> {
            if (asset.isPublicShow()) {
                if (asset.getPublicCollectionId() != null) {
                    List<Order> orders = orderRepo.findByCollectionId(asset.getPublicCollectionId());
                    if (orders.stream().anyMatch(o -> o.getStatus() != OrderStatus.CANCELLED)) {
                        throw new BusinessException("已有订单不可兑换");
                    }
                }

                //通过assetId关联删除
                List<Long> collectionIds = collectionRepo.findAllByAssetId(asset.getId());
                if (CollectionUtils.isNotEmpty(collectionIds)) {
                    log.info("取消展示删除collection {}", collectionIds);
                    collectionRepo.deleteAllByIdIn(collectionIds);
                }
            }

        });

        //收集记录
        ActivityOrder activityOrder = activityOrderRepo.save(ActivityOrder.builder()
                .userId(user.getId())
                .phone(user.getPhone())
                .activityCollection(activity.getCollectionName())
                .activityCollectionId(mintActivityId)
                .build());

        //兑换详情
        assetList.forEach(asset -> {
            activityMaterialRepo.save(
                    ActivityMaterial.builder()
                            .orderId(activityOrder.getId())
                            .assetId(asset.getId())
                            .category(asset.getCategory())
                            .collectionId(asset.getCollectionId())
                            .name(asset.getName())
                            .number(asset.getNumber())
                            .pic(asset.getPic())
                            .build());
            //转赠
            assetService.transfer(asset, asset.getPrice(), newOwner, OperationType.give.getDescription(), null);
        });

        //变更数据库库存
        if (activity.getType() == null || activity.getType().equals(ActivityCollectionType.DEFAULT)) {
            activityCollectionRepo.updateStock(activity.getId(), activity.getStock() - exchangeNum);
        }else {
            awardActivityCollectionService.updateStock(activity.getId(), collectionId, activityStock - exchangeNum);
        }
        List<AwardActivityCollectionInfo> awardList = activity.getAwardList();
        AwardActivityCollectionInfo award = awardList.stream().filter(item -> collectionId.equals(item.getCollectionId())).findFirst().get();
        Asset newAsset;
        if (AirDropType.asset.equals(award.getAirDropType())) {
            newAsset = giveOutAsset(user, collectionId, exchangeNum);
        } else if (AirDropType.SURPRISE_BOX.equals(award.getAirDropType())) {
            newAsset = giveOutSurpriseBox(user, collectionId, exchangeNum);
        } else {
            throw new BusinessException("不支持的类型");
        }
        //最后再减去活动缓存库存
        activityStock = Optional.ofNullable(activityCollectionService.decreaseStock(mintActivityId,collectionId, exchangeNum))
                .map(Math::toIntExact)
                .orElseThrow(new BusinessException("很遗憾，活动已无库存"));
        if (activityStock < 0) {
            //恢复活动库存
            activityCollectionService.increaseStock(mintActivityId,collectionId, exchangeNum);
            throw new BusinessException("领取失败，活动已无库存");
        }
        return newAsset;
    }


    /**
     *  发放的惊喜盒子
     * @param user 发放的用户
     * @param collectionId 发放的惊喜盒子数量
     * @param exchangeNum 发放的数量
     * @return 藏品
     */
    private Asset giveOutSurpriseBox(User user, Long collectionId, int exchangeNum) {
        Optional<ActivitySurpriseBox> surpriseBox = activitySurpriseBoxRepo.findById(collectionId);
        if (!surpriseBox.isPresent() || surpriseBox.get().getBoxSum() - exchangeNum < 0) {
            throw new BusinessException("惊喜盒子库存不足,请联系系统管理员");
        }
        ActivitySurpriseBox box = surpriseBox.get();
        airDropService.batchCreate(AirDrop.builder()
                .name("合成奖励发放")
                .type(AirDropType.SURPRISE_BOX)
                .surpriseBoxId(box.getId())
                .phone(Arrays.asList(user.getPhone()))
                .userIds(Arrays.asList(user.getId()))
                .projectId(box.getProjectId())
                .dropCount(exchangeNum)
                .operation(OperationType.EXCHANGE.getDescription())
                //积分抽奖 不需要在空投记录里保存
                .notSave(true)
                .build());
        List<FileObject> list = new ArrayList<>();
        list.add(new FileObject(box.getName(),box.getPic(),null,null));
        return Asset.builder().name(box.getName()).detail("惊喜盒子").pic(list).build();
    }

    /**
     *  发放藏品
     * @param user 发放的用户
     * @param collectionId 发放的藏品
     * @param exchangeNum 发放的数量
     * @return 藏品
     */
    private Asset giveOutAsset(User user, Long collectionId, int exchangeNum) {
        //查询兑换藏品获得数量
        Integer awardStock = collectionService.getStockCache(collectionId);
        if (awardStock - exchangeNum < 0) {
            throw new BusinessException("所兑换藏品剩余库存不足");
        }
        //兑换后的,锁定藏品记录
        Collection awardCollection = collectionRepo.findByIdForUpdate(collectionId)
                .orElseThrow(new BusinessException("无可兑换藏品"));

        //减少藏品库存
        awardStock = Optional.ofNullable(collectionService.increaseStockCache(awardCollection.getId(), -exchangeNum))
                .map(Math::toIntExact)
                .orElseThrow(new BusinessException("兑换藏品无库存"));
        if (awardStock < 0) {
            //如果扣掉数量后数量不足 则恢复藏品库存
            collectionService.increaseStockCache(awardCollection.getId(), exchangeNum);
            throw new BusinessException("兑换藏品剩余库存不足");
        }
        Asset newAsset;
        try {
            AirDrop airDrop = airDropService.batchCreate(AirDrop.builder()
                    .name("合成奖励发放")
                    .type(AirDropType.asset)
                    .collectionId(awardCollection.getId())
                    .phone(Arrays.asList(user.getPhone()))
                    .userIds(Arrays.asList(user.getId()))
                    .projectId(awardCollection.getProjectId())
                    .dropCount(exchangeNum)
                    .operation(OperationType.EXCHANGE.getDescription())
                    //积分抽奖 不需要在空投记录里保存
                    .notSave(true)
                    .build());
            newAsset = airDrop.getAsset();
        }catch (Exception e){
            //如果空投出错 恢复redis库存
            collectionService.increaseStockCache(awardCollection.getId(), exchangeNum);
            throw new BusinessException("兑换藏品剩余库存不足");
        }
        return newAsset;
    }

    /**
     * 获取活动获得藏品数
     * @param activity 活动
     * @param awardCollectionId 获得的藏品id
     * @return 活动获得藏品数
     */
    private int getExchangeNum(ActivityCollection activity , Long awardCollectionId) {
        if (activity.getType() == null || activity.getType().equals(ActivityCollectionType.DEFAULT)) {
            //最早的合成活动只能兑换1个
            return 1;
        }else {
            AwardActivityCollectionInfo collectionInfo = activity.getAwardList()
                    .stream().filter(item -> item.getCollectionId().equals(awardCollectionId)).findFirst().orElseThrow(new BusinessException("未找到所兑换的藏品"));
            return collectionInfo.getExchangeNum();
        }
    }

    /**
     * 集齐指定数量+任意藏品可兑换
     * @param assetIds 兑换的藏品ID
     * @param activity 活动
     * @param assetList 消耗的藏品
     * @param assets 持有的藏品
     */
    private void someToAnyAssetList(Set<Long> assetIds, ActivityCollection activity, List<Asset> assetList, List<Asset> assets) {
        List<Asset> toUseAssets = assets.stream().filter(item -> assetIds.contains(item.getId())).collect(Collectors.toList());
        Set<Long> blackList =  activity.getActivities()
                .stream().filter(item -> !item.getMustNeedCollected()).map(ActivityCollectionInfo::getCollectionId).collect(Collectors.toSet());
        List<Asset> blackCollect = toUseAssets.stream().filter(item -> blackList.contains(item.getCollectionId())).collect(Collectors.toList());
        if (!blackCollect.isEmpty()){
            StringBuilder errorMsg = new StringBuilder();
            errorMsg.append("您选中的有不可兑换藏品,其中为");
            blackCollect.forEach(item ->errorMsg.append("【").append(item.getName()).append("】").append(";"));
            errorMsg.deleteCharAt(errorMsg.length() - 1);
            throw new BusinessException(errorMsg.toString());
        }
        List<ActivityCollectionInfo> mustNeedCollected = activity.getActivities()
                .stream().filter(ActivityCollectionInfo::getMustNeedCollected).collect(Collectors.toList());
        //计算必须兑换的藏品数 如果小于要求的藏品数 进行抛错处理
        //此处 获取了必须要收集的藏品id
        Set<Long> mustNeedCollectionIds = mustNeedCollected.stream().map(ActivityCollectionInfo::getCollectionId).collect(Collectors.toSet());
        //计算消耗的藏品中 消耗的必须兑换藏品数量,先把必须消耗的藏品捞出来
        List<Asset> removeAssets = new ArrayList<>();
        //先添加 必须收集的藏品数
        StringBuilder errorMsg = new StringBuilder("");
        mustNeedCollected.forEach(item -> {
            List<Asset> collect = toUseAssets.stream()
                    .filter(asset -> asset.getCollectionId().equals(item.getCollectionId())).collect(Collectors.toList());
            //选择的必选藏品超过指定数量
            if (collect.size() > item.getNum()) {
                errorMsg.append("【").append(item.getCollectionName()).append("】;");
            } else {
                removeAssets.addAll(collect);
            }
        });
        if (errorMsg.length()>0) {
            errorMsg.delete(0, errorMsg.length());
            errorMsg.append("超过要求数量,请重新选择消耗藏品");
            throw new BusinessException(errorMsg.toString());
        }
        if (removeAssets.size() < mustNeedCollected.stream().mapToLong(ActivityCollectionInfo::getNum).sum()){
            errorMsg.delete(0, errorMsg.length());
            errorMsg.append("活动要求收集");
            mustNeedCollected.forEach(item -> errorMsg.append("【").append(item.getCollectionName()).append("】").append(item.getNum()).append("张;"));
            errorMsg.deleteCharAt(errorMsg.length() - 1);
            errorMsg.append("请确认您收集数量");
            throw new BusinessException(errorMsg.toString());
        }
        //计算总共要扣款的量
        int needCollectionNum = activity.getNeedCollectedNum();
        //需要补足的藏品数量
        int otherNum = needCollectionNum-removeAssets.size();
        //补足其他非必须藏品到指定数量
        removeAssets.addAll(toUseAssets.stream().filter(item -> !mustNeedCollectionIds.contains(item.getCollectionId()))
                .limit(otherNum).collect(Collectors.toList()));
        if (removeAssets.isEmpty() || removeAssets.size() < needCollectionNum) {
            throw new BusinessException("收集的数量不足，无法领取");
        }
        assetList.addAll(removeAssets);
    }

    private void anyToOneAssetList(Set<Long> assetIds, ActivityCollection activity, List<Asset> assetList, List<Asset> assets) {
        //集全指定藏品数量可兑换只需要消耗传入的库存
        List<Asset> toUseAssets = assets.stream().filter(item -> assetIds.contains(item.getId())).collect(Collectors.toList());
        //必须消耗的藏品种类集合
        List<ActivityCollectionInfo> mustNeedCollected = activity.getActivities()
                .stream().filter(ActivityCollectionInfo::getMustNeedCollected).collect(Collectors.toList());
        //计算必须兑换的藏品数 如果小于要求的藏品数 进行抛错处理
        //此处 获取了必须要收集的藏品id
        Set<Long> mustNeedCollectionIds = mustNeedCollected.stream().map(ActivityCollectionInfo::getCollectionId).collect(Collectors.toSet());
        //计算消耗的藏品中 消耗的必须兑换藏品数量
        long count = toUseAssets.stream().filter(item -> mustNeedCollectionIds.contains(item.getCollectionId())).count();
        //如果消耗的数量不够必须消耗的数量
        if (count < mustNeedCollected.stream().mapToLong(ActivityCollectionInfo::getNum).sum()){
            StringBuilder errorMsg = new StringBuilder();
            errorMsg.append("活动要求收集");
            mustNeedCollected.forEach(item -> errorMsg.append("【").append(item.getCollectionName()).append("】").append(item.getNum()).append("张;"));
            errorMsg.deleteCharAt(errorMsg.length() - 1);
            errorMsg.append("请确认您收集数量");
            throw new BusinessException(errorMsg.toString());
        }
        //计算总共要扣款的量
        int needCollectionNum = activity.getActivities().stream().mapToInt(ActivityCollectionInfo::getNum).sum();

        if (toUseAssets.isEmpty() || toUseAssets.size() < needCollectionNum) {
            throw new BusinessException("收集的数量不足，无法领取");
        }
        assetList.addAll(toUseAssets.stream().limit(needCollectionNum).collect(Collectors.toList()));
    }

    private void oneToManyAssetList(Set<Long> assetIds, ActivityCollection activity, List<Asset> assetList, List<Asset> assets) {
        List<Asset> toUseAssets = assets.stream().filter(item -> assetIds.contains(item.getId())).collect(Collectors.toList());
        //如果消耗的库存 不属于同一款藏品 抛错
        if (toUseAssets.isEmpty() || toUseAssets.stream().map(Asset::getCollectionId).collect(Collectors.toSet()).size() > 1) {
            throw new BusinessException("请选择要兑换的库存");
        }
        //获取要消耗的数量
        ActivityCollectionInfo collectionInfo = activity.getActivities().stream()
                .filter(item -> item.getCollectionId().equals(toUseAssets.get(0).getCollectionId()))
                .findFirst().orElseThrow(new BusinessException("与要求库存不符合"));
        if (toUseAssets.isEmpty() || toUseAssets.size() < collectionInfo.getNum()) {
            throw new BusinessException("收集的数量不足，无法领取");
        }
        assetList.addAll(toUseAssets.stream().limit(collectionInfo.getNum()).collect(Collectors.toList()));
    }

    private void manyToManyAssetList(User user, Set<Long> assetIds, ActivityCollection activity, List<Asset> assetList) {
        for (ActivityCollectionInfo info : activity.getActivities()) {
            List<Asset> assets = assetRepo.findAllByCollectionIdAndUserIdAndStatus(info.getCollectionId(), user.getId(),
                    AssetStatus.NORMAL).stream().filter(item-> !item.isVariableType()).collect(Collectors.toList());
            //选出用户拥有的Id 进行 消耗
            assets = assets.stream().filter(item -> assetIds.contains(item.getId())).collect(Collectors.toList());
            //如果不够 进行报错
            if (assets.size() < info.getNum()) {
                throw new BusinessException("收集的数量不足，无法领取");
            }
            assetList.addAll(assets.stream().limit(info.getNum()).collect(Collectors.toList()));
        }
    }


    public ActivityCollection activityDetail(Integer projectId,Long id,User user) {
        ActivityCollection activityCollection = activityCollectionRepo.findById(id).orElseThrow(new BusinessException("活动不存在"));
        if(activityCollection.getType() == null){
            activityCollection.setType(ActivityCollectionType.DEFAULT);
        }
        //活动要求总量 除了 全平台匹配自身有 和单一集齐不需要 其余都可以自己算
        if (!ActivityCollectionType.SOME_TO_ANY.equals(activityCollection.getType()) && !ActivityCollectionType.ONE_TO_MANY.equals(activityCollection.getType())) {
            activityCollection.setNeedCollectedNum(activityCollection.getActivities().stream().mapToInt(ActivityCollectionInfo::getNum).sum());
        }
        //如果是普通的进行数据兼容处理 转换为列表 用于统一判断是否 可兑换藏品
        if (ActivityCollectionType.DEFAULT.equals(activityCollection.getType())){
            ActivityCollectionInfo info = ActivityCollectionInfo.builder()
                    .num(activityCollection.getNum())
                    .collectionId(activityCollection.getCollectionId())
                    .collectionName(activityCollection.getCollectionName()).build();
            List<ActivityCollectionInfo> activities = new ArrayList<>();
            activities.add(info);
            activityCollection.setActivities(activities);
            AwardActivityCollectionInfo award = AwardActivityCollectionInfo.builder()
                    .num(activityCollection.getTotal())
                    .stock(activityCollection.getStock())
                    .collectionId(activityCollection.getAwardCollectionId())
                    .collectionName(activityCollection.getAwardCollectionName())
                    .stock(activityCollection.getStock()).build();
            List<AwardActivityCollectionInfo> awards = new ArrayList<>();
            awards.add(award);
            activityCollection.setAwardList(awards);
            activityCollection.setType(ActivityCollectionType.ONE_TO_MANY);
        }

        //添加收集物品展示 因为要求有几张展示几张 所以进行复制
        List<ActivityCollectionInfo> parseNumActivities = new ArrayList<>();
        if (ActivityCollectionType.SOME_TO_ANY.equals(activityCollection.getType())){
            List<Asset> assets = assetRepo.findAllByProjectIdAndUserIdAndStatus(projectId, user.getId(),AssetStatus.NORMAL)
                    .stream().filter(item-> !item.isVariableType()).collect(Collectors.toList());
            assets.forEach(temp -> {
                ActivityCollectionInfo info = new ActivityCollectionInfo();
                info.setId(temp.getId());
                info.setCollectionId(temp.getCollectionId());
                info.setCollectionName(temp.getName());
                info.setImgUrl(temp.getPic().stream().filter(pic -> StringUtils.hasText(pic.getUrl())).findFirst().get().getUrl());
                parseNumActivities.add(info);
            });
        }else {
            //其余是对可参与兑换藏品进行添加
            if (ActivityCollectionType.ONE_TO_MANY.equals(activityCollection.getType())){
                //添加单一集齐的收集信息
                List<ActivityCollectionInfo> infoList = new ArrayList<>();
                infoList.addAll(activityCollection.getActivities());
                activityCollection.setCollectionInfo(infoList);
            }
            activityCollection.getActivities().forEach(item -> {
                List<Asset> assets = assetRepo.findAllByCollectionIdAndUserIdAndStatus(item.getCollectionId(), user.getId(),
                        AssetStatus.NORMAL).stream().filter(asset-> !asset.isVariableType()).collect(Collectors.toList());
                assets.forEach(temp -> {
                    ActivityCollectionInfo info = new ActivityCollectionInfo();
                    info.setId(temp.getId());
                    info.setCollectionId(temp.getCollectionId());
                    info.setCollectionName(temp.getName());
                    info.setImgUrl(temp.getPic().stream().filter(pic -> StringUtils.hasText(pic.getUrl())).findFirst().get().getUrl());
                    parseNumActivities.add(info);
                });

            });
        }
        activityCollection.setActivities(parseNumActivities);
        //兑换物品展示
        activityCollection.getAwardList().parallelStream().forEach(item -> {
            if (AirDropType.SURPRISE_BOX.equals(item.getAirDropType())){
                ActivitySurpriseBox surpriseBox = activitySurpriseBoxRepo.findById(item.getCollectionId()).orElseThrow(() -> new BusinessException("兑换的盒子不存在"));
                item.setImgUrl(surpriseBox.getPic());
            }else {
                Collection collection = collectionRepo.findById(item.getCollectionId()).orElseThrow(new BusinessException("藏品无记录"));
                item.setImgUrl(collection.getPic().stream().filter(pic -> StringUtils.hasText(pic.getUrl())).findFirst().get().getUrl());
            }
        });
        return activityCollection;
    }
}
