package shop.alien.store.service.impl;

import com.alibaba.fastjson2.JSONObject;
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.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;
import org.springframework.stereotype.Service;
import shop.alien.entity.store.*;
import shop.alien.entity.store.dto.LifeDiscountCouponStoreFriendDto;
import shop.alien.entity.store.vo.*;
import shop.alien.mapper.*;
import shop.alien.store.config.WebSocketProcess;
import shop.alien.store.service.LifeDiscountCouponStoreFriendService;
import shop.alien.util.common.constant.DiscountCouponEnum;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 优惠券商户发放好友优惠券关系表	 服务实现类
 * </p>
 *
 * @author ssk
 * @since 2025-02-19
 */
@Service
@RequiredArgsConstructor
public class LifeDiscountCouponStoreFriendServiceImpl extends ServiceImpl<LifeDiscountCouponStoreFriendMapper, LifeDiscountCouponStoreFriend> implements LifeDiscountCouponStoreFriendService {

    final String STORE_PREFIX = "store_";

    private final StoreUserMapper storeUserMapper;

    private final LifeFansMapper lifeFansMapper;

    private final LifeDiscountCouponMapper lifeDiscountCouponMapper;

    private final LifeDiscountCouponStoreFriendMapper lifeDiscountCouponStoreFriendMapper;

    private final LifeDiscountCouponUserMapper lifeDiscountCouponUserMapper;

    private final LifeUserOrderMapper lifeUserOrderMapper;

    private final LifeDiscountCouponStoreFriendSendRecordMapper lifeDiscountCouponStoreFriendSendRecordMapper;

    private final StoreInfoMapper storeInfoMapper;

    private final LifeUserMapper lifeUserMapper;

    private final LifeNoticeMapper lifeNoticeMapper;

    private final LifeDiscountCouponFriendRuleMapper lifeDiscountCouponFriendRuleMapper;

    private final LifeDiscountCouponFriendRuleDetailMapper lifeDiscountCouponFriendRuleDetailMapper;

    private final WebSocketProcess webSocketProcess;

