package shop.alien.store.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import shop.alien.entity.store.*;
import shop.alien.entity.store.vo.LifeCouponVo;
import shop.alien.entity.store.vo.LifeTuanGouParamVo;
import shop.alien.mapper.*;
import shop.alien.store.service.LifeGroupPackageService;
import shop.alien.store.util.GroupConstant;
import shop.alien.util.common.UniqueRandomNumGenerator;
import shop.alien.util.common.constant.DiscountCouponEnum;
import shop.alien.util.coupon.DiscountCouponExpirationUtil;
import shop.alien.util.type.LifeCollectIdentityQuery;
import shop.alien.util.type.LifeNoticeUtil;
import shop.alien.util.type.TypeUtil;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 团购包
 *
 * @author ssk
 * @version 1.0
 * @date 2024/12/23 16:11
 */
@Service
@RequiredArgsConstructor
public class LifeGroupPackageServiceImpl extends ServiceImpl<LifeGroupPackageMapper, LifeGroupPackage> implements LifeGroupPackageService {

    private final LifeCouponMapper lifeCouponMapper;
    private final LifeDiscountCouponMapper lifeDiscountCouponMapper;
    private final LifeUserOrderMapper lifeUserOrderMapper;
    private final LifeGroupPackageMapper lifeGroupPackageMapper;
    private final LifeDiscountCouponUserMapper lifeDiscountCouponUserMapper;
    private final LifeUserMapper lifeUserMapper;
    private final LifeNoticeMapper lifeNoticeMapper;

    private final LifeNoticeUtil lifeNoticeUtil;
    private final StoreInfoMapper storeInfoMapper;
    private final StoreGroupInfoMapper storeGroupInfoMapper;
    private final StoreImgMapper storeImgMapper;
    private final StoreHotelGroupRoomInfoMapper storeHotelGroupRoomInfoMapper;
    private final LifeCollectMapper lifeCollectMapper;

    private final TypeUtil typeUtil;


