package com.cyksj.web.controller.coupon;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cyksj.common.annotation.NoSubmit;
import com.cyksj.common.constant.Constant;
import com.cyksj.common.exception.BusinessRuntimeException;
import com.cyksj.common.util.Jsons;
import com.cyksj.dto.Result;
import com.cyksj.enums.GatewayResponse;
import com.cyksj.mapper.CouponUserPopupsRecordMapper;
import com.cyksj.mapper.UserMapper;
import com.cyksj.mapper.manage.coupon.CouponMapper;
import com.cyksj.mapper.manage.coupon.CouponRecommendMapper;
import com.cyksj.mapper.manage.coupon.CouponSkuMapper;
import com.cyksj.mapper.manage.coupon.CouponUserMapper;
import com.cyksj.mapper.manage.distribute.UserDistributeMapper;
import com.cyksj.mapper.manage.distribute.UserDistributeSharedMapper;
import com.cyksj.model.dto.CouponPopularizeDto;
import com.cyksj.model.entity.*;
import com.cyksj.model.request.ChannelPopularizeCouponReq;
import com.cyksj.model.request.CouponCollectReq;
import com.cyksj.model.views.*;
import com.cyksj.redis.RedisService;
import com.cyksj.service.coupon.CouponFontService;
import com.cyksj.service.sys.SysConfigService;
import com.cyksj.web.util.StpUserUtil;
import com.ejlchina.searcher.BeanSearcher;
import com.ejlchina.searcher.param.Operator;
import com.ejlchina.searcher.util.MapUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.List;
import java.util.stream.Collectors;

/*
 *项目名: netflix
 *文件名: CouponFrontController
 *创建者: JavaZou
 *创建时间:2022/11/18 10:56
 */
@RestController
@RequestMapping("/applet/coupon")
@RequiredArgsConstructor
public class CouponFrontController {
	private final CouponUserMapper couponUserMapper;

	private final BeanSearcher beanSearcher;

	private final CouponFontService couponFontService;

	private final RedisService redisService;

	private final CouponSkuMapper couponSkuMapper;

	private final CouponMapper couponMapper;

	private final UserDistributeMapper userDistributeMapper;

	private final CouponRecommendMapper couponRecommendMapper;

	private final UserDistributeSharedMapper userDistributeSharedMapper;

	private final UserMapper userMapper;

	private final HttpServletRequest request;

	private final SysConfigService sysConfigService;

	private final CouponUserPopupsRecordMapper couponUserPopupsRecordMapper;

	/**
	 * 优惠券领取中心列表
	 */
	@GetMapping("/center/list")
	public Result<Page<CouponActiveView>> couponCenterList(@RequestParam(defaultValue = "1") Long start, @RequestParam(defaultValue = "5") Long limit) {
		Long userId = StpUserUtil.getLoginIdAsLong();
		Page<CouponActiveView> page = couponUserMapper.couponCenterList(userId, new Page<>(start, limit));
		page.getRecords().forEach(data -> {
			String str = couponSkuMapper.selectGoodsSkuStr(data.getCouponId());
			data.setGoodsSkuStr(str.replaceAll(",", "/").replaceAll(";", ""));
			List<CouponSkuView> couponSkus = couponSkuMapper.getGoodsSkuByCouponId(data.getCouponId());
			try {
				data.setGoodsSkuIds(Jsons.toJson(couponSkus));
			} catch (Exception e) {

			}
		});
		return GatewayResponse.SUCCESS.newBuilder().toResult(page);
	}

	/**
	 * 个人优惠券列表
	 */
	@GetMapping("/personal/list")
	public Result<Page<CouponUserView>> couponPersonalList(@RequestParam(defaultValue = "1") Long start, @RequestParam(defaultValue = "5") Long limit, Long couponId) {
		Long userId = StpUserUtil.getLoginIdAsLong();
		Page<CouponUserView> page = couponUserMapper.couponPersonalList(userId, new Page<>(start, limit), couponId);
		page.getRecords().forEach(data -> {
			String str = couponSkuMapper.selectGoodsSkuStr(data.getCouponId());
			data.setGoodsSkuStr(str.replaceAll(",", "/").replaceAll(";", ""));
			List<CouponSkuView> couponSkus = couponSkuMapper.getGoodsSkuByCouponId(data.getCouponId());
			try {
				data.setGoodsSkuIds(Jsons.toJson(couponSkus));
			} catch (Exception e) {

			}
		});
		return GatewayResponse.SUCCESS.newBuilder().toResult(page);
	}