    @Override
    public List<LifeDiscountCouponStoreFriendVo> getFriendCouponList(UserLoginInfo userLoginInfo, String friendUserId) {
        List<LifeDiscountCouponStoreFriendVo> result = new ArrayList<>();
        //登录人是店铺用户这个获取到的是店铺用户id
        String phoneNumber = userLoginInfo.getUserPhone();
        //查询该店铺登录人 fans 表互相关注的列表
        String fansUserPhone = STORE_PREFIX + phoneNumber;
        //查看自己关注的店铺
        LambdaQueryWrapper<LifeFans> queryWrapper = new LambdaQueryWrapper();
        //查看自己关注的id（我作为粉丝）
        queryWrapper.eq(LifeFans::getFansId, fansUserPhone);
        //并且是商户id的相关数据
        queryWrapper.likeRight(LifeFans::getFollowedId, STORE_PREFIX);
        List<LifeFans> lifeFans = lifeFansMapper.selectList(queryWrapper);
        //循环本人关注列表查看也关注我的列表
        for (LifeFans lifeFan : lifeFans) {
            //关注人id
            String followedId = lifeFan.getFollowedId();
            //查询也关注我的信息（他作为粉丝，关注我）
            LifeFans alsoFansMe = lifeFansMapper.selectOne(new LambdaQueryWrapper<LifeFans>().eq(LifeFans::getFansId, followedId).eq(LifeFans::getFollowedId, fansUserPhone));
            //如果有值说明我俩互为朋友
            if (alsoFansMe != null) {
                LifeDiscountCouponStoreFriendVo addLifeDiscountCouponStoreFriendVo = new LifeDiscountCouponStoreFriendVo();
                //拿手机号查询一下
                StoreUser storeUser = storeUserMapper.selectOne(new LambdaQueryWrapper<StoreUser>().eq(StoreUser::getPhone, followedId.substring(STORE_PREFIX.length())));
                //如果不为空，或不相等
                if (StringUtils.isNotEmpty(friendUserId) && !friendUserId.equals(storeUser.getId().toString())) {
                    continue;
                }
                addLifeDiscountCouponStoreFriendVo.setFriendStoreUserName(storeUser.getName());
                addLifeDiscountCouponStoreFriendVo.setFriendStoreUserId(storeUser.getId());
                //查询该店铺的券
                LambdaQueryWrapper<LifeDiscountCoupon> couponQueryWrapper = new LambdaQueryWrapper<>();

                // 获取当前日期
                LocalDate currentDate = LocalDate.now();

                // 截取前缀之后的部分（可用券，开放领取，并且还没结束的券）
                couponQueryWrapper
                        .eq(LifeDiscountCoupon::getStoreId, storeUser.getStoreId())
                        .eq(LifeDiscountCoupon::getGetStatus, DiscountCouponEnum.CAN_GET)
                        .ge(LifeDiscountCoupon::getEndDate, currentDate)
                ;
                List<LifeDiscountCoupon> lifeDiscountCoupons = lifeDiscountCouponMapper.selectList(couponQueryWrapper);
                List<LifeDiscountCouponVo> lifeDiscountCouponVoList = new ArrayList<>();
                for (LifeDiscountCoupon lifeDiscountCoupon : lifeDiscountCoupons) {
                    LifeDiscountCouponVo lifeDiscountCouponVo = new LifeDiscountCouponVo();
                    BeanUtils.copyProperties(lifeDiscountCoupon, lifeDiscountCouponVo);
                    lifeDiscountCouponVo.setCouponId(lifeDiscountCoupon.getId());
                    lifeDiscountCouponVoList.add(lifeDiscountCouponVo);
                }
                addLifeDiscountCouponStoreFriendVo.setFriendStoreCouponList(lifeDiscountCouponVoList);
                result.add(addLifeDiscountCouponStoreFriendVo);
            }
        }

        return result;
    }