    @Override
    public int addOrUpdateGroupPackage(LifeTuanGouParamVo lifeTuanGouParamVo) {
        LifeCoupon lifeCoupon = lifeTuanGouParamVo.getTuangou();
        List<LifeGroupPackage> packageList = lifeTuanGouParamVo.getTuangouPackageList();
//        List<StoreGroupInfo> storeGroupInfos = lifeTuanGouParamVo.getStoreGroupInfos();


        if (StringUtils.isEmpty(lifeCoupon.getId())) {
            lifeCoupon.setType(2);
            lifeCoupon.setStatus(-1);
            lifeCoupon.setCouponCode(UniqueRandomNumGenerator.generateUniqueCode(12));
            int ret = lifeCouponMapper.insert(lifeCoupon);
            if (ret == 0) {
                return 0;
            }
//            if (!CollectionUtils.isEmpty(storeGroupInfos)) {
//                for (StoreGroupInfo storeGroupInfo : storeGroupInfos) {
//                    storeGroupInfo.setGroupId(Integer.parseInt(lifeCoupon.getId()));
//                    storeGroupInfoMapper.insert(storeGroupInfo);
//                }
//            }

            if (!packageList.isEmpty()) {
                for (LifeGroupPackage lifeGroupPackage : packageList) {
                    if (StringUtils.isEmpty(lifeGroupPackage.getId())) {
                        lifeGroupPackage.setQuanId(lifeCoupon.getId());
                        lifeGroupPackageMapper.insert(lifeGroupPackage);
                    }
                }
            }
            return ret;
        } else {
            //状态变更为待审核
            lifeCoupon.setStatus(-1);
            int ret = lifeCouponMapper.updateById(lifeCoupon);
            if (ret == 0) {
                return 0;
            }
            // 添加保价逻辑
            // 查询
            LifeCoupon lifeCouponById = lifeCouponMapper.selectById(lifeCoupon.getId());
            // 当用户购买该团购，并且在开启保价
            if (lifeCouponById.getOpenPriceProtection() != null && lifeCouponById.getPriceBelow() != null && lifeCouponById.getCouponComp() != null && lifeCouponById.getCouponCompDate() != null && lifeCouponById.getOpenPriceProtection() > 0) {
                // 查询购买这个团购的用户订单
                LambdaUpdateWrapper<LifeUserOrder> wrapper = new LambdaUpdateWrapper<>();
                wrapper.eq(LifeUserOrder::getQuanId, lifeCouponById.getId());
                List<LifeUserOrder> lifeUserOrders = lifeUserOrderMapper.selectList(wrapper);
                if (!lifeUserOrders.isEmpty()) {
                    // 在保价有效期内
                    // 七天前的时间
                    LocalDateTime sevenDaysAgo = LocalDateTime.now().minusDays(7);
                    for (LifeUserOrder lifeUserOrder : lifeUserOrders) {
                        Date createdTime = lifeUserOrder.getCreatedTime();
                        LocalDateTime orderCreatedTime = createdTime.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
                        if (orderCreatedTime.isAfter(sevenDaysAgo)) {
                            // 商家修改的价格
                            String price = lifeCoupon.getPrice();
                            BigDecimal decimalPrice = new BigDecimal(price);
                            // 用户购买时价格
                            String userPrice = lifeUserOrder.getPrice();
                            BigDecimal decimalUserPrice = new BigDecimal(userPrice);
                            // 商户修改价格 低于最开始规定的降价范围时，触发保价服务
                            // 计算差值，并取绝对值
                            BigDecimal priceDifference = decimalPrice.subtract(decimalUserPrice).abs();

                            // 将lifeCouponById.getPriceBelow() 转换为 BigDecimal
                            BigDecimal priceBelow = BigDecimal.valueOf(lifeCouponById.getPriceBelow());

                            // 商户修改价格 低于最开始规定的降价范围时，触发保价服务
                            if (priceDifference.compareTo(priceBelow) > 0) {                                // 给对应用户添加这个商家的优惠券 发送通知
                                // 优惠券
                                LifeDiscountCoupon newLifeCoupon = new LifeDiscountCoupon();
                                newLifeCoupon.setName("价保补偿优惠券");
                                newLifeCoupon.setStoreId(lifeCouponById.getStoreId());
                                newLifeCoupon.setNominalValue(new BigDecimal(lifeCouponById.getCouponComp()));
                                // 待定 有效期
                                newLifeCoupon.setExpirationDate(lifeCouponById.getCouponCompDate());
                                newLifeCoupon.setStartDate(LocalDate.now());
                                // 设置结束日期为当前时间加上有效期
                                newLifeCoupon.setEndDate(LocalDate.now().plusDays(lifeCouponById.getCouponCompDate()));
                                newLifeCoupon.setSingleQty(1);
                                newLifeCoupon.setType(1);
                                newLifeCoupon.setCreatedTime(new Date());
                                if (lifeDiscountCouponMapper.insert(newLifeCoupon) > 0) {
                                    // 把优惠券分给对应用户
                                    // 获取刚刚插入的优惠券的 ID
                                    Integer couponId = newLifeCoupon.getId();
                                    // 根据 ID 查询刚刚插入的优惠券
                                    LifeDiscountCoupon insertedCoupon = lifeDiscountCouponMapper.selectById(couponId);

                                    // 把优惠券分给对应用户
                                    LifeDiscountCouponUser lifeDiscountCouponUser = new LifeDiscountCouponUser();
                                    // 设置该优惠券记录的优惠券 ID
                                    lifeDiscountCouponUser.setCouponId(insertedCoupon.getId());
                                    // 设置该优惠券记录的用户 ID 为当前用户 ID
                                    lifeDiscountCouponUser.setUserId(Integer.valueOf(lifeUserOrder.getUserId()));
                                    // 设置该优惠券的领取时间为当前时间
                                    lifeDiscountCouponUser.setReceiveTime(new Date());
                                    lifeDiscountCouponUser.setExpirationTime(DiscountCouponExpirationUtil.resolveLifeDiscountCouponExpiration(
                                            lifeDiscountCouponUser.getReceiveTime(),
                                            insertedCoupon.getLongTermValid(),
                                            insertedCoupon.getSpecifiedDay(),
                                            insertedCoupon.getExpirationDate(),
                                            insertedCoupon.getValidDate(),
                                            insertedCoupon.getEndDate(),
                                            ZoneId.systemDefault()));
                                    // 设置该优惠券的状态为待使用
                                    lifeDiscountCouponUser.setStatus(Integer.parseInt(DiscountCouponEnum.WAITING_USED.getValue()));
                                    lifeDiscountCouponUser.setIssueSource(5); // 5-平台发放（团购套餐补偿）
                                    // 将该用户优惠券记录插入到数据库中
                                    if (lifeDiscountCouponUserMapper.insert(lifeDiscountCouponUser) > 0) {
                                        // 发送通知
                                        LifeNotice lifeMessage = new LifeNotice();
                                        LifeUser lifeUser = lifeUserMapper.selectById(lifeUserOrder.getUserId());
                                        lifeMessage.setReceiverId("user_" + lifeUser.getUserPhone());
                                        String text = "您的编号为" + lifeUserOrder.getOrderNo() + "的订单降价了，平台已为您发放优惠价补偿，现已发放至您的的优惠券中，快去查收吧";
                                        lifeMessage.setContext(text);
                                        lifeMessage.setSenderId("system");
                                        lifeMessage.setIsRead(0);
                                        lifeMessage.setNoticeType(2);
                                        lifeNoticeUtil.fillUserTypeAndRefId(lifeMessage);
                                        lifeNoticeMapper.insert(lifeMessage);
                                    }
                                }
                            }
                        }

                    }
                }

            }

            LambdaUpdateWrapper<LifeGroupPackage> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(LifeGroupPackage::getQuanId, lifeCoupon.getId());
            lifeGroupPackageMapper.delete(updateWrapper);
            for (LifeGroupPackage lifeGroupPackage : packageList) {
                if (StringUtils.isEmpty(lifeGroupPackage.getId())) {
                    lifeGroupPackage.setQuanId(lifeCoupon.getId());
                    lifeGroupPackageMapper.insert(lifeGroupPackage);
                }
            }
            return ret;
        }
    }


