package com.cyksj.web.controller.cps;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.qrcode.QrCodeUtil;
import cn.hutool.extra.qrcode.QrConfig;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.cyksj.common.EnvCommonService;
import com.cyksj.common.annotation.NoSubmit;
import com.cyksj.common.constant.Constant;
import com.cyksj.common.util.Jsons;
import com.cyksj.dto.Result;
import com.cyksj.enums.GatewayResponse;
import com.cyksj.mapper.DistributePopularizeClickRecordMapper;
import com.cyksj.mapper.GoodsDonMapper;
import com.cyksj.mapper.GoodsDonSkuMapper;
import com.cyksj.mapper.UserDistributePosterRecordMapper;
import com.cyksj.mapper.manage.coupon.CouponDistributePopularizeMapper;
import com.cyksj.mapper.manage.distribute.*;
import com.cyksj.mapper.sys.SysConfigMapper;
import com.cyksj.model.entity.*;
import com.cyksj.model.views.*;
import com.cyksj.service.cps.CpsPopularizeService;
import com.cyksj.service.user.UserBindRelationService;
import com.cyksj.service.user.UserCommonService;
import com.cyksj.service.user.UserService;
import com.cyksj.web.util.StpCpsManageUser;
import com.ejlchina.searcher.BeanSearcher;
import com.ejlchina.searcher.SearchResult;
import com.ejlchina.searcher.param.Operator;
import com.ejlchina.searcher.util.MapBuilder;
import com.ejlchina.searcher.util.MapUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.*;

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

/*
 *项目名: netflix
 *文件名: CpsPopularizeController
 *创建者: JavaZou
 *创建时间:2023/5/15 15:03
 */
@RestController
@RequestMapping("/cps/manage/popularize")
@RequiredArgsConstructor
public class CpsPopularizeController {
	private final CpsPopularizeService cpsPopularizeService;

	private final BeanSearcher beanSearcher;

	private final HttpServletRequest request;

	private final EnvCommonService envCommonService;

	private final CouponDistributePopularizeMapper couponDistributePopularizeMapper;

	private final UserService userService;

	private final UserCommonService userCommonService;

	private final GoodsDonMapper goodsDonMapper;

	private final DistributePopularizeClickRecordMapper distributePopularizeClickRecordMapper;

	private final UserDistributeMapper userDistributeMapper;

	private final UserPlatDistributeRateMapper userPlatDistributeRateMapper;

	private final GoodsDonSkuMapper skuMapper;

	private final UserPlatSkuDistributeRateMapper userPlatSkuDistributeRateMapper;

	private final DistributeGeneralSkuRateMapper distributeGeneralSkuRateMapper;

	private final UserDistributePosterRecordMapper userDistributePosterRecordMapper;

	private final DistributePosterGoodsMapper distributePosterGoodsMapper;

	private final UserBindRelationService userBindRelationService;

	private final BusinessDistributeDefaultRateConfigMapper businessDistributeDefaultRateConfigMapper;

	private final BusinessDistributeDefaultSkuRateConfigMapper businessDistributeDefaultSkuRateConfigMapper;

	private final SysConfigMapper sysConfigMapper;