    @Override
    /**
     * 为好友设置优惠券，涉及优惠券库存检查、发放记录处理和库存更新等操作。
     *
     * @param userLoginInfo 当前用户的登录信息
     * @param lifeDiscountCouponStoreFriendDto 包含要设置的优惠券信息的 DTO 对象
     * @return 如果所有优惠券都成功设置，返回 true；否则返回 false
     */
    public boolean setFriendCoupon(UserLoginInfo userLoginInfo, LifeDiscountCouponStoreFriendDto lifeDiscountCouponStoreFriendDto) {
        try {
            // 从传入的 DTO 对象中获取要处理的优惠券列表
            List<LifeDiscountCouponStoreFriendDto> coupons = lifeDiscountCouponStoreFriendDto.getCouponIds();
            // 遍历优惠券列表，对每个优惠券进行处理
            for (LifeDiscountCouponStoreFriendDto couponDto : coupons) {
                // 根据优惠券 ID 从数据库中查询对应的优惠券信息
                LifeDiscountCoupon lifeDiscountCoupon = lifeDiscountCouponMapper.selectById(couponDto.getCouponId());
                // 检查优惠券的库存数量是否足够发放，如果库存数小于要发放的数量，则拦截操作并返回 false
                if ((lifeDiscountCoupon.getSingleQty() - couponDto.getSingleQty()) < 0) {
                    return false;
                }
                // 根据优惠券所属店铺 ID 从数据库中查询对应的店铺用户信息
                StoreUser storeUser = storeUserMapper.selectOne(new LambdaQueryWrapper<StoreUser>().eq(StoreUser::getStoreId, lifeDiscountCoupon.getStoreId()));
                // 检查该优惠券是否已经发放给指定的好友，如果发放过则获取发放记录
                LifeDiscountCouponStoreFriend lifeDiscountCouponStoreFriend = lifeDiscountCouponStoreFriendMapper.selectOne(
                        new LambdaQueryWrapper<LifeDiscountCouponStoreFriend>()
                                // 匹配优惠券 ID
                                .eq(LifeDiscountCouponStoreFriend::getCouponId, couponDto.getCouponId())
                                // 匹配店铺用户 ID
                                .eq(LifeDiscountCouponStoreFriend::getStoreUserId, lifeDiscountCouponStoreFriendDto.getFriendStoreUserId())
                                // 匹配好友店铺用户 ID
                                .eq(LifeDiscountCouponStoreFriend::getFriendStoreUserId, userLoginInfo.getUserId())
                );

                if (lifeDiscountCouponStoreFriend == null) {
                    // 如果该优惠券还没有发放给指定的好友，创建一个新的发放记录
                    lifeDiscountCouponStoreFriend = new LifeDiscountCouponStoreFriend();
                    // 将传入的 DTO 对象的属性复制到新的发放记录对象中
                    BeanUtils.copyProperties(lifeDiscountCouponStoreFriendDto, lifeDiscountCouponStoreFriend);
                    // 设置优惠券 ID
                    lifeDiscountCouponStoreFriend.setCouponId(couponDto.getCouponId());
                    // 设置优惠券的过期日期
                    lifeDiscountCouponStoreFriend.setExpirationDate(lifeDiscountCoupon.getExpirationDate());
                    // 设置优惠券的开始日期
                    lifeDiscountCouponStoreFriend.setStartDate(lifeDiscountCoupon.getStartDate());
                    // 设置优惠券的结束日期
                    lifeDiscountCouponStoreFriend.setEndDate(lifeDiscountCoupon.getEndDate());
                    // 设置好友店铺用户 ID
                    lifeDiscountCouponStoreFriend.setFriendStoreUserId(storeUser.getId());
                    // 设置要发放的优惠券数量
                    lifeDiscountCouponStoreFriend.setSingleQty(couponDto.getSingleQty());
                    // 设置店铺用户 ID
                    lifeDiscountCouponStoreFriend.setStoreUserId(lifeDiscountCouponStoreFriendDto.getFriendStoreUserId());
                    // 设置优惠券的发布状态
                    lifeDiscountCouponStoreFriend.setReleaseType(1);
                    // 将新的发放记录插入到数据库中
                    lifeDiscountCouponStoreFriendMapper.insert(lifeDiscountCouponStoreFriend);
                } else {
                    // 如果该优惠券已经发放给指定的好友，增加发放记录中的优惠券数量
                    lifeDiscountCouponStoreFriend.setSingleQty(lifeDiscountCouponStoreFriend.getSingleQty() + couponDto.getSingleQty());
                    // 更新数据库中的发放记录
                    lifeDiscountCouponStoreFriendMapper.updateById(lifeDiscountCouponStoreFriend);
                }
                // 减少优惠券的库存数量
                lifeDiscountCoupon.setSingleQty(lifeDiscountCoupon.getSingleQty() - couponDto.getSingleQty());
                // 更新数据库中的优惠券库存信息
                lifeDiscountCouponMapper.updateById(lifeDiscountCoupon);

                int friendStoreId =  lifeDiscountCouponStoreFriendDto.getFriendStoreUserId();
                LambdaQueryWrapper<StoreUser> storeUserLambdaQueryWrapper = new LambdaQueryWrapper<>();
                storeUserLambdaQueryWrapper.eq(StoreUser::getStoreId, friendStoreId);
                List<StoreUser> storeUserList = storeUserMapper.selectList(storeUserLambdaQueryWrapper);

                if(CollectionUtils.isNotEmpty(storeUserList)){
                    StoreUser friendStoreUser = storeUserList.get(0);
                    String friendPhone = friendStoreUser.getPhone();
                    if(StringUtils.isNotEmpty(friendPhone)){
                        // 获取发送优惠券的店铺名称
                        String storeName = userLoginInfo.getUserName(); // 默认使用用户名
                        // 根据当前登录用户ID查询店铺用户信息
                        StoreUser currentStoreUser = storeUserMapper.selectById(userLoginInfo.getUserId());
                        if (currentStoreUser != null && currentStoreUser.getStoreId() != null) {
                            // 根据storeId查询店铺信息，获取店铺名称
                            StoreInfo currentStoreInfo = storeInfoMapper.selectById(currentStoreUser.getStoreId());
                            if (currentStoreInfo != null && currentStoreInfo.getStoreName() != null) {
                                storeName = currentStoreInfo.getStoreName();
                            }
                        }
                        // 发送好友优惠券通知
                        LifeNotice lifeMessage = new LifeNotice();
                        String text = "您的好友"+storeName+"送了您"+couponDto.getSingleQty()+"张店铺优惠券，快去使用吧！";
                        JSONObject jsonObject = new JSONObject();
                        jsonObject.put("message", text);
                        lifeMessage.setReceiverId("store_"+friendPhone);
                        lifeMessage.setTitle("赠券通知");
                        lifeMessage.setContext(jsonObject.toJSONString());
                        lifeMessage.setNoticeType(1);
                        lifeMessage.setIsRead(0);
                        lifeMessage.setDeleteFlag(0);
                        lifeMessage.setSenderId("system");
                        lifeNoticeMapper.insert(lifeMessage);
                    }
                }
            }
            // 如果所有优惠券都成功处理，返回 true
            return true;
        } catch (BeansException e) {
            // 捕获 Bean 复制过程中可能出现的异常，并打印异常堆栈信息
            e.printStackTrace();
            // 出现异常时返回 false
            return false;
        }
    }