    @Override
    public int addOrUpdateHotelGroupPackage(LifeTuanGouParamVo lifeTuanGouParamVo) {
        LifeCoupon lifeCoupon = lifeTuanGouParamVo.getTuangou();
        List<StoreHotelGroupRoomInfo> storeHotelGroupRoomInfoList = lifeTuanGouParamVo.getTuangouHotelRoomList();

        if (StringUtils.isEmpty(lifeCoupon.getId())) {
            lifeCoupon.setType(GroupConstant.LIFE_GROUP_TYPE);
            lifeCoupon.setStatus(GroupConstant.LIFE_COUPON_STATUS_PENDING_APPROVAL);
            lifeCoupon.setCouponCode(UniqueRandomNumGenerator.generateUniqueCode(12));
            int ret = lifeCouponMapper.insert(lifeCoupon);
            if (ret == 0) {
                return 0;
            }

            if (!storeHotelGroupRoomInfoList.isEmpty()) {
                for (StoreHotelGroupRoomInfo storeHotelGroupRoomInfos : storeHotelGroupRoomInfoList) {
                    if (StringUtils.isEmpty(storeHotelGroupRoomInfos.getId())) {
                        storeHotelGroupRoomInfos.setGroupId(lifeCoupon.getId());
                        storeHotelGroupRoomInfoMapper.insert(storeHotelGroupRoomInfos);
                    }
                }
            }
            return ret;
        } else {
            //状态变更为待审核
            lifeCoupon.setStatus(GroupConstant.LIFE_COUPON_STATUS_PENDING_APPROVAL);
            int ret = lifeCouponMapper.updateById(lifeCoupon);
            if (ret == 0) {
                return 0;
            }
            // 添加保价逻辑
            // 查询
            LifeCoupon lifeCouponById = lifeCouponMapper.selectById(lifeCoupon.getId());
            // 当用户购买该团购，并且在开启保价
            if (lifeCouponById.getOpenPriceProtection() != null && lifeCouponById.getPriceBelow() != null && lifeCouponById.getCouponComp() != null && lifeCouponById.getCouponCompDate() != null && lifeCouponById.getOpenPriceProtection() > 0) {
                // 查询购买这个团购的用户订单
                LambdaUpdateWrapper<LifeUserOrder> wrapper = new LambdaUpdateWrapper<>();
                wrapper.eq(LifeUserOrder::getQuanId, lifeCouponById.getId());
                List<LifeUserOrder> lifeUserOrders = lifeUserOrderMapper.selectList(wrapper);
                if (!lifeUserOrders.isEmpty()) {
                    // 在保价有效期内
                    // 七天前的时间
                    LocalDateTime sevenDaysAgo = LocalDateTime.now().minusDays(7);
                    for (LifeUserOrder lifeUserOrder : lifeUserOrders) {
                        Date createdTime = lifeUserOrder.getCreatedTime();
                        LocalDateTime orderCreatedTime = createdTime.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
                        if (orderCreatedTime.isAfter(sevenDaysAgo)) {
                            // 商家修改的价格
                            String price = lifeCoupon.getPrice();
                            BigDecimal decimalPrice = new BigDecimal(price);
                            // 用户购买时价格
                            String userPrice = lifeUserOrder.getPrice();
                            BigDecimal decimalUserPrice = new BigDecimal(userPrice);
                            // 商户修改价格 低于最开始规定的降价范围时，触发保价服务
                            // 计算差值，并取绝对值
                            BigDecimal priceDifference = decimalPrice.subtract(decimalUserPrice).abs();

                            // 将lifeCouponById.getPriceBelow() 转换为 BigDecimal
                            BigDecimal priceBelow = BigDecimal.valueOf(lifeCouponById.getPriceBelow());

                            // 商户修改价格 低于最开始规定的降价范围时，触发保价服务
                            if (priceDifference.compareTo(priceBelow) > 0) {                                // 给对应用户添加这个商家的优惠券 发送通知
                                // 优惠券
                                LifeDiscountCoupon newLifeCoupon = new LifeDiscountCoupon();
                                newLifeCoupon.setName("价保补偿优惠券");
                                newLifeCoupon.setStoreId(lifeCouponById.getStoreId());
                                newLifeCoupon.setNominalValue(new BigDecimal(lifeCouponById.getCouponComp()));
                                // 待定 有效期
                                newLifeCoupon.setExpirationDate(lifeCouponById.getCouponCompDate());
                                newLifeCoupon.setStartDate(LocalDate.now());
                                // 设置结束日期为当前时间加上有效期
                                newLifeCoupon.setEndDate(LocalDate.now().plusDays(lifeCouponById.getCouponCompDate()));
                                newLifeCoupon.setSingleQty(1);
                                newLifeCoupon.setType(1);
                                newLifeCoupon.setCreatedTime(new Date());
                                if (lifeDiscountCouponMapper.insert(newLifeCoupon) > 0) {
                                    // 把优惠券分给对应用户
                                    // 获取刚刚插入的优惠券的 ID
                                    Integer couponId = newLifeCoupon.getId();
                                    // 根据 ID 查询刚刚插入的优惠券
                                    LifeDiscountCoupon insertedCoupon = lifeDiscountCouponMapper.selectById(couponId);

                                    // 把优惠券分给对应用户
                                    LifeDiscountCouponUser lifeDiscountCouponUser = new LifeDiscountCouponUser();
                                    // 设置该优惠券记录的优惠券 ID
                                    lifeDiscountCouponUser.setCouponId(insertedCoupon.getId());
                                    // 设置该优惠券记录的用户 ID 为当前用户 ID
                                    lifeDiscountCouponUser.setUserId(Integer.valueOf(lifeUserOrder.getUserId()));
                                    // 设置该优惠券的领取时间为当前时间
                                    lifeDiscountCouponUser.setReceiveTime(new Date());
                                    lifeDiscountCouponUser.setExpirationTime(DiscountCouponExpirationUtil.resolveLifeDiscountCouponExpiration(
                                            lifeDiscountCouponUser.getReceiveTime(),
                                            insertedCoupon.getLongTermValid(),
                                            insertedCoupon.getSpecifiedDay(),
                                            insertedCoupon.getExpirationDate(),
                                            insertedCoupon.getValidDate(),
                                            insertedCoupon.getEndDate(),
                                            ZoneId.systemDefault()));
                                    // 设置该优惠券的状态为待使用
                                    lifeDiscountCouponUser.setStatus(Integer.parseInt(DiscountCouponEnum.WAITING_USED.getValue()));
                                    lifeDiscountCouponUser.setIssueSource(5); // 5-平台发放（团购套餐补偿）
                                    // 将该用户优惠券记录插入到数据库中
                                    if (lifeDiscountCouponUserMapper.insert(lifeDiscountCouponUser) > 0) {
                                        // 发送通知
                                        LifeNotice lifeMessage = new LifeNotice();
                                        LifeUser lifeUser = lifeUserMapper.selectById(lifeUserOrder.getUserId());
                                        lifeMessage.setReceiverId("user_" + lifeUser.getUserPhone());
                                        String text = "您的编号为" + lifeUserOrder.getOrderNo() + "的订单降价了，平台已为您发放优惠价补偿，现已发放至您的的优惠券中，快去查收吧";
                                        lifeMessage.setContext(text);
                                        lifeMessage.setSenderId("system");
                                        lifeMessage.setIsRead(0);
                                        lifeMessage.setNoticeType(2);
                                        lifeNoticeUtil.fillUserTypeAndRefId(lifeMessage);
                                        lifeNoticeMapper.insert(lifeMessage);
                                    }
                                }
                            }
                        }

                    }
                }

            }

            LambdaUpdateWrapper<StoreHotelGroupRoomInfo> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(StoreHotelGroupRoomInfo::getGroupId, lifeCoupon.getId());
            storeHotelGroupRoomInfoList.stream().forEach(RoomInfoList -> {
                RoomInfoList.setGroupId(lifeCoupon.getId());
                storeHotelGroupRoomInfoMapper.updateById(RoomInfoList);
            });
            return ret;
        }
    }