	/**
	 * 可用优惠券展示数量
	 */
	@GetMapping("/available/num")
	public Result<Integer> availableCouponNum(Long skuId, Boolean isRenew) {
		Long userId = StpUserUtil.getLoginIdAsLong();
		Long goodsId = null;
		//实物还是虚物
		GoodsDonSkuView goodsDonSkuView = beanSearcher.searchFirst(GoodsDonSkuView.class, MapUtils.builder().field(GoodsDonSkuView::getSkuId, skuId).op(Operator.Equal).build());
		if (goodsDonSkuView == null) {
			throw BusinessRuntimeException.getInstance("规格不存在");
		}
		BigDecimal skuMoney = goodsDonSkuView.getMoney();
		if (goodsDonSkuView.getType() == 2) {
			goodsId = goodsDonSkuView.getGoodsId();
		}
		List<CouponUserView> couponUserViews = couponUserMapper.countAvailableCouponList(goodsId, skuId, userId, isRenew);
		Integer total = couponUserViews.size();
		if (goodsDonSkuView.getType() == 2) {
			List<CouponUserView> collect = couponUserViews.stream().filter(coupon -> {
				if (coupon.getType() == Coupon.Type.reduce && skuMoney.compareTo(coupon.getReduceCondition()) < 0) {
					return false;
				}
				return true;
			}).collect(Collectors.toList());
			total = collect.size();
		}
		return GatewayResponse.SUCCESS.newBuilder().toResult(total);
	}

	@GetMapping("/available/list")
	public Result<Page<CouponUserView>> availableCouponList(Long skuId, Long couponId, Boolean isRenew, @RequestParam(defaultValue = "1") Long start, @RequestParam(defaultValue = "5") Long limit) {
		Long userId = StpUserUtil.getLoginIdAsLong();
		Page<CouponUserView> couponActiveViewList = couponFontService.getAvailableCouponList(skuId, couponId, userId, isRenew, start, limit);
		return GatewayResponse.SUCCESS.newBuilder().toResult(couponActiveViewList);
	}

	/**
	 * 推荐优惠券列表
	 */
	@GetMapping("/recommend/list")
	public Result<Page<CouponRecommendView>> getRecommendList(@RequestParam(defaultValue = "1") Long start, @RequestParam(defaultValue = "5") Long limit, Long couponId) {
		Long userId = StpUserUtil.getLoginIdAsLong();
		CouponNewUserView couponNewUserView = beanSearcher.searchFirst(CouponNewUserView.class, MapUtils.builder().field(CouponNewUserView::getUserId, userId).op(Operator.Equal).build());
		Boolean isNewUser = true;
		if (couponNewUserView != null) {
			isNewUser = false;
		}
		Page<CouponRecommendView> page = couponRecommendMapper.getRecommendCouponViewList(userId, isNewUser, new Page<>(start, limit), couponId);
		page.getRecords().forEach(data -> {
			if (data.getCouponStatus() == CouponActiveView.CouponStatus.received) {
				data.setValidStartTime(data.getUserValidStartTime());
				data.setValidEndTime(data.getUserValidEndTime());
			}
			String str = couponSkuMapper.selectGoodsSkuStr(data.getCouponId());
			data.setGoodsSkuStr(str.replaceAll(",", "/").replaceAll(";", ""));
			List<CouponSkuView> couponSkus = couponSkuMapper.getGoodsSkuByCouponId(data.getCouponId());
			try {
				data.setGoodsSkuIds(Jsons.toJson(couponSkus));
			} catch (Exception e) {

			}
		});
		return GatewayResponse.SUCCESS.newBuilder().toResult(page);
	}

