package com.czg.service.market.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.TypeReference;
import com.czg.account.entity.ShopInfo;
import com.czg.account.entity.ShopUser;
import com.czg.account.service.ShopInfoService;
import com.czg.account.service.ShopUserService;
import com.czg.account.vo.ShopInfoCouponVO;
import com.czg.account.vo.UserCouponVo;
import com.czg.constant.MarketConstants;
import com.czg.exception.CzgException;
import com.czg.market.dto.MkShopCouponGiftDTO;
import com.czg.market.dto.ShopCouponDTO;
import com.czg.market.entity.ChatCoupon;
import com.czg.market.entity.MkShopCouponRecord;
import com.czg.market.entity.ShopCoupon;
import com.czg.market.service.*;
import com.czg.market.vo.ShopCouponPopUp;
import com.czg.market.vo.UserCouponVO;
import com.czg.order.entity.OrderInfo;
import com.czg.product.entity.Product;
import com.czg.product.service.ProductService;
import com.czg.sa.StpKit;
import com.czg.service.market.enums.OrderStatusEnums;
import com.czg.service.market.mapper.ChatCouponMapper;
import com.czg.service.market.mapper.MkShopCouponRecordMapper;
import com.czg.service.market.mapper.ShopCouponMapper;
import com.czg.utils.AssertUtil;
import com.czg.utils.CzgStrUtils;
import com.czg.utils.PageUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.scheduling.annotation.Async;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 优惠券信息表 服务层实现。
 *
 * @author ww
 * @since 2025-09-11
 */
@Slf4j
@DubboService
public class ShopCouponServiceImpl extends ServiceImpl<ShopCouponMapper, ShopCoupon> implements ShopCouponService {
    @Resource
    private MkCouponGiftService couponGiftService;
    @Resource
    private MkShopCouponRecordService recordService;
    @Resource
    private MkShopCouponRecordMapper recordMapper;
    @DubboReference
    private ShopInfoService shopInfoService;
    @DubboReference
    private ShopUserService shopUserService;
    @DubboReference
    private ProductService productService;
    @Resource
    private OrderInfoService orderInfoService;
    @Resource
    private ChatCouponMapper chatCouponMapper;

    @Override
    public Page<ShopCouponDTO> chatCoupon(Long shopId, String search) {
        QueryWrapper queryWrapper = new QueryWrapper();
//        queryWrapper.select("id as id,title as name");
        queryWrapper.eq(ShopCoupon::getShopId, shopId)
                .eq(ShopCoupon::getGetUserType, "all")
                .eq(ShopCoupon::getIsDel, 0)
                .eq(ShopCoupon::getStatus, 1)
                .like(ShopCoupon::getTitle, CzgStrUtils.getStrOrNull(search))
                .orderBy(ShopCoupon::getCreateTime).desc();
        queryWrapper.and(q -> {
            q.eq(ShopCoupon::getValidType, "fixed").or(q1 -> {
                q1.eq(ShopCoupon::getValidType, "custom").gt(ShopCoupon::getValidEndTime, LocalDateTime.now());
            });
        });
        Page<ShopCouponDTO> list = pageAs(PageUtil.buildPage(), queryWrapper, ShopCouponDTO.class);
        return list;
    }