    @Override
    public IPage<LifeCouponVo> getGroupPackageList(Integer pageNum, Integer pageSize, String storeId, String status, String couponCode, String name) {
        IPage<LifeCouponVo> iPage = new Page<>(pageNum, pageSize);
        QueryWrapper<LifeCouponVo> wrapper = new QueryWrapper<>();
        wrapper.eq(StringUtils.isNotEmpty(storeId), "coupon.store_id ", storeId)
//                .eq(StringUtils.isNotEmpty(status), "coupon.status", status)
                .eq("coupon.type", 1)
                .eq("coupon.delete_flag", 0)
                .and(StringUtils.isNotEmpty(couponCode) || StringUtils.isNotEmpty(name), wq -> wq.like(StringUtils.isNotEmpty(couponCode), "coupon.coupon_code", couponCode)
                        .or()
                        .like(StringUtils.isNotEmpty(name), "coupon.name", name))
                .orderByDesc("coupon.created_time");
        if (StringUtils.isNotEmpty(status)) {
            if (status.equals("0")) {
                wrapper.ge("coupon.status", 0);
            } else if (status.equals("2")) {
                wrapper.in("coupon.status", Arrays.asList(0, 2));
            } else {
                wrapper.eq("coupon.status", status);
            }
        }
        IPage<LifeCouponVo> groupPackageList = lifeCouponMapper.getGroupPackageList(iPage, wrapper);
        for (LifeCouponVo record : groupPackageList.getRecords()) {
            record.setStoreGroupInfos(storeGroupInfoMapper.selectList(new LambdaQueryWrapper<StoreGroupInfo>().eq(StoreGroupInfo::getGroupId, record.getId())));
            if (StringUtils.isNotEmpty(record.getUploadedPiclist())) {
                List<String> collect = Arrays.stream(record.getUploadedPiclist().split(","))
                        .map(String::trim)
                        .collect(Collectors.toList());
                List<StoreImg> storeImgs = storeImgMapper.selectList(new LambdaQueryWrapper<StoreImg>().in(StoreImg::getId, collect));
                if (storeImgs != null) {
                    String imgs = storeImgs.stream()
                            .map(StoreImg::getImgUrl)
                            .collect(Collectors.joining(","));
                    record.setImgs(imgs);
                }
            }
        }
        return groupPackageList;
    }