	/**
	 * 一键领取推荐优惠券
	 */
	@PostMapping("/collect/recommend/whole")
	@NoSubmit
	public Result<String> collectWholeRecommendCoupon() {
		Long userId = StpUserUtil.getLoginIdAsLong();
		couponFontService.collectWholeRecommendCoupon(userId);
		return GatewayResponse.SUCCESS.newBuilder().toResult("领取成功");
	}

	/**
	 * 今日推荐优惠券弹窗已弹
	 */
	@GetMapping("/get/recommend/appear")
	public Result<Boolean> recommendIsAppear() {
		Long userId = StpUserUtil.getLoginIdAsLong();
		String zero = DateUtil.beginOfDay(DateTime.now()).toString();
		Object exists = redisService.get(RedisService.key.RECOMMEND_COUPON_DAY.getNameFormat(String.format("%s-%s", zero, userId)));
		if (exists == null) {
			redisService.set(RedisService.key.RECOMMEND_COUPON_DAY.getNameFormat(String.format("%s-%s", zero, userId)), userId, RedisService.key.RECOMMEND_COUPON_DAY.getTimeout());
		}
		return GatewayResponse.SUCCESS.newBuilder().toResult(exists == null ? false : true);
	}

	/**
	 * 领取优惠券
	 */
	@PostMapping("/collect")
	public Result<String> collectCoupon(@RequestBody CouponCollectReq couponCollectReq) {
		Long userId = StpUserUtil.getLoginIdAsLong();
		couponFontService.collectCoupon(couponCollectReq, userId);
		return GatewayResponse.SUCCESS.newBuilder().toResult("领取优惠券成功");
	}

	/**
	 * 领取推荐优惠券
	 */
	@PostMapping("/recommend/collect")
	public Result<String> collectRecommendCoupon(@RequestBody CouponCollectReq couponCollectReq) {
		Long userId = StpUserUtil.getLoginIdAsLong();
		couponFontService.collectRecommendCoupon(couponCollectReq, userId);
		return GatewayResponse.SUCCESS.newBuilder().toResult("领取优惠券成功");
	}

	/**
	 * 查询有可以领取的推荐优惠券
	 */
	@GetMapping("/recommend/collect/num")
	public Result<Integer> collectRecommendCouponNum() {
		Long userId = StpUserUtil.getLoginIdAsLong();
		CouponNewUserView couponNewUserView = beanSearcher.searchFirst(CouponNewUserView.class, MapUtils.builder().field(CouponNewUserView::getUserId, userId).op(Operator.Equal).build());
		Boolean isNewUser = true;
		if (couponNewUserView != null) {
			isNewUser = false;
		}
		Integer num = couponFontService.collectRecommendCouponNum(userId, isNewUser);
		return GatewayResponse.SUCCESS.newBuilder().toResult(num);
	}