    /**
     * 为当前用户发放店铺为好友设定的可用优惠券。
     *
     * @param lifeDiscountCouponStoreFriendDto 包含店铺ID等信息的DTO对象
     * @return 成功发放的优惠券信息列表
     */
    @Override
    public List<LifeDiscountCouponStoreFriendVo> issueFriendCoupon(LifeDiscountCouponStoreFriendDto lifeDiscountCouponStoreFriendDto) {

        // 用于存储最终成功发放的优惠券信息的列表
        List<LifeDiscountCouponStoreFriendVo> result = new ArrayList<>();

        //判断该订单是否已经发放过好友店铺优惠券
        LifeUserOrder lifeUserOrder = lifeUserOrderMapper.selectById(lifeDiscountCouponStoreFriendDto.getOrderId());
        if (lifeUserOrder.getSendDiscountCouponFlag() == 1) {
            throw new RuntimeException("已发放优惠券");
        }

        //送券规则
        List<Integer> couponList = new ArrayList<>();
        LambdaQueryWrapper<LifeDiscountCouponFriendRule> ruleLambdaQueryWrapper = new LambdaQueryWrapper<>();
        ruleLambdaQueryWrapper.eq(LifeDiscountCouponFriendRule::getStoreId, lifeUserOrder.getStoreId())
                .eq(LifeDiscountCouponFriendRule::getDeleteFlag, 0);
        List<LifeDiscountCouponFriendRule> lifeDiscountCouponFriendRules = lifeDiscountCouponFriendRuleMapper.selectList(ruleLambdaQueryWrapper);
        lifeDiscountCouponFriendRules = lifeDiscountCouponFriendRules.stream().filter(i -> i.getMoneyLow().compareTo(new BigDecimal(lifeUserOrder.getFinalPrice())) <= 0 && i.getMoneyHigh().compareTo(new BigDecimal(lifeUserOrder.getFinalPrice())) >= 0).collect(Collectors.toList());
        if (ObjectUtils.isNotEmpty(lifeDiscountCouponFriendRules)) {
            LambdaQueryWrapper<LifeDiscountCouponFriendRuleDetail> detailLambdaQueryWrapper = new LambdaQueryWrapper<>();
            detailLambdaQueryWrapper.in(LifeDiscountCouponFriendRuleDetail::getRuleId, lifeDiscountCouponFriendRules.stream().map(LifeDiscountCouponFriendRule::getId).collect(Collectors.toList()));
            List<LifeDiscountCouponFriendRuleDetail> lifeDiscountCouponFriendRuleDetails = lifeDiscountCouponFriendRuleDetailMapper.selectList(detailLambdaQueryWrapper);
            couponList = lifeDiscountCouponFriendRuleDetails.stream().map(LifeDiscountCouponFriendRuleDetail::getCouponId).collect(Collectors.toList());
        }


        lifeUserOrder.setSendDiscountCouponFlag(1);
        lifeUserOrderMapper.updateById(lifeUserOrder);

        //有符合规则的优惠券
        if (ObjectUtils.isNotEmpty(couponList) && !couponList.isEmpty()) {
            // 获取当前消费用户的ID
            int userId = Integer.parseInt(lifeUserOrder.getUserId());
            LifeUser lifeUser = lifeUserMapper.selectById(userId);
            // 从传入的DTO对象中获取店铺ID
            StoreUser storeUser =
                    storeUserMapper.selectOne(new LambdaQueryWrapper<StoreUser>().eq(StoreUser::getStoreId, lifeUserOrder.getStoreId()));
            Integer storeUserId = storeUser.getId();
            Integer storeId = storeUser.getStoreId();
            StoreInfo storeInfo = storeInfoMapper.selectById(storeUser.getStoreId());

            // 根据店铺ID从数据库中查询该店铺为好友设定的所有优惠券信息
            List<LifeDiscountCouponStoreFriend> lifeDiscountCouponStoreFriends = lifeDiscountCouponStoreFriendMapper.selectList(
                    // 使用LambdaQueryWrapper构建查询条件，筛选出店铺ID等于指定店铺ID的优惠券记录,并且发布状态为已发布
                    new LambdaQueryWrapper<LifeDiscountCouponStoreFriend>().eq(LifeDiscountCouponStoreFriend::getStoreUserId, storeId)
                            .eq(LifeDiscountCouponStoreFriend::getReleaseType, 1)
                            .in(LifeDiscountCouponStoreFriend::getCouponId, couponList));

            // 获取当前日期，用于后续判断优惠券是否在有效期内
            LocalDate currentDate = LocalDate.now();
            if (!lifeDiscountCouponStoreFriends.isEmpty()) {
                // 遍历该店铺为好友设定的所有优惠券信息
                for (LifeDiscountCouponStoreFriend coupon : lifeDiscountCouponStoreFriends) {
                    // 创建一个Lambda查询包装器，用于构建查询优惠券的条件
                    LambdaQueryWrapper<LifeDiscountCoupon> queryWrapper = new LambdaQueryWrapper<>();
                    // 设置查询条件：优惠券的领取状态为可领取
                    queryWrapper.eq(LifeDiscountCoupon::getGetStatus, DiscountCouponEnum.CAN_GET.getValue());
                    // 设置查询条件：优惠券的ID等于当前遍历到的优惠券ID
                    queryWrapper.eq(LifeDiscountCoupon::getId, coupon.getCouponId());
                    // 设置查询条件：优惠券的结束日期大于等于当前日期，即优惠券在有效期内
                    queryWrapper.ge(LifeDiscountCoupon::getValidDate, currentDate);
                    // 设置查询条件：优惠券还有库存
                    queryWrapper.gt(LifeDiscountCoupon::getSingleQty, 0);

                    // 根据上述查询条件从数据库中查询符合条件的优惠券信息
                    LifeDiscountCoupon lifeDiscountCoupon = lifeDiscountCouponMapper.selectOne(queryWrapper);

                    // 如果查询到符合条件的优惠券，说明该优惠券可领
                    if (lifeDiscountCoupon != null) {
                        // 设定本次领取优惠券的数量，这里固定为1张
                        Integer receiveQuantity = 1;

                        // 循环领取优惠券，根据设定的领取数量进行多次领取操作
                        for (int i = 0; i < receiveQuantity; i++) {
                            // 创建一个新的用户优惠券记录对象
                            LifeDiscountCouponUser lifeDiscountCouponUser = new LifeDiscountCouponUser();
                            // 设置该优惠券记录的优惠券ID
                            lifeDiscountCouponUser.setCouponId(coupon.getCouponId());
                            // 设置该优惠券记录的用户ID为当前用户ID
                            lifeDiscountCouponUser.setUserId(userId);
                            // 设置该优惠券的领取时间为当前时间
                            lifeDiscountCouponUser.setReceiveTime(new Date());
                            // 设置该优惠券的过期时间为优惠券本身的结束日期
                            lifeDiscountCouponUser.setExpirationTime(lifeDiscountCoupon.getValidDate());
                            // 设置该优惠券的状态为待使用
                            lifeDiscountCouponUser.setStatus(Integer.parseInt(DiscountCouponEnum.WAITING_USED.getValue()));
                            // 将该用户优惠券记录插入到数据库中
                            lifeDiscountCouponUserMapper.insert(lifeDiscountCouponUser);
                        }

                        // 削减该优惠券的库存，根据领取数量减少库存
                        coupon.setSingleQty(coupon.getSingleQty() - receiveQuantity);
                        // 更新数据库中该优惠券的库存信息
                        lifeDiscountCouponStoreFriendMapper.updateById(coupon);

                        // 创建一个用于存储优惠券信息的VO对象
                        LifeDiscountCouponStoreFriendVo lifeDiscountCouponStoreFriendVo = new LifeDiscountCouponStoreFriendVo();
                        // 将优惠券信息复制到VO对象中
                        BeanUtils.copyProperties(coupon, lifeDiscountCouponStoreFriendVo);
                        // 将该VO对象添加到最终结果列表中
                        result.add(lifeDiscountCouponStoreFriendVo);
                    }
                }

                //存储发放日志
                LifeDiscountCouponStoreFriendSendRecord lifeDiscountCouponStoreFriendSendRecord = new LifeDiscountCouponStoreFriendSendRecord();
                //存入门店id
                lifeDiscountCouponStoreFriendSendRecord.setStoreId(Integer.parseInt(lifeUserOrder.getStoreId()));
                //存入接收人id
                lifeDiscountCouponStoreFriendSendRecord.setUserId(userId);
                //存入发放人id
                lifeDiscountCouponStoreFriendSendRecord.setStoreUserId(storeUserId);
                //存入订单id
                lifeDiscountCouponStoreFriendSendRecord.setOrderId(Integer.parseInt(lifeUserOrder.getId()));
                //存入优惠券ids
                String[] couponIds = result.stream()
                        .map(LifeDiscountCouponStoreFriendVo::getCouponId)
                        .map(String::valueOf)  // 将 Integer 转换为 String
                        .toArray(String[]::new);

                String join = String.join(",", couponIds);
                lifeDiscountCouponStoreFriendSendRecord.setDiscountCouponIds(join);
                lifeDiscountCouponStoreFriendSendRecordMapper.insert(lifeDiscountCouponStoreFriendSendRecord);

                //发送公告消息
                LifeNotice lifeNotice = new LifeNotice();
                //存入发送人
                lifeNotice.setSenderId("system");
                //存入接收人
                lifeNotice.setReceiverId("user_" + lifeUser.getUserPhone());
                //存入信息
                String text = storeInfo.getStoreName() + "赠送了您他的好友店铺优惠券，快去我的券包查看吧~";
                com.alibaba.fastjson2.JSONObject jsonObject = new com.alibaba.fastjson2.JSONObject();
                jsonObject.put("message", text);
                lifeNotice.setContext(jsonObject.toJSONString());
                //存入类型
                lifeNotice.setNoticeType(1);
                lifeNotice.setTitle("赠劵通知");
                lifeNoticeMapper.insert(lifeNotice);

            }
        }




        // 返回成功发放的优惠券信息列表
        return result;
    }