    @Override
    public IPage<LifeCouponVo> getHotelGroupPackageList(Integer pageNum, Integer pageSize, String storeId, String status, String couponCode, String name) {
        IPage<LifeCouponVo> iPage = new Page<>(pageNum, pageSize);
        QueryWrapper<LifeCouponVo> wrapper = new QueryWrapper<>();
        wrapper.eq(StringUtils.isNotEmpty(storeId), "coupon.store_id ", storeId)
                .eq("coupon.type", 2)
                .eq("coupon.delete_flag", 0)
                .and(StringUtils.isNotEmpty(couponCode) || StringUtils.isNotEmpty(name), wq -> wq.like(StringUtils.isNotEmpty(couponCode), "coupon.coupon_code", couponCode)
                        .or()
                        .like(StringUtils.isNotEmpty(name), "coupon.name", name))
                .orderByDesc("coupon.created_time");
        if (StringUtils.isNotEmpty(status)) {
            if (status.equals("0")) {
                wrapper.ge("coupon.status", 0);
            } else if (status.equals("2")) {
                wrapper.in("coupon.status", Arrays.asList(0, 2));
            } else {
                wrapper.eq("coupon.status", status);
            }
        }
        IPage<LifeCouponVo> groupPackageList = lifeCouponMapper.getGroupPackageList(iPage, wrapper);
        for (LifeCouponVo record : groupPackageList.getRecords()) {
            record.setStoreHotelGroupRoomInfos(storeHotelGroupRoomInfoMapper.selectList(new LambdaQueryWrapper<StoreHotelGroupRoomInfo>().eq(StoreHotelGroupRoomInfo::getGroupId, record.getId())));
            if (StringUtils.isNotEmpty(record.getUploadedPiclist())) {
                List<String> collect = Arrays.stream(record.getUploadedPiclist().split(","))
                        .map(String::trim)
                        .collect(Collectors.toList());
                List<StoreImg> storeImgs = storeImgMapper.selectList(new LambdaQueryWrapper<StoreImg>().in(StoreImg::getId, collect));
                if (storeImgs!=null) {
                    String imgs = storeImgs.stream()
                            .map(StoreImg::getImgUrl)
                            .collect(Collectors.joining(","));
                    record.setImgs(imgs);
                }
            }
        }
        return groupPackageList;
    }