	/**
	 * 优惠码详情
	 */
	@GetMapping("/get/exCode/detail")
	public Result<CouponPopularizeDto> getExCodeDetail(Long skuId, String exCode, Boolean isRenew) {
		Long userId = StpUserUtil.getLoginIdAsLong();
		GoodsDonSkuView goodsDonSkuView = beanSearcher.searchFirst(GoodsDonSkuView.class, MapUtils.builder().field(GoodsDonSkuView::getSkuId, skuId).op(Operator.Equal).build());
		if (goodsDonSkuView == null) {
			throw BusinessRuntimeException.getInstance("该规格不存在");
		}
		BigDecimal skuMoney = goodsDonSkuView.getMoney();
		if (goodsDonSkuView.getType() == 2) {
			throw BusinessRuntimeException.getInstance("实物不支持使用优惠码");
		}
		CouponPopularizeDto dto = couponMapper.checkExCode(exCode);
		if (dto == null) {
			throw BusinessRuntimeException.getInstance("该优惠码不存在");
		}
		if (dto.getIsGeneral() != null) {
			if (dto.getIsGeneral() && userId.equals(dto.getUserId())) {
				throw BusinessRuntimeException.getInstance("不可以使用自己的优惠码");
			}
			if (!dto.getIsGeneral()) {
				UserDistribute userDistribute = userDistributeMapper.selectById(dto.getDistributeId());
				if (userDistribute != null && userDistribute.getUserId().equals(userId)) {
					throw BusinessRuntimeException.getInstance("不可以使用自己的优惠码");
				}
			}
			//是否有上下级关系
			if (dto.getIsGeneral()) {
				UserDistributeShared userDistributeShared = userDistributeSharedMapper.selectOne(Wrappers.lambdaQuery(UserDistributeShared.class)
						.eq(UserDistributeShared::getUserId, userId).last("limit 1"));
				if (userDistributeShared == null) {
					//是否是 当天注册新用户 且下过单
					User user = userMapper.selectById(userId);
					if (user.getCreatedTime().before(DateUtil.beginOfDay(DateTime.now()))) {
						throw BusinessRuntimeException.getInstance("该优惠码只适用于新用户");
					}
					CouponNewUserView couponNewUserView = beanSearcher.searchFirst(CouponNewUserView.class, MapUtils.builder().field(CouponNewUserView::getUserId, userId).op(Operator.Equal).build());
					if (couponNewUserView != null) throw BusinessRuntimeException.getInstance("该优惠码只适用于新用户");
				}
				if (userDistributeShared != null && !userDistributeShared.getSharedId().equals(dto.getUserId())) {
					throw BusinessRuntimeException.getInstance("您已有推广,无法使用其他人推广码");
				}
			}
		}
		if (dto.getScope() == Coupon.Scope.newUser) {
			CouponNewUserView couponNewUserView = beanSearcher.searchFirst(CouponNewUserView.class, MapUtils.builder().field(CouponNewUserView::getUserId, userId).op(Operator.Equal).build());
			if (couponNewUserView != null) {
				throw BusinessRuntimeException.getInstance("该优惠码只适用于新用户");
			}
		}
		if (isRenew != null && isRenew) {
			Coupon.UseScope useScope = dto.getUseScope();
			if (useScope == Coupon.UseScope.orders) {
				throw BusinessRuntimeException.getInstance("该优惠码续费时不可使用");
			}
		}
		if (isRenew == null || !isRenew) {
			Coupon.UseScope useScope = dto.getUseScope();
			if (useScope == Coupon.UseScope.renew) {
				throw BusinessRuntimeException.getInstance("该优惠码下单时不可使用");
			}
		}
		if (dto.getIsValidTime() && dto.getValidStartTime().after(DateTime.now())) {
			throw BusinessRuntimeException.getInstance("该优惠码待生效");
		}
		if (dto.getIsValidTime() && dto.getValidEndTime().before(DateTime.now())) {
			throw BusinessRuntimeException.getInstance("该优惠码已失效");
		}
		CouponSku couponSku = couponSkuMapper.selectOne(Wrappers.lambdaQuery(CouponSku.class)
				.eq(CouponSku::getSkuId, skuId)
				.eq(CouponSku::getCouponId, dto.getCouponId())
				.select(CouponSku::getId).last("limit 1"));
		if (couponSku == null) {
			throw BusinessRuntimeException.getInstance("该优惠码不适用于该规格");
		}
		if (goodsDonSkuView.getType() == 2) {
			if (dto.getType() == Coupon.Type.reduce && skuMoney.compareTo(dto.getReduceCondition()) < 0) {
				throw BusinessRuntimeException.getInstance(String.format("满%s可用", dto.getReduceCondition().divide(BigDecimal.valueOf(100))));
			}
		}
		return GatewayResponse.SUCCESS.newBuilder().toResult(dto);
	}

	/**
	 * 查询优惠券
	 */
	@GetMapping("/get/couponList")
	public Result<List<CouponView>> getCouponList(@RequestParam(value = "couponIds") List<Long> couponIds) {
		if (couponIds.isEmpty()) {
			return GatewayResponse.SUCCESS.newBuilder().toResult();
		}
		List<CouponView> couponViews = beanSearcher.searchAll(CouponView.class, MapUtils.builder()
				.field(CouponView::getId, couponIds).op(Operator.InList)
				.orderBy(CouponView::getId).desc()
				.build());
		return GatewayResponse.SUCCESS.newBuilder().toResult(couponViews);
	}