    @Override
    public List<LifeDiscountCouponStoreFriendVo> getSendCoupons(LifeDiscountCouponStoreFriendDto lifeDiscountCouponStoreFriendDto) {
        List<LifeDiscountCouponStoreFriendVo> result = new ArrayList<>();
        Integer orderId = lifeDiscountCouponStoreFriendDto.getOrderId();
        //根据订单id获取发放记录
        LifeDiscountCouponStoreFriendSendRecord lifeDiscountCouponStoreFriendSendRecord =
                lifeDiscountCouponStoreFriendSendRecordMapper.selectOne(
                        new LambdaQueryWrapper<LifeDiscountCouponStoreFriendSendRecord>()
                                .eq(LifeDiscountCouponStoreFriendSendRecord::getOrderId, orderId));
        //如果没查出信息，说明没发
        if (lifeDiscountCouponStoreFriendSendRecord != null) {
            //获取发放的优惠券ids
            String discountCouponIds = lifeDiscountCouponStoreFriendSendRecord.getDiscountCouponIds();
            List<String> list = Arrays.asList(discountCouponIds.split(","));
            for (String couponId : list) {
                LifeDiscountCouponStoreFriendVo lifeDiscountCouponStoreFriendVo = new LifeDiscountCouponStoreFriendVo();
                lifeDiscountCouponStoreFriendVo.setCouponId(Integer.parseInt(couponId));
                result.add(lifeDiscountCouponStoreFriendVo);
            }
        }
        return result;
    }