    @Override
    public int updateGroupPackageStatus(String id, Integer status) {
        LifeCoupon lifeCoupon = new LifeCoupon();
        lifeCoupon.setId(id);
        lifeCoupon.setStatus(status);
        return lifeCouponMapper.updateById(lifeCoupon);
    }

    @Override
    public Map<String, Object> getGroupPackageDetail(String id, String userId) {
        Map<String, Object> returnMap = new HashMap<>();
        LifeCoupon tuangou = lifeCouponMapper.selectById(id);
        LambdaUpdateWrapper<LifeGroupPackage> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(LifeGroupPackage::getQuanId, tuangou.getId());
        List<LifeGroupPackage> tuangouPackageList = lifeGroupPackageMapper.selectList(updateWrapper);
        Map<String, List<LifeGroupPackage>> groupedPackages = tuangouPackageList.stream().collect(Collectors.groupingBy(LifeGroupPackage::getGroupName));
        List<Map<String, Object>> resultList = new ArrayList<>();
        // 是否收藏了该团购
        LambdaQueryWrapper<LifeCollect> collectQuery = new LambdaQueryWrapper<>();
        LifeCollectIdentityQuery.applyUserSide(collectQuery, LifeCollectIdentityQuery.resolve(userId, typeUtil));
        collectQuery.eq(LifeCollect::getCouponId, id);
        LifeCollect lifeCollect = lifeCollectMapper.selectOne(collectQuery);
        for (Map.Entry<String, List<LifeGroupPackage>> entry : groupedPackages.entrySet()) {
            String groupName = entry.getKey();
            List<LifeGroupPackage> packageList = entry.getValue();
            List<Map<String, Object>> packageListFormatted = new ArrayList<>();
            for (LifeGroupPackage pkg : packageList) {
                Map<String, Object> packageMap = new HashMap<>();
                packageMap.put("dishName", pkg.getDishName());

                packageMap.put("qty", pkg.getQty());
                packageMap.put("price", pkg.getPrice());
                packageMap.put("unit",pkg.getUnit());
                packageListFormatted.add(packageMap);
            }
            Map<String, Object> groupMap = new HashMap<>();
            groupMap.put("groupName", groupName);
            groupMap.put("packageList", packageListFormatted);
            resultList.add(groupMap);
        }

        // 添加商户信息
        StoreInfo storeUser = storeInfoMapper.selectById(tuangou.getStoreId());
        String receiverId = "store_" + storeUser.getStoreTel();


        LifeCouponVo lifeCouponVo = new LifeCouponVo();
        lifeCouponVo.setReceiverId(receiverId);
        lifeCouponVo.setStoreName(storeUser.getStoreName());

        LifeCouponVo tuangouVO = new LifeCouponVo();
        BeanUtils.copyProperties(tuangou,tuangouVO);

        tuangouVO.setIsCollect("0");
        if(!Objects.isNull(lifeCollect)){
            tuangouVO.setIsCollect("1");
        }

        if (StringUtils.isNotEmpty(tuangou.getUploadedPiclist())) {
            List<String> collect = Arrays.stream(tuangou.getUploadedPiclist().split(","))
                    .map(String::trim)
                    .collect(Collectors.toList());
            List<StoreImg> storeImgs = storeImgMapper.selectList(new LambdaQueryWrapper<StoreImg>().in(StoreImg::getId, collect));
            if (storeImgs!=null) {
                String imgs = storeImgs.stream()
                        .map(StoreImg::getImgUrl)
                        .collect(Collectors.joining(","));
                tuangouVO.setImgs(imgs);
            }
        }

        returnMap.put("lianxishangjia", lifeCouponVo);
        returnMap.put("tuangou", tuangouVO);
        returnMap.put("tuangouPackageList", resultList);
        return returnMap;
    }