	/**
	 * 渠道推广用户领取优惠券
	 */
	@PostMapping("/channel/popularize/receive")
	public Result<String> receiveChannelPopularizeCoupon(@RequestBody @Validated ChannelPopularizeCouponReq req) {
		long userId = StpUserUtil.getLoginIdAsLong();
		req.setUserId(userId);
		couponFontService.receiveChannelPopularizeCoupon(req);
		return GatewayResponse.SUCCESS.newBuilder().toResult("领取成功");
	}

	/**
	 * 渠道推广一键领取优惠券
	 */
	@PostMapping("/channel/popularize/collectAll/{popularizeId}")
	public Result<String> collectAllChannelCoupons(@PathVariable Long popularizeId) {
		long userId = StpUserUtil.getLoginIdAsLong();
		couponFontService.collectAllChannelCoupons(userId, popularizeId);
		return GatewayResponse.SUCCESS.newBuilder().toResult("领取成功");
	}

	/**
	 * 新用户福利 优惠券详情展示
	 */
	@GetMapping("/get/newUser/welfare")
	public Result<Object> getNewUserWelfare() {
		long userId = StpUserUtil.getLoginIdAsLong();
		SysConfig one = sysConfigService.getOne(Wrappers.lambdaQuery(SysConfig.class)
				.eq(SysConfig::getSysKey, Constant.YL_NEW_WELFARE_COUPON_ID)
				.last("limit 1"));
		if (one == null || StrUtil.isEmpty(one.getSysValue())) {
			return GatewayResponse.SUCCESS.newBuilder().toResult();
		}
		String couponId = one.getSysValue();
		CouponUserView couponUserView = couponFontService.getNewUserWelfareCoupons(userId, Long.valueOf(couponId));
		if (couponUserView == null) {
			CouponDetailView couponDetailView = beanSearcher.searchFirst(CouponDetailView.class, MapUtils.flatBuilder(request.getParameterMap()).field(CouponDetailView::getCouponId, couponId).build());
			return GatewayResponse.SUCCESS.newBuilder().toResult(couponDetailView);
		}
		return GatewayResponse.SUCCESS.newBuilder().toResult(couponUserView);
	}

	@GetMapping("/get/coupon/detail/{couponId}")
	public Result<CouponUserView> getCouponDetailById(@PathVariable Long couponId) {
		long userId = StpUserUtil.getLoginIdAsLong();
		CouponUserView couponUserView = couponFontService.getCouponDetailById(userId, couponId);
		return GatewayResponse.SUCCESS.newBuilder().toResult(couponUserView);
	}

	/**
	 * 领取优惠券
	 */
	@PostMapping("/receive/coupon/{couponId}")
	public Result<CouponUserView> receiveCoupon(@PathVariable Long couponId) {
		long userId = StpUserUtil.getLoginIdAsLong();
		CouponUserView couponUserView = couponFontService.receiveCoupon(userId, couponId, CouponUser.Channel.manual);
		return GatewayResponse.SUCCESS.newBuilder().toResult(couponUserView);
	}

	/**
	 * 优惠券详情
	 */
	@GetMapping("/get/detail/{couponId}")
	public Result<CouponDetailView> getCouponDetail(@PathVariable Long couponId) {
		CouponDetailView couponDetailView = beanSearcher.searchFirst(CouponDetailView.class, MapUtils.flatBuilder(request.getParameterMap()).field(CouponDetailView::getCouponId, couponId).build());
		String str = couponSkuMapper.selectGoodsSkuStr(couponDetailView.getCouponId());
		couponDetailView.setGoodsSkuStr(str.replaceAll(",", "/").replaceAll(";", ""));
		List<CouponSkuView> couponSkus = couponSkuMapper.getGoodsSkuByCouponId(couponDetailView.getCouponId());
		try {
			couponDetailView.setGoodsSkuIds(Jsons.toJson(couponSkus));
		} catch (Exception e) {

		}
		return GatewayResponse.SUCCESS.newBuilder().toResult(couponDetailView);
	}