	/**
	 * 渠道推广链接列表
	 */
	@GetMapping("/get")
	public Result<SearchResult<UserDistributePopularizeView>> getList(String startTime, String endTime) {
		long cpsUserId = StpCpsManageUser.getLoginIdAsLong();
		MapBuilder builder = MapUtils.flatBuilder(request.getParameterMap());
		builder.put("userId", String.format("and user_id = %s", cpsUserId));
		String time = StrUtil.EMPTY;
		if (startTime != null) {
			time += String.format(" and od.created_time >= '%s'", startTime);
		}
		if (endTime != null) {
			time += String.format(" and od.created_time < '%s'", endTime);
		}
		if (StrUtil.isNotBlank(time)) {
			builder.put("time", time);
		}
		UserDistribute userDistribute = userDistributeMapper.selectOne(Wrappers.lambdaQuery(UserDistribute.class)
				.eq(UserDistribute::getUserId, cpsUserId)
				.eq(UserDistribute::getDeleted, 1)
				.last("limit 1"));
		SearchResult<UserDistributePopularizeView> search = beanSearcher.search(UserDistributePopularizeView.class, builder.build());
		search.getDataList().forEach(data -> {
			if (StrUtil.isNotBlank(data.getOtherUrl())) {
				if (Constant.CC_DISTRIBUTE_MARK.equals(data.getOtherUrl())) {
					data.setPopularizeLink(String.format(Constant.DISTRIBUTE_CLAUDE_CODE_CC_URL, data.getCode()));
					//对应优惠码
					data.setCouponCode(couponDistributePopularizeMapper.getCouponCodeByUid(cpsUserId, Constant.DISTRIBUTE_CLAUDE_CODE_COUPON_ID));
				} else if (Constant.NANO_DISTRIBUTE_MARK.equals(data.getOtherUrl())) {
					data.setPopularizeLink(String.format(Constant.DISTRIBUTE_NANO_URL, data.getCode()));
					//对应优惠码
					data.setCouponCode(couponDistributePopularizeMapper.getCouponCodeByUid(cpsUserId, Constant.DISTRIBUTE_NANO_COUPON_ID));
				}
			}
			if (StrUtil.isEmpty(data.getPopularizeLink())) {
				data.setPopularizeLink(String.format(envCommonService.DISTRIBUTE_DEFAULT_URL_PREFIX, data.getCode()));
			}
			Optional.ofNullable(goodsDonMapper.selectById(data.getGoodsId())).ifPresent(goods -> {
				data.setTitle(goods.getTitle());
				data.setLogo(goods.getLogo());
				if (data.getGoodsId() != null && data.getGoodsId() == Constant.VIP_RELATE_GOODS_ID) {
					SysConfig sysConfig = sysConfigMapper.selectOne(Wrappers.lambdaQuery(SysConfig.class)
							.eq(SysConfig::getSysKey, Constant.VIP_FEE_KEY)
							.last("limit 1"));
					if (sysConfig != null && StrUtil.isNotEmpty(sysConfig.getSysValue())) {
						data.setPrice(BigDecimal.valueOf(Integer.parseInt(sysConfig.getSysValue())));
					}
				} else {
					data.setPrice(goods.getMinPrice());
				}
				UserPlatDistributeRate userPlatDistributeRate = userPlatDistributeRateMapper.selectOne(Wrappers.lambdaQuery(UserPlatDistributeRate.class)
						.eq(UserPlatDistributeRate::getDistributeId, userDistribute.getId())
						.eq(UserPlatDistributeRate::getGoodsId, data.getGoodsId())
						.last("limit 1"));
				if (userPlatDistributeRate != null) {
					data.setRate(userPlatDistributeRate.getRate());
				} else {
					BusinessDistributeDefaultRateConfig businessDistributeDefaultRateConfig = businessDistributeDefaultRateConfigMapper.selectOne(Wrappers.lambdaQuery(BusinessDistributeDefaultRateConfig.class)
							.eq(BusinessDistributeDefaultRateConfig::getGoodsId, data.getGoodsId())
							.last("limit 1"));
					if (businessDistributeDefaultRateConfig != null) {
						data.setRate(businessDistributeDefaultRateConfig.getRate());
					}
				}
				if (goods.getIsSkuDistribute()) {
					UserPlatSkuDistributeRate userPlatSkuDistributeRate = userPlatSkuDistributeRateMapper.selectOne(Wrappers.lambdaQuery(UserPlatSkuDistributeRate.class)
							.eq(UserPlatSkuDistributeRate::getDistributeId, userDistribute.getId())
							.eq(UserPlatSkuDistributeRate::getGoodsId, data.getGoodsId())
							.ne(UserPlatSkuDistributeRate::getRate, 0)
							//上架
							.apply("exists (select 1 from goods_don_sku sku where sku.id = sku_id and sku.status is true limit 1)")
							.orderByAsc(UserPlatSkuDistributeRate::getRate)
							.last("limit 1"));
					if (userPlatSkuDistributeRate != null) {
						data.setRate(userPlatSkuDistributeRate.getRate());
					} else {
						BusinessDistributeDefaultSkuRateConfig businessDistributeDefaultSkuRateConfig = businessDistributeDefaultSkuRateConfigMapper.selectOne(Wrappers.lambdaQuery(BusinessDistributeDefaultSkuRateConfig.class)
								.eq(BusinessDistributeDefaultSkuRateConfig::getGoodsId, data.getGoodsId())
								.gt(BusinessDistributeDefaultSkuRateConfig::getRate, 0)
								.apply("exists (select 1 from goods_don_sku sku where sku.id = sku_id and sku.status is true limit 1)")
								.orderByAsc(BusinessDistributeDefaultSkuRateConfig::getRate)
								.last("limit 1"));
						if (businessDistributeDefaultSkuRateConfig != null) {
							data.setRate(businessDistributeDefaultSkuRateConfig.getRate());
						}
					}
				}
			});
			data.setClickNum(distributePopularizeClickRecordMapper.selectCount(Wrappers.lambdaQuery(DistributePopularizeClickRecord.class)
					.eq(DistributePopularizeClickRecord::getPopularizeId, data.getId())
					.ge(startTime != null, DistributePopularizeClickRecord::getCreatedTime, startTime)
					.lt(endTime != null, DistributePopularizeClickRecord::getCreatedTime, endTime)));
			String link = data.getPopularizeLink();
			if (data.getGoodsId() != null && data.getGoodsId() > 0) {
				if (!envCommonService.isPrdEnv()) {
					link += "/test/web";
				}
				link += "/?gid=" + data.getGoodsId();
			}
			if (data.getSkuId() != null && data.getSkuId() > 0) {
				Optional.ofNullable(skuMapper.selectById(data.getSkuId())).ifPresent(sku -> data.setSpecVal(sku.getSpecVal()));
				link += "&skuId=" + data.getSkuId();
			}
			data.setUrlCode(QrCodeUtil.generateAsBase64(link, QrConfig.create(), "png"));
			//会员订单数据
			if (data.getGoodsId() != null && data.getGoodsId() == Constant.VIP_RELATE_GOODS_ID) {
				UserDistributePopularizeView vipOrderView =cpsPopularizeService.getVipPopularizeDetail(data.getId(), startTime, endTime);
				data.setOrders(data.getOrders() + vipOrderView.getOrders());
				data.setOrdersMoney(data.getOrdersMoney().add(vipOrderView.getOrdersMoney()));
				data.setWMoney(data.getWMoney().add(vipOrderView.getWMoney()));
				data.setGotMoney(data.getGotMoney().add(vipOrderView.getGotMoney()));
			}
		});
		return GatewayResponse.SUCCESS.newBuilder().toResult(search);
	}