    @Override
    public Page<ShopCouponDTO> getCouponPage(ShopCouponDTO param) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq(ShopCoupon::getShopId, param.getShopId())
                .eq(ShopCoupon::getCouponType, param.getCouponType())
                .like(ShopCoupon::getTitle, CzgStrUtils.getStrOrNull(param.getTitle()))
                .eq(ShopCoupon::getIsDel, 0)
                .orderBy(ShopCoupon::getCreateTime).desc();
        return pageAs(PageUtil.buildPage(), queryWrapper, ShopCouponDTO.class);
    }

    @Override
    public List<ShopCouponPopUp> getPopUp(Long shopId, Long userId, String getMode) {
        ShopUser shopUser = shopUserService.getShopUserInfo(shopId, userId);
        AssertUtil.isNull(shopUser, "用户不存在");
        List<ShopCouponPopUp> result = new ArrayList<>();
        List<ShopCoupon> coupons = list(new QueryWrapper()
                .eq(ShopCoupon::getShopId, StpKit.USER.getShopId())
                .eq(ShopCoupon::getGetType, "yes")
                .eq(ShopCoupon::getStatus, 1)
                .eq(ShopCoupon::getIsDel, 0)
                .like(ShopCoupon::getGetMode, getMode)
        );

        for (ShopCoupon coupon : coupons) {
            if ("custom".equals(coupon.getValidType()) && coupon.getValidEndTime() != null && coupon.getValidEndTime().isBefore(LocalDateTime.now())) {
                continue;
            }
            if (coupon.getGiveNum() != MarketConstants.Num.NOT_LIMIT && coupon.getLeftNum() <= 0) {
                continue;
            }
            boolean isNotNewUser = true;
            if (!"all".equals(coupon.getGetUserType())) {
                if ("new".equals(coupon.getGetUserType())) {
                    isNotNewUser = false;
                    boolean exists = orderInfoService.exists(new QueryWrapper().eq(OrderInfo::getUserId, userId)
                            .eq(OrderInfo::getShopId, shopId).eq(OrderInfo::getStatus, OrderStatusEnums.DONE.getCode()));
                    if (exists) {
                        continue;
                    }
                    boolean exists1 = recordService.exists(new QueryWrapper().eq(MkShopCouponRecord::getCouponSyncId, coupon.getSyncId()));
                    if (exists1) {
                        continue;
                    }
                } else if ("vip".equals(coupon.getGetUserType()) && shopUser.getIsVip() != 1) {
                    continue;
                }
            }
            if (isNotNewUser && coupon.getGetLimit() != MarketConstants.Num.NOT_LIMIT) {
                if (coupon.getSyncId() != null) {
                    long count = recordService.count(new QueryWrapper()
                            .eq(MkShopCouponRecord::getUserId, userId)
                            .eq(MkShopCouponRecord::getCouponSyncId, coupon.getSyncId()));
                    if (count >= coupon.getGetLimit()) {
                        continue;
                    }
                } else {
                    long count = recordService.count(new QueryWrapper()
                            .eq(MkShopCouponRecord::getUserId, userId)
                            .eq(MkShopCouponRecord::getCouponId, coupon.getId()));
                    if (count >= coupon.getGetLimit()) {
                        continue;
                    }
                }
            }
            result.add(BeanUtil.copyProperties(coupon, ShopCouponPopUp.class));
        }
        return result;
    }

    @Override
    public void receivePopUp(Long shopId, Long userId, String getMode) {
        ShopUser shopUser = null;
        List<ShopCouponPopUp> popUps = getPopUp(shopId, userId, getMode);
//        if ("home".equals(getMode)) {
//            getMode = "首页";
//        } else if ("eat".equals(getMode)) {
//            getMode = "用餐";
//        } else if ("order".equals(getMode)) {
//            getMode = "订单";
//        }
        for (ShopCouponPopUp popUp : popUps) {
            MkShopCouponGiftDTO giftDTO = new MkShopCouponGiftDTO();
            giftDTO.setShopId(shopId);
            if (shopUser == null) {
                shopUser = shopUserService.getShopUserInfo(shopId, userId);
            }
            giftDTO.setShopUserId(shopUser.getId());
            giftDTO.setCouponId(popUp.getId());
            giftDTO.setSourceId(-1L);
            giftDTO.setSource("用户弹窗领取");
//            giftDTO.setSource(getMode + "弹窗领取");
            recordService.receiveCoupon(giftDTO, 1, true);
        }
    }

    @Override
    public ShopCouponDTO getCouponById(Long id) {
        AssertUtil.isNull(id, "优惠券ID不能为空");
        return getOneAs(new QueryWrapper().eq(ShopCoupon::getId, id), ShopCouponDTO.class);
    }

    @Override
    public void addCoupon(ShopCouponDTO param) {
        ShopCoupon coupon = BeanUtil.toBean(param, ShopCoupon.class);
        if (coupon.getValidEndTime() != null) {
            coupon.setValidEndTime(coupon.getValidEndTime().with(LocalTime.MAX));
        }
        save(coupon);
        param.setId(coupon.getId());
    }

    @Override
    public void updateCouponById(ShopCouponDTO param) {
        ShopCoupon tbShopCoupon = getById(param.getId());
        if (tbShopCoupon.getGiveNum() == MarketConstants.Num.NOT_LIMIT) {
            if (param.getGiveNum() != MarketConstants.Num.NOT_LIMIT) {
                if (param.getGiveNum() < tbShopCoupon.getGiftNum()) {
                    throw new CzgException("修改失败 总发放数量必须大于已发放数量");
                } else {
                    param.setLeftNum(param.getGiveNum() - tbShopCoupon.getGiftNum());
                }
            }
        } else {
            if (param.getGiveNum() == MarketConstants.Num.NOT_LIMIT) {
                param.setLeftNum(MarketConstants.Num.NOT_LIMIT);
            } else {
                if (param.getGiveNum() < tbShopCoupon.getGiftNum()) {
                    throw new CzgException("修改失败 总发放数量必须大于已发放数量");
                } else {
                    param.setLeftNum(param.getGiveNum() - tbShopCoupon.getGiftNum());
                }
            }
        }
        ShopCoupon coupon = BeanUtil.toBean(param, ShopCoupon.class);
        updateById(coupon, true);
    }

    @Override
    public void deleteCoupon(Long id) {
        AssertUtil.isNull(id, "优惠券ID不能为空");
        updateById(new ShopCoupon().setIsDel(1).setId(id), true);
        couponGiftService.deleteJoinCouponGift(id, 3);
    }

    @Override
    public Page<UserCouponVO> find(Long userId, String name, Long shopId, Integer status) {
        Page<Object> page = PageUtil.buildPage();
        Long mainShopId = null;
        if (shopId != null) {
            mainShopId = shopInfoService.getMainIdByShopId(shopId);
        }
        List<Long> shopUserIds = shopUserService.listAs(new QueryWrapper().eq(ShopUser::getUserId, userId)
                .eq(ShopUser::getMainShopId, mainShopId)
                .select(ShopUser::getId), Long.class);

        if (CollectionUtil.isNotEmpty(shopUserIds)) {
            PageHelper.startPage(Math.toIntExact(page.getPageNumber()), Math.toIntExact(page.getPageSize()));
            List<UserCouponVO> coupons = recordService.findByUser(name, shopUserIds, status, shopId);
            for (UserCouponVO coupon : coupons) {
                int maxShow = 5;
                if (StrUtil.isNotBlank(coupon.getFoods())) {
                    List<String> productNames = productService.listAs(new QueryWrapper().select(Product::getName)
                            .in(Product::getId, Arrays.stream(coupon.getFoods().split(",")).map(Long::parseLong).toList())
                            .eq(Product::getIsDel, 0), String.class);
                    if (CollUtil.isNotEmpty(productNames)) {
                        StringBuilder result = new StringBuilder();
                        for (int i = 0; i < productNames.size(); i++) {
                            if (i > 0) {
                                result.append(",");
                            }
                            result.append(productNames.get(i));
                            if (i == maxShow - 1 && i != productNames.size() - 1) {
                                result.append("...");
                                break;
                            }
                        }
                        coupon.setFoods(result.toString());
                    }
                } else {
                    coupon.setFoods("全部商品");
                }
                if ("only".equals(coupon.getUseShopType())) {
                    ShopInfo shopInfo = shopInfoService.getById(coupon.getShopId());
                    coupon.setUseShops("仅本店:" + shopInfo.getShopName());
                } else if ("all".equals(coupon.getUseShopType())) {
                    coupon.setUseShops("所有门店");
                } else if ("custom".equals(coupon.getUseShopType())) {
                    if (StrUtil.isNotBlank(coupon.getUseShops())) {
                        coupon.setUseShops(coupon.getUseShops() + "," + coupon.getShopId());
                        QueryWrapper queryWrapper = QueryWrapper.create().select(ShopInfo::getShopName)
                                .in(ShopInfo::getId, Arrays.stream(coupon.getUseShops().split(",")).map(Long::parseLong).toList())
                                .eq(ShopInfo::getStatus, 1);
                        List<String> shopNames = shopInfoService.listAs(queryWrapper, String.class);
                        if (CollUtil.isNotEmpty(shopNames)) {
                            StringBuilder result = new StringBuilder();
                            for (int i = 0; i < shopNames.size(); i++) {
                                if (i > 0) {
                                    result.append(",");
                                }
                                result.append(shopNames.get(i));
                                if (i == maxShow - 1 && i != shopNames.size() - 1) {
                                    result.append("...");
                                    break;
                                }
                            }
                            coupon.setUseShops(result.toString());
                        }
                    }
                }
            }
            return PageUtil.convert(new PageInfo<>(coupons));
        }
        return PageUtil.emptyPage();
    }

    @Override
    public List<UserCouponVo> findCoupon(Long shopId, Long shopUserId, Integer type, Integer isFood) {
        List<UserCouponVo> tbUserCouponVos = recordService.queryByVipIdAndShopId(shopId, shopUserId, type, isFood);
        if (CollectionUtil.isNotEmpty(tbUserCouponVos)) {
            String week = CzgStrUtils.getStrWeek();
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm:ss");

            //券id 券使用描述
            Map<Long, JSONObject> coupons = new HashMap<>();
            for (UserCouponVo tbUserCouponVo : tbUserCouponVos) {
                //填充优惠券使用描述 每人每日使用限量校验
                if (!coupons.containsKey(tbUserCouponVo.getCouponId())) {
                    setCouponInfo(coupons, tbUserCouponVo, week, formatter, shopUserId);
                }
                //填充使用门店
                setUseShop(tbUserCouponVo);
                //填充使用/门槛商品
                setFoods(tbUserCouponVo);
                JSONObject couponJson = coupons.get(tbUserCouponVo.getCouponId());
                tbUserCouponVo.setUse(couponJson.getBoolean("isUse"));
                tbUserCouponVo.setUseRestrictions(couponJson.getString("useRestrictions"));
                tbUserCouponVo.setNoUseRestrictions(couponJson.getString("noUseRestrictions"));
            }
            tbUserCouponVos.sort(Comparator.comparing(UserCouponVo::isUse).reversed());
            return tbUserCouponVos;
        }
        return null;
    }

    @Override
    @Async
    public void use(List<Long> ids, Long shopUserId, Long orderId) {
        List<MkShopCouponRecord> records = recordService.listByIds(ids);
        if (records.isEmpty()) {
            log.error("优惠券使用失败，订单Id:{}", orderId);
        }
        Map<Long, Long> chatCouponIdCountMap = records.stream()
                .filter(record -> "群聊发放".equals(record.getSource()))
                .collect(Collectors.groupingBy(MkShopCouponRecord::getSourceId,
                        Collectors.counting()
                ));
        chatCouponIdCountMap.forEach((chatCouponId, count) -> {
            ChatCoupon chatCoupon = chatCouponMapper.selectOneById(chatCouponId);
            if (chatCoupon == null) {
                return;
            }
            ChatCoupon upChatCoupon = new ChatCoupon();
            upChatCoupon.setId(chatCoupon.getId());
            upChatCoupon.setUseNum(chatCoupon.getUseNum() + count.intValue());
            chatCouponMapper.update(upChatCoupon);
        });


        // 使用流来统计 couponId 出现的次数
        Map<Long, Long> couponIdCountMap = records.stream()
                .collect(Collectors.groupingBy(MkShopCouponRecord::getCouponId,
                        Collectors.counting()
                ));
        couponIdCountMap.forEach((couponId, count) -> {
            ShopCoupon tbShopCoupon = getById(couponId);
            tbShopCoupon.setUseNum(tbShopCoupon.getUseNum() + count.intValue());
            ShopCoupon coupon1 = new ShopCoupon();
            coupon1.setUseNum(tbShopCoupon.getUseNum());

            QueryWrapper recordQueryWrapper = new QueryWrapper();
            if (tbShopCoupon.getSyncId() != null) {
                recordQueryWrapper.and(q -> {
                    q.eq(ShopCoupon::getId, tbShopCoupon.getId()).or(q1 -> {
                        q1.eq(ShopCoupon::getSyncId, tbShopCoupon.getSyncId());
                    });
                });
            } else {
                recordQueryWrapper.and(q -> {
                    q.eq(ShopCoupon::getId, tbShopCoupon.getId()).or(q1 -> {
                        q1.eq(ShopCoupon::getSyncId, tbShopCoupon.getId());
                    });
                });
            }
            update(coupon1, recordQueryWrapper);
        });
        recordService.updateChain()
                .set(MkShopCouponRecord::getStatus, 1)
                .set(MkShopCouponRecord::getTargetId, orderId)
                .set(MkShopCouponRecord::getUseTime, LocalDateTime.now())
                .eq(MkShopCouponRecord::getShopUserId, shopUserId)
                .in(MkShopCouponRecord::getId, ids).update();
    }

    /**
     * 退还券
     */
    @Override
    public Boolean refund(Long orderId, Long shopUserId) {
        return recordService.updateChain()
                .set(MkShopCouponRecord::getStatus, 0)
                .eq(MkShopCouponRecord::getShopUserId, shopUserId)
                .eq(MkShopCouponRecord::getTargetId, orderId)
                .update();
    }

    @Override
    public List<ShopInfoCouponVO> getShopByCouponRecord(Long shopId, Long shopUserId) {
        List<ShopInfoCouponVO> originalList = recordMapper.getShopByCouponRecord(shopUserId);
        // 2. 若shopId为空，直接返回原集合
        if (shopId == null) {
            return originalList;
        }

        // 3. 若shopId不为空，筛选目标元素并重组列表
        List<ShopInfoCouponVO> resultList = new ArrayList<>();
        ShopInfoCouponVO targetShop = null;

        // 遍历原始集合，找到目标元素
        for (ShopInfoCouponVO shopVO : originalList) {
            if (Objects.equals(shopVO.getShopId(), shopId)) {
                targetShop = shopVO;
                break;
            }
        }


        if (targetShop != null) {
            resultList.add(targetShop);
            // 再添加其余非目标元素
            for (ShopInfoCouponVO shopVO : originalList) {
                if (!Objects.equals(shopVO.getShopId(), shopId)) {
                    resultList.add(shopVO);
                }
            }
        } else {
            resultList = originalList;
        }

        return resultList;
    }


    /**
     * 设置优惠券使用门店
     */
    private void setUseShop(UserCouponVo tbUserCouponVo) {
        int maxShow = 5;
        if ("only".equals(tbUserCouponVo.getUseShopType())) {
            ShopInfo shopInfo = shopInfoService.getById(tbUserCouponVo.getShopId());
            tbUserCouponVo.setUseShops("仅本店:" + shopInfo.getShopName());
        } else if ("all".equals(tbUserCouponVo.getUseShopType())) {
            tbUserCouponVo.setUseShops("所有门店");
        } else if ("custom".equals(tbUserCouponVo.getUseShopType())) {
            if (StrUtil.isNotBlank(tbUserCouponVo.getUseShops())) {
                QueryWrapper queryWrapper = QueryWrapper.create().select(ShopInfo::getShopName)
                        .in(ShopInfo::getId, Arrays.stream(tbUserCouponVo.getUseShops().split(",")).map(Long::parseLong).toList())
                        .eq(ShopInfo::getStatus, 1);
                List<String> shopNames = shopInfoService.listAs(queryWrapper, String.class);
                if (CollUtil.isNotEmpty(shopNames)) {
                    StringBuilder result = new StringBuilder();
                    for (int i = 0; i < shopNames.size(); i++) {
                        if (i > 0) {
                            result.append(",");
                        }
                        result.append(shopNames.get(i));
                        if (i == maxShow - 1 && i != shopNames.size() - 1) {
                            result.append("...");
                            break;
                        }
                    }
                    tbUserCouponVo.setUseShops(result.toString());
                }
            }
        }
    }

    /**
     * 填充使用/门槛商品
     */
    private void setFoods(UserCouponVo tbUserCouponVo) {
        if (tbUserCouponVo.getType() == 1 || tbUserCouponVo.getType() == 2 || tbUserCouponVo.getType() == 3
                || tbUserCouponVo.getType() == 4 || tbUserCouponVo.getType() == 6) {
            if (StrUtil.isNotBlank(tbUserCouponVo.getFoods()) && !",".equals(tbUserCouponVo.getFoods())) {
                List<Long> couponFoodIds = Arrays.stream(tbUserCouponVo.getFoods().split(",")).map(Long::parseLong).toList();
                if (CollUtil.isNotEmpty(couponFoodIds)) {
                    List<Product> list = productService.list(new QueryWrapper()
                            .in(Product::getId, couponFoodIds).eq(Product::getIsDel, 0));
//                            log.info("优惠券商品列表:{}", list);
                    if (CollUtil.isEmpty(list)) {
                        tbUserCouponVo.setFoods("");
                    } else {
                        if (tbUserCouponVo.getType() == 1 || tbUserCouponVo.getType() == 3) {
                            tbUserCouponVo.setThresholdFoods(JSON.parseObject(JSON.toJSONString(list), new TypeReference<>() {
                            }));
                        } else {
                            tbUserCouponVo.setUseFoods(JSON.parseObject(JSON.toJSONString(list), new TypeReference<>() {
                            }));
                        }
                        String foods = list.stream().map(Product::getName).collect(Collectors.joining(","));
                        tbUserCouponVo.setFoods(foods);
                    }
                }
            } else {
                tbUserCouponVo.setFoods("全部商品");
            }
        }
    }

    /**
     * 过滤优惠券可用时间段 每人每日使用限量校验
     * 填充优惠券Json信息
     * {
     * "isUse": true,
     * "useRestrictions": "10：00到12：00可用",
     * "noUseRestrictions": "不在可用时间范围内"
     * }
     */
    private void setCouponInfo(Map<Long, JSONObject> coupons, UserCouponVo tbUserCouponVo, String week, DateTimeFormatter formatter, Long shopUserId) {
        boolean isUse = true;
        ShopCoupon tbShopCoupon = getById(tbUserCouponVo.getCouponId());
        StringBuilder useRestrictions = new StringBuilder("每天 ");
        String noUseRestrictions = "";
        if (StrUtil.isNotBlank(tbShopCoupon.getUseDays())) {
            String[] split = tbShopCoupon.getUseDays().split(",");
            if (split.length != 7) {
//                useRestrictions = new StringBuilder(STR."\{tbShopCoupon.getUseDays()} ");
                useRestrictions = new StringBuilder(tbShopCoupon.getUseDays() + " ");
            }
            if (!tbShopCoupon.getUseDays().contains(week)) {
                noUseRestrictions = "不在可用时间范围内";
                isUse = false;
            }
        }
        if ("custom".equals(tbShopCoupon.getUseTimeType())) {
            LocalTime currentTime = LocalTime.now();
            LocalTime startTime = tbShopCoupon.getUseStartTime().toLocalTime();
            LocalTime endTime = tbShopCoupon.getUseEndTime().toLocalTime();
            if (currentTime.isBefore(startTime)) {
                if (startTime.isBefore(endTime)) {
                    noUseRestrictions = "不在可用时间范围内";
                    isUse = false;
                } else if (currentTime.isAfter(endTime)) {
                    noUseRestrictions = "不在可用时间范围内";
                    isUse = false;
                }
            } else if (startTime.isBefore(endTime)) {
                if (currentTime.isAfter(endTime)) {
                    noUseRestrictions = "不在可用时间范围内";
                    isUse = false;
                }
            }
//            useRestrictions.append(STR."\{startTime.format(formatter)}-\{endTime.format(formatter)}");
            useRestrictions.append(startTime.format(formatter) + "-" + endTime.format(formatter));
        } else {
            useRestrictions.append("全时段");
        }
        useRestrictions.append(" 可用");
        if (tbUserCouponVo.getUseLimit() != MarketConstants.Num.NOT_LIMIT) {
            long useCount = recordService.count(new QueryWrapper()
                    .eq(MkShopCouponRecord::getCouponId, tbUserCouponVo.getCouponId())
                    .eq(MkShopCouponRecord::getShopUserId, shopUserId)
                    .ge(MkShopCouponRecord::getUseTime, LocalDate.now().atTime(LocalTime.MIN))
                    .le(MkShopCouponRecord::getUseTime, LocalDate.now().atTime(LocalTime.MAX))
                    .eq(MkShopCouponRecord::getStatus, 1));
            if (useCount >= tbUserCouponVo.getUseLimit()) {
                isUse = false;
                noUseRestrictions = "已达使用限量" + tbUserCouponVo.getUseLimit() + "张";
            }
        }
        JSONObject json = new JSONObject();
        json.put("isUse", isUse);
        json.put("useRestrictions", useRestrictions);
        json.put("noUseRestrictions", noUseRestrictions);

        coupons.put(tbUserCouponVo.getCouponId(), json);
    }

}