	/**
	 * 引流新人优惠券详情
	 */
	@GetMapping("/get/yl/welfare/coupon/detail")
	@Deprecated
	public Result<CouponDetailView> getYlWelfareCouponDetail() {
		SysConfig one = sysConfigService.getOne(Wrappers.lambdaQuery(SysConfig.class)
				.eq(SysConfig::getSysKey, Constant.YL_NEW_WELFARE_COUPON_ID)
				.last("limit 1"));
		if (one == null || StrUtil.isEmpty(one.getSysValue())) {
			return GatewayResponse.SUCCESS.newBuilder().toResult();
		}
		String couponId = one.getSysValue();
		CouponDetailView couponDetailView = beanSearcher.searchFirst(CouponDetailView.class, MapUtils.flatBuilder(request.getParameterMap()).field(CouponDetailView::getCouponId, couponId).build());
		return GatewayResponse.SUCCESS.newBuilder().toResult(couponDetailView);
	}

	/**
	 * 领取新人优惠券
	 */
	@PostMapping("/receive/newWelfare")
	public Result<CouponUserView> receiveNewWelfareCoupon() {
		long userId = StpUserUtil.getLoginIdAsLong();
		SysConfig one = sysConfigService.getOne(Wrappers.lambdaQuery(SysConfig.class)
				.eq(SysConfig::getSysKey, Constant.YL_NEW_WELFARE_COUPON_ID)
				.last("limit 1"));
		if (one == null || StrUtil.isEmpty(one.getSysValue())) {
			throw BusinessRuntimeException.getInstance("暂无新人优惠券活动");
		}
		String couponId = one.getSysValue();
		CouponUserView couponUserView = couponFontService.receiveCoupon(userId, Long.valueOf(couponId), CouponUser.Channel.new_welfare);
		if (couponUserView == null) {
			couponUserView = beanSearcher.searchFirst(CouponUserView.class, MapUtils.flatBuilder(request.getParameterMap()).field(CouponNewUserView::getUserId, userId).field(CouponUserView::getCouponId, couponId).build());
		}
		if (couponUserView != null) {
			String str = couponSkuMapper.selectGoodsSkuStr(couponUserView.getCouponId());
			couponUserView.setGoodsSkuStr(str.replaceAll(",", "/").replaceAll(";", ""));
			List<CouponSkuView> couponSkus = couponSkuMapper.getGoodsSkuByCouponId(couponUserView.getCouponId());
			try {
				couponUserView.setGoodsSkuIds(Jsons.toJson(couponSkus));
			} catch (Exception e) {
			}
		}
		return GatewayResponse.SUCCESS.newBuilder().toResult(couponUserView);
	}

	//==================================================优惠券弹窗======================================================================================

	/**
	 * 用户存在弹窗列表
	 * @return
	 */
	@GetMapping("/get/popups")
	public Result<List<CouponUserPopupsView>> getCouponPopups() {
		long userId = StpUserUtil.getLoginIdAsLong();
		DateTime now = DateTime.now();
		List<CouponUserPopupsView> couponUserPopups = beanSearcher.searchAll(CouponUserPopupsView.class, MapUtils.flatBuilder(request.getParameterMap())
				.field(CouponUserPopupsView::getStartTime, now).op(Operator.LessEqual)
				.field(CouponUserPopupsView::getEndTime, now).op(Operator.GreaterThan)
				.build());
		couponUserPopups = couponUserPopups.stream().filter(cu -> {
			try {
				List<Long> couponIds = Jsons.parseList(cu.getCouponIds(), Long.class);
				Integer selectCount = couponUserMapper.selectCount(Wrappers.lambdaQuery(CouponUser.class)
						.eq(CouponUser::getUserId, userId)
						.in(CouponUser::getCouponId, couponIds)
						.le(CouponUser::getValidStartTime, now)
						.gt(CouponUser::getValidEndTime, now)
						.eq(CouponUser::getStatus, CouponUser.Status.unused));
				//是否符合条件
				if (selectCount > 0) {
					Integer frequency = cu.getFrequency();
					LambdaQueryWrapper<CouponUserPopupsRecord> wrapper = Wrappers.lambdaQuery(CouponUserPopupsRecord.class);
					if (frequency != 0) {
						wrapper.between(CouponUserPopupsRecord::getCreatedTime, DateUtil.beginOfDay(now), DateUtil.endOfDay(now));
					}
					Integer popupsRecordCount = couponUserPopupsRecordMapper.selectCount(wrapper.eq(CouponUserPopupsRecord::getUserId, userId).eq(CouponUserPopupsRecord::getPopupsId, cu.getPopupsId()));
					//未有弹窗记录
					if (popupsRecordCount == 0) {
						List<CouponUserView> couponUserViews = beanSearcher.searchAll(CouponUserView.class, MapUtils.builder().field(CouponUserView::getUserId, userId)
								.field(CouponUserView::getCouponId, couponIds).op(Operator.InList)
								.orderBy(CouponUserView::getDiscount).asc()
								.build());
						cu.setCouponUserViews(couponUserViews);
						return true;
					}
				}
				return false;
			} catch (Exception e) {

			}
			return false;
		}).collect(Collectors.toList());
		return GatewayResponse.SUCCESS.newBuilder().toResult(couponUserPopups);
	}