	/**
	 * 默认链接详情
	 */
	@GetMapping("/get/default")
	public Result<UserDistributePopularizeView> getDefaultDetail(String startTime, String endTime) {
		long cpsUserId = StpCpsManageUser.getLoginIdAsLong();
		User user = userService.getById(cpsUserId);
		UserDistributePopularizeView view = Optional.ofNullable(cpsPopularizeService.getDefaultPopularizeDetail(cpsUserId, startTime, endTime)).orElseGet(() -> {
			UserDistributePopularizeView newPopularizeView = new UserDistributePopularizeView();
			newPopularizeView.setOrders(0);
			newPopularizeView.setOrdersMoney(BigDecimal.ZERO);
			newPopularizeView.setWMoney(BigDecimal.ZERO);
			newPopularizeView.setGotMoney(BigDecimal.ZERO);
			return newPopularizeView;
		});
		if (StrUtil.isEmpty(user.getShowId())) {
			user.setShowId(userCommonService.getUserShowId(user.getId()));
		}
		view.setPopularizeLink(String.format(envCommonService.DISTRIBUTE_DEFAULT_URL_PREFIX, user.getShowId()));
		//优惠码
		view.setCouponCode(couponDistributePopularizeMapper.getCouponCodeByUid(cpsUserId, null));
		view.setClickNum(distributePopularizeClickRecordMapper.selectCount(Wrappers.lambdaQuery(DistributePopularizeClickRecord.class).eq(DistributePopularizeClickRecord::getShowId, user.getShowId())));
		view.setUrlCode(QrCodeUtil.generateAsBase64(view.getPopularizeLink(), QrConfig.create(), "png"));
		return GatewayResponse.SUCCESS.newBuilder().toResult(view);
	}