    @Override
    public int releaseAndCancelFriendStoreCoupon(String giveCouponId, String releaseType) {
        LambdaUpdateWrapper<LifeDiscountCouponStoreFriend> updateWrapper = new LambdaUpdateWrapper<>();
        // 设置更新条件，根据优惠券的 ID 进行更新
        updateWrapper.eq(LifeDiscountCouponStoreFriend::getId, giveCouponId)
                // 设置要更新的字段，将优惠券的状态更新为 3
                .set(LifeDiscountCouponStoreFriend::getReleaseType, releaseType);
        return lifeDiscountCouponStoreFriendMapper.update(null, updateWrapper);
    }

    @Override
    public LifeDiscountCouponFriendRuleVo saveFriendCouponRule(LifeDiscountCouponFriendRule lifeDiscountCouponFriendRule) {
        if (ObjectUtils.isNotEmpty(lifeDiscountCouponFriendRule.getId())) {
            List<LifeDiscountCouponFriendRuleDetail> details = lifeDiscountCouponFriendRule.getDetails();
            lifeDiscountCouponFriendRuleDetailMapper.delete(new LambdaQueryWrapper<LifeDiscountCouponFriendRuleDetail>().eq(LifeDiscountCouponFriendRuleDetail::getRuleId, lifeDiscountCouponFriendRule.getId()));
            for (LifeDiscountCouponFriendRuleDetail detail : details) {
                detail.setRuleId(lifeDiscountCouponFriendRule.getId());
                detail.setStoreId(lifeDiscountCouponFriendRule.getStoreId());
            }
            lifeDiscountCouponFriendRuleDetailMapper.insertList(details);
            lifeDiscountCouponFriendRuleMapper.updateById(lifeDiscountCouponFriendRule);
        }else {
            lifeDiscountCouponFriendRuleMapper.insert(lifeDiscountCouponFriendRule);
            if (ObjectUtils.isNotEmpty(lifeDiscountCouponFriendRule.getDetails())) {
                lifeDiscountCouponFriendRule.getDetails().forEach(detail -> detail.setRuleId(lifeDiscountCouponFriendRule.getId()));
                lifeDiscountCouponFriendRuleDetailMapper.insertList(lifeDiscountCouponFriendRule.getDetails());
            }
        }
        return null;
    }