    @Override
    public Map<String, Object> getGroupHotelPackageDetail(String id, String userId) {
        Map<String, Object> returnMap = new HashMap<>();
        LifeCoupon tuangou = lifeCouponMapper.selectById(id);
        LambdaUpdateWrapper<StoreHotelGroupRoomInfo> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(StoreHotelGroupRoomInfo::getGroupId, tuangou.getId());
        List<StoreHotelGroupRoomInfo> storeHotelGroupRoomInfoList = storeHotelGroupRoomInfoMapper.selectList(updateWrapper);
        // 是否收藏了该团购
        LambdaQueryWrapper<LifeCollect> collectQuery = new LambdaQueryWrapper<>();
        LifeCollectIdentityQuery.applyUserSide(collectQuery, LifeCollectIdentityQuery.resolve(userId, typeUtil));
        collectQuery.eq(LifeCollect::getCouponId, id);
        LifeCollect lifeCollect = lifeCollectMapper.selectOne(collectQuery);

        // 添加商户信息
        StoreInfo storeUser = storeInfoMapper.selectById(tuangou.getStoreId());
        String receiverId = "store_" + storeUser.getStoreTel();

        LifeCouponVo lifeCouponVo = new LifeCouponVo();
        lifeCouponVo.setReceiverId(receiverId);
        lifeCouponVo.setStoreName(storeUser.getStoreName());

        LifeCouponVo tuangouVO = new LifeCouponVo();
        BeanUtils.copyProperties(tuangou,tuangouVO);

        tuangouVO.setIsCollect("0");
        if(!Objects.isNull(lifeCollect)){
            tuangouVO.setIsCollect("1");
        }

        if (StringUtils.isNotEmpty(tuangou.getUploadedPiclist())) {
            List<String> collect = Arrays.stream(tuangou.getUploadedPiclist().split(","))
                    .map(String::trim)
                    .collect(Collectors.toList());
            List<StoreImg> storeImgs = storeImgMapper.selectList(new LambdaQueryWrapper<StoreImg>().in(StoreImg::getId, collect));
            if (storeImgs!=null) {
                String imgs = storeImgs.stream()
                        .map(StoreImg::getImgUrl)
                        .collect(Collectors.joining(","));
                tuangouVO.setImgs(imgs);
            }
        }

        returnMap.put("lianxishangjia", lifeCouponVo);
        returnMap.put("tuangou", tuangouVO);
        returnMap.put("storeHotelGroupRoomInfoList", storeHotelGroupRoomInfoList);
        return returnMap;
    }
}