	/**
	 * 新增推广链接
	 */
	@PostMapping("/post")
	@NoSubmit
	public Result<String> insert(@RequestBody UserDistributePopularize popularize) {
		long cpsUserId = StpCpsManageUser.getLoginIdAsLong();
		popularize.setUserId(cpsUserId);
		cpsPopularizeService.insert(popularize);
		return GatewayResponse.SUCCESS.newBuilder().toResult(String.format("%s?dsCode=%s", envCommonService.getDomain2(), popularize.getCode()));
	}

	/**
	 * 编辑推广链接
	 */
	@PutMapping("/put")
	@NoSubmit
	public Result<String> update(@RequestBody UserDistributePopularize popularize) {
		long cpsUserId = StpCpsManageUser.getLoginIdAsLong();
		popularize.setUserId(cpsUserId);
		cpsPopularizeService.update(popularize);
		return GatewayResponse.SUCCESS.newBuilder().toResult();
	}

	/**
	 * 删除推广链接
	 */
	@DeleteMapping("/delete/{id}")
	@NoSubmit
	public Result<String> deleteById(@PathVariable Long id) {
		long cpsUserId = StpCpsManageUser.getLoginIdAsLong();
		cpsPopularizeService.deleteById(cpsUserId, id);
		return GatewayResponse.SUCCESS.newBuilder().toResult();
	}

	/**
	 * 获取所有平台列表
	 */
	@GetMapping("/get/all/goods")
	public Result<List<CpsGoodsDonDistributeView>> getAllGoodsList(Boolean isNoBuyout, Boolean isRate) {
		Long cpsUserId = StpCpsManageUser.getLoginIdAsLong();
		MapBuilder builder = MapUtils.flatBuilder(request.getParameterMap());
		if (isRate != null && isRate) {
			builder.field(CpsGoodsDonDistributeView::getRate, 0).op(Operator.GreaterThan);
		}
		List<CpsGoodsDonDistributeView> list = beanSearcher.searchAll(CpsGoodsDonDistributeView.class, builder
				.put("distribute_id", String.format("and distribute_id = (select id from user_distribute where user_id = %s and deleted is true limit 1)", cpsUserId))
				.build());
		UserDistribute userDistribute = userDistributeMapper.selectOne(Wrappers.lambdaQuery(UserDistribute.class).eq(UserDistribute::getUserId, cpsUserId)
				.eq(UserDistribute::getDeleted, Boolean.TRUE)
				.last("limit 1"));
		list.forEach(goods->{
			LambdaQueryWrapper<GoodsDonSku> wrapper = Wrappers.lambdaQuery(GoodsDonSku.class)
					.eq(GoodsDonSku::getGoodsId, goods.getId())
					.isNull(GoodsDonSku::getUserOwns)
					.eq(GoodsDonSku::getStatus, Boolean.TRUE);
			if (goods.getIsSkuDistribute()) {
				//开启规格分销 需要排除那些为0的规格
				List<UserPlatSkuDistributeRate> userPlatSkuDistributeRates = beanSearcher.searchList(UserPlatSkuDistributeRate.class, MapUtils.builder()
						.field(UserPlatSkuDistributeRate::getDistributeId, userDistribute.getId())
						.field(UserPlatSkuDistributeRate::getRate, 0)
						.build());
				List<Long> exuSkuIds = userPlatSkuDistributeRates.stream().map(UserPlatSkuDistributeRate::getSkuId).collect(Collectors.toList());
				if (CollUtil.isNotEmpty(exuSkuIds)) {
					wrapper.notIn(GoodsDonSku::getId, exuSkuIds);
				}
			}
			List<GoodsDonSku> goodsDonSkus = skuMapper.selectList(wrapper
					.select(GoodsDonSku::getId, GoodsDonSku::getSpecVal));
			goods.setSkus(goodsDonSkus);
		});
		return GatewayResponse.SUCCESS.newBuilder().toResult(list);
	}

	/**
	 * 复制客服活码链接
	 * 用于cps用户实物分销
	 */
	@GetMapping("/get/service/code")
	public Result<String> getServiceCodeUrl() {
		long cpsUserId = StpCpsManageUser.getLoginIdAsLong();
		return GatewayResponse.SUCCESS.newBuilder().toResult(cpsPopularizeService.getServiceCodeUrl(cpsUserId));
	}