    @Override
    public void delFriendCouponRule(String id) {
        lifeDiscountCouponFriendRuleDetailMapper.delete(new LambdaQueryWrapper<LifeDiscountCouponFriendRuleDetail>().eq(LifeDiscountCouponFriendRuleDetail::getRuleId, id));
        lifeDiscountCouponFriendRuleMapper.deleteById(id);
    }

    /**
     * 获取好友送的优惠券列表
     *
     * @param storeId 当前登录店铺id
     * @param friendStoreUserId 选中好友店铺用户id
     * @return 领取的优惠券列表
     */
    @Override
    public List<LifeDiscountCouponFriendRuleDetailVo> getReceivedFriendCouponList(String storeId,String friendStoreUserId) {
        QueryWrapper<LifeDiscountCouponFriendRuleDetailVo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("ldcsf.store_user_id", storeId);
        queryWrapper.eq("ldcsf.delete_flag", 0);
        queryWrapper.eq("ldcsf.release_type", 1);
        //查询送过优惠券的店铺
        if (StringUtils.isEmpty(friendStoreUserId)) {
            queryWrapper.groupBy("ldcsf.friend_store_user_id").orderByDesc("couponNum");
        }
        //查询选中店铺送的优惠券
        else {
            queryWrapper.eq("ldcsf.friend_store_user_id", friendStoreUserId).groupBy("ldcsf.coupon_id").orderByDesc("couponNum");
        }
        return lifeDiscountCouponFriendRuleDetailMapper.getReceivedFriendCouponList(queryWrapper);
    }