	/**
	 * 优惠弹窗记录
	 */
	@PostMapping("/record/popups/{popupsId}")
	public Result<String> recordPopups(@PathVariable Long popupsId) {
		long userId = StpUserUtil.getLoginIdAsLong();
		CouponUserPopupsRecord couponUserPopupsRecord = new CouponUserPopupsRecord();
		couponUserPopupsRecord.setPopupsId(popupsId);
		couponUserPopupsRecord.setUserId(userId);
		couponUserPopupsRecordMapper.insert(couponUserPopupsRecord);
		return GatewayResponse.SUCCESS.newBuilder().toResult();
	}

	/**
	 * 平台发券活动详情
	 */
	@GetMapping("/get/goods/activity")
	public Result<UserActivityView> getGoodsActivity() throws Exception {
		Long userId = StpUserUtil.getUserIdAfterLogin();
		String dateStr = DateTime.now().toString();
		String time = String.format(" and (ua.start_time is null or (ua.start_time < '%s' and ua.end_time > '%s'))", dateStr, dateStr);
		UserActivityView userActivityView = beanSearcher.searchFirst(UserActivityView.class, MapUtils.flatBuilder(request.getParameterMap())
				.field(UserActivityView::getType, 3)
				.put("time", time)
				.build());
		if (userActivityView != null && StrUtil.isNotBlank(userActivityView.getCouponIds())) {
			List<Long> couponIds = Jsons.parseList(userActivityView.getCouponIds(), Long.class);
			userActivityView.setCouponViews(beanSearcher.searchAll(CouponView.class, MapUtils.builder().field(CouponView::getId, couponIds).op(Operator.InList).build()));
			//是否领取过
			if (userId != null) {
				Integer selectCount = couponUserMapper.selectCount(Wrappers.lambdaQuery(CouponUser.class).in(CouponUser::getCouponId, couponIds).eq(CouponUser::getUserId, userId));
				userActivityView.setIsReceived(selectCount == couponIds.size());
			}
		}
		return GatewayResponse.SUCCESS.newBuilder().toResult(userActivityView);
	}


	/**
	 * 平台发券活动
	 * 购买特定商品 展示优惠券
	 */
	@GetMapping("/get/goods/activity/coupons")
	public Result<List<CouponView>> getGoodsUserActivityCoupons() throws Exception {
		long userId = StpUserUtil.getLoginIdAsLong();
		List<CouponView> couponViews = couponFontService.getGoodsUserActivityCoupons(userId);
		return GatewayResponse.SUCCESS.newBuilder().toResult(couponViews);
	}

	/**
	 * 平台发券活动
	 * 一键领取优惠券
	 */
	@PostMapping("/goods/activity/collectAll")
	public Result<String> collectAllGoodsActivityCoupons() throws Exception {
		long userId = StpUserUtil.getLoginIdAsLong();
		couponFontService.collectAllGoodsActivityCoupons(userId);
		return GatewayResponse.SUCCESS.newBuilder().toResult();
	}
}