	/**
	 * 推广平台海报列表
	 */
	@GetMapping("/get/ds/poster/goods")
	public Result<List<DistributePosterGoodsCpsView>> getPosterGoods(String startTime, String endTime) {
		long cpsUserId = StpCpsManageUser.getLoginIdAsLong();
		UserDistribute userDistribute = userDistributeMapper.selectOne(Wrappers.lambdaQuery(UserDistribute.class)
				.eq(UserDistribute::getUserId, cpsUserId)
				.eq(UserDistribute::getDeleted, 1)
				.last("limit 1"));
		MapBuilder builder = MapUtils.flatBuilder(request.getParameterMap());
		StringBuilder time = new StringBuilder();
		if (startTime != null) {
			time.append(String.format(" and od.created_time >= '%s'", startTime));
		}
		if (endTime != null) {
			time.append(String.format(" and od.created_time < '%s'", endTime));
		}
		List<Long> userIdList = userBindRelationService.getRelationUserIdList(cpsUserId, null);
		List<DistributePosterGoodsCpsView> searchAll = beanSearcher.searchAll(DistributePosterGoodsCpsView.class, builder.build());
		searchAll.forEach(e -> {
			if (userDistribute != null) {
				UserPlatDistributeRate userPlatDistributeRate = userPlatDistributeRateMapper.selectOne(Wrappers.lambdaQuery(UserPlatDistributeRate.class)
						.eq(UserPlatDistributeRate::getDistributeId, userDistribute.getId())
						.eq(UserPlatDistributeRate::getGoodsId, e.getGoodsId())
						.last("limit 1"));
				if (userPlatDistributeRate != null) {
					e.setRate(userPlatDistributeRate.getRate());
				} else {
					BusinessDistributeDefaultRateConfig businessDistributeDefaultRateConfig = businessDistributeDefaultRateConfigMapper.selectOne(Wrappers.lambdaQuery(BusinessDistributeDefaultRateConfig.class)
							.eq(BusinessDistributeDefaultRateConfig::getGoodsId, e.getGoodsId())
							.last("limit 1"));
					if (businessDistributeDefaultRateConfig != null) {
						e.setRate(businessDistributeDefaultRateConfig.getRate());
					}
				}
			}
			if (e.getIsSkuRate()) {
				GoodsDonSku sku = skuMapper.selectOne(Wrappers.lambdaQuery(GoodsDonSku.class)
						.eq(GoodsDonSku::getGoodsId, e.getGoodsId())
						.eq(GoodsDonSku::getStatus, 1)
						.orderByAsc(GoodsDonSku::getPrice)
						.last("limit 1"));
				//先获取价格最低的规格对应的 比例
				//渠道
				if (userDistribute != null) {
					UserPlatSkuDistributeRate minPriceSkuRate = userPlatSkuDistributeRateMapper.selectOne(Wrappers.lambdaQuery(UserPlatSkuDistributeRate.class)
							.eq(UserPlatSkuDistributeRate::getDistributeId, userDistribute.getId())
							.eq(UserPlatSkuDistributeRate::getGoodsId, e.getGoodsId())
							.eq(UserPlatSkuDistributeRate::getSkuId, sku.getId())
							.last("limit 1"));
					if (minPriceSkuRate != null && minPriceSkuRate.getRate() != 0) {
						e.setRate(minPriceSkuRate.getRate());
					} else {
						UserPlatSkuDistributeRate userPlatSkuDistributeRate = userPlatSkuDistributeRateMapper.selectOne(Wrappers.lambdaQuery(UserPlatSkuDistributeRate.class)
								.eq(UserPlatSkuDistributeRate::getDistributeId, userDistribute.getId())
								.eq(UserPlatSkuDistributeRate::getGoodsId, e.getGoodsId())
								.ne(UserPlatSkuDistributeRate::getRate, 0)
								//上架
								.apply("exists (select 1 from goods_don_sku sku where sku.id = sku_id and sku.status is true limit 1)")
								.orderByAsc(UserPlatSkuDistributeRate::getRate)
								.last("limit 1"));
						if (userPlatSkuDistributeRate != null) {
							e.setRate(userPlatSkuDistributeRate.getRate());
							sku = skuMapper.selectById(userPlatSkuDistributeRate.getSkuId());
							e.setPrice(sku.getPrice());
						} else {
							BusinessDistributeDefaultSkuRateConfig businessDistributeDefaultSkuRateConfig = businessDistributeDefaultSkuRateConfigMapper.selectOne(Wrappers.lambdaQuery(BusinessDistributeDefaultSkuRateConfig.class)
									.eq(BusinessDistributeDefaultSkuRateConfig::getGoodsId, e.getGoodsId())
									.gt(BusinessDistributeDefaultSkuRateConfig::getRate, 0)
									.apply("exists (select 1 from goods_don_sku sku where sku.id = sku_id and sku.status is true limit 1)")
									.orderByAsc(BusinessDistributeDefaultSkuRateConfig::getRate)
									.last("limit 1"));
							if (businessDistributeDefaultSkuRateConfig != null) {
								e.setRate(businessDistributeDefaultSkuRateConfig.getRate());
							}
						}
					}
				} else {
					//普通
					DistributeGeneralSkuRate minPriceRate = distributeGeneralSkuRateMapper.selectOne(Wrappers.lambdaQuery(DistributeGeneralSkuRate.class)
							.eq(DistributeGeneralSkuRate::getGoodsId, e.getGoodsId())
							.eq(DistributeGeneralSkuRate::getSkuId, sku.getId())
							.last("limit 1"));
					if (minPriceRate != null && minPriceRate.getRate() > 0) {
						e.setRate(minPriceRate.getRate());
					} else {
						DistributeGeneralSkuRate distributeGeneralSkuRate = distributeGeneralSkuRateMapper.selectOne(Wrappers.lambdaQuery(DistributeGeneralSkuRate.class)
								.eq(DistributeGeneralSkuRate::getGoodsId, e.getGoodsId())
								.apply("exists (select 1 from goods_don_sku sku where sku.id = sku_id and sku.status is true limit 1)")
								.ne(DistributeGeneralSkuRate::getRate, 0)
								.orderByAsc(DistributeGeneralSkuRate::getRate)
								.last("limit 1"));
						if (distributeGeneralSkuRate != null) {
							e.setRate(distributeGeneralSkuRate.getRate());
							sku = skuMapper.selectById(distributeGeneralSkuRate.getSkuId());
							e.setPrice(sku.getPrice());
						}
					}
				}
			}

			//用户推广海报订单详情
			MapBuilder posterOrderBuilder = MapUtils.flatBuilder(request.getParameterMap());
			if (time.length() > 0) {
				posterOrderBuilder.put("time", time.toString());
			}
			UserDistributePosterOrderDetailView distributePosterOrderDetailView = beanSearcher.searchFirst(UserDistributePosterOrderDetailView.class, posterOrderBuilder.put("condition", String.format(String.format(" where user_id = %s and poster_id = %s", cpsUserId, e.getId()))).build());
			if (distributePosterOrderDetailView != null) {
				e.setOrdersMoney(distributePosterOrderDetailView.getOrdersMoney());
				e.setOrders(distributePosterOrderDetailView.getOrders());
				e.setWMoney(distributePosterOrderDetailView.getWMoney());
				e.setGotMoney(distributePosterOrderDetailView.getGotMoney());
				e.setClickNum(distributePopularizeClickRecordMapper.selectCount(Wrappers.lambdaQuery(DistributePopularizeClickRecord.class)
						.eq(DistributePopularizeClickRecord::getRid, distributePosterOrderDetailView.getId())
						.ge(startTime != null, DistributePopularizeClickRecord::getCreatedTime, startTime)
						.lt(endTime != null, DistributePopularizeClickRecord::getCreatedTime, endTime)));
			}

			UserDistributePosterRecord distributePosterRecord = userDistributePosterRecordMapper.selectOne(Wrappers.lambdaQuery(UserDistributePosterRecord.class)
					.eq(UserDistributePosterRecord::getPosterId, e.getId())
					.in(UserDistributePosterRecord::getUserId, userIdList)
					.last("limit 1"));
			if (distributePosterRecord != null) {
				e.setRid(distributePosterRecord.getId());
			}
		});
		return GatewayResponse.SUCCESS.newBuilder().toResult(searchAll);
	}