    @Override
    public List<LifeDiscountCouponFriendRuleVo> getRuleList(String storeId, String acName, String status) {
        List<LifeDiscountCouponFriendRuleVo> ruleList = lifeDiscountCouponFriendRuleDetailMapper.getRuleList(storeId);
        if (ObjectUtils.isNotEmpty(ruleList)) {
            ruleList.forEach(i -> i.setStatus(i.getEndDate().after(new Date()) ? "0" : "1"));
        }
        if (StringUtils.isNotEmpty(acName)) {
            ruleList = ruleList.stream().filter(i -> i.getAcName().contains(acName)).collect(Collectors.toList());
        }
        if (StringUtils.isNotEmpty(status)) {
            ruleList = ruleList.stream().filter(i -> i.getStatus().equals(status)).collect(Collectors.toList());
        }
        return ruleList;
    }

    @Override
    public LifeDiscountCouponFriendRuleVo getRuleById(String id) {
        LifeDiscountCouponFriendRule lifeDiscountCouponFriendRule = lifeDiscountCouponFriendRuleMapper.selectById(id);
        LifeDiscountCouponFriendRuleVo ruleVo = new LifeDiscountCouponFriendRuleVo();
        BeanUtils.copyProperties(lifeDiscountCouponFriendRule, ruleVo);
        if (ObjectUtils.isNotEmpty(lifeDiscountCouponFriendRule)) {
            List<LifeDiscountCouponFriendRuleDetailVo> lifeDiscountCouponFriendRuleDetails = lifeDiscountCouponFriendRuleDetailMapper.getDetailList(lifeDiscountCouponFriendRule.getId().toString());
            ruleVo.setLifeDiscountCouponFriendRuleDetailVos(lifeDiscountCouponFriendRuleDetails);
        }
        return ruleVo;
    }

    @Override
    public List<LifeDiscountCouponFriendRuleVo> getReceivedSendFriendCouponList(String storeUserId, String friendStoreUserId,String storeName) {
        QueryWrapper<LifeDiscountCouponFriendRuleVo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(StringUtils.isNotEmpty(storeUserId),"ldcsf.store_user_id", storeUserId)
                .eq(StringUtils.isNotEmpty(friendStoreUserId),"ldcsf.friend_store_user_id", friendStoreUserId)
                .like(StringUtils.isNotEmpty(storeName),"si.store_name", storeName);
        if (StringUtils.isNotEmpty(storeUserId)) {
            return lifeDiscountCouponStoreFriendMapper.getReceivedSendFriendCouponList(queryWrapper);
        }
        if (StringUtils.isNotEmpty(friendStoreUserId)) {
            return lifeDiscountCouponStoreFriendMapper.getReceivedSendFriendCouponListwzhy(queryWrapper);
        }
        else {
            return new ArrayList<>();
        }
    }
}