	/**
	 * 用户下载海报记录
	 */
	@PostMapping("/poster/record/{posterId}")
	public Result<Long> posterRecord(@PathVariable Long posterId) {
		long cpsUserId = StpCpsManageUser.getLoginIdAsLong();
		DistributePosterGoods distributePosterGoods = distributePosterGoodsMapper.selectById(posterId);
		if (distributePosterGoods == null) {
			return GatewayResponse.SUCCESS.newBuilder().toResult();
		}
		UserDistributePosterRecord distributePosterRecord = new UserDistributePosterRecord();
		distributePosterRecord.setPosterId(posterId);
		distributePosterRecord.setUserId(cpsUserId);
		try {
			userDistributePosterRecordMapper.insert(distributePosterRecord);
		} catch (DuplicateKeyException e) {
			distributePosterRecord = userDistributePosterRecordMapper.selectOne(Wrappers.lambdaQuery(UserDistributePosterRecord.class)
					.eq(UserDistributePosterRecord::getUserId, cpsUserId)
					.eq(UserDistributePosterRecord::getPosterId, posterId)
					.last("limit 1"));
		}
		return GatewayResponse.SUCCESS.newBuilder().toResult(distributePosterRecord.getId());
	}

	/**
	 * 更新推荐海报状态
	 */
	@PutMapping("/update/recommend/status")
	public Result<String> updateRecommendStatus() {
		long cpsUserId = StpCpsManageUser.getLoginIdAsLong();

		UserDistribute userDistribute = userDistributeMapper.selectOne(Wrappers.lambdaQuery(UserDistribute.class)
				.eq(UserDistribute::getUserId, cpsUserId)
				.eq(UserDistribute::getDeleted, 1)
				.last("limit 1"));
		if (userDistribute != null) {
			Boolean isPoster = userDistribute.getIsPoster();
			userDistributeMapper.update(null, Wrappers.lambdaUpdate(UserDistribute.class)
					.set(UserDistribute::getIsPoster, !isPoster)
					.eq(UserDistribute::getId, userDistribute.getId()));
		}
		return GatewayResponse.SUCCESS.newBuilder().toResult();
	}

	/**
	 * 可绑定优惠券列表
	 */
	@GetMapping("/get/available/coupon")
	public Result<List<CouponView>> getAvailableCoupon() throws Exception {
		SysConfig sysConfig = sysConfigMapper.selectOne(Wrappers.lambdaQuery(SysConfig.class).eq(SysConfig::getSysKey, Constant.COUPON_DISTRIBUTE_RELATE_COUPON_KEY)
				.last("limit 1"));
		List<Long> show_coupon_ids = null;
		if (sysConfig != null && StrUtil.isNotBlank(sysConfig.getSysValue())) {
			show_coupon_ids = Jsons.parseList(sysConfig.getSysValue(), Long.class);
		}
		if (CollUtil.isEmpty(show_coupon_ids)) {
			return GatewayResponse.SUCCESS.newBuilder().toResult();
		}
		List<CouponView> couponViews = beanSearcher.searchAll(CouponView.class, MapUtils.flatBuilder(request.getParameterMap()).field(CouponView::getCouponId, show_coupon_ids).op(Operator.InList).onlySelect(CouponView::getCouponId, CouponView::getName, CouponView::getIsValidTime, CouponView::getValidStartTime, CouponView::getValidEndTime).build());
		DateTime now = DateTime.now();
		couponViews = couponViews.stream().filter(c -> {
			if (c.getIsValidTime() && c.getValidStartTime() != null) {
				Date validStartTime = c.getValidStartTime();
				Date validEndTime = c.getValidEndTime();
				if (validStartTime.compareTo(now) <= 0 && validEndTime.compareTo(now) >= 0) {
					return true;
				}
				return false;
			}
			c.setValidStartTime(null);
			c.setValidEndTime(null);
			return true;
		}).collect(Collectors.toList());
		return GatewayResponse.SUCCESS.newBuilder().toResult(couponViews);
	}
}
