package com.cyksj.web.controller.nano;

import cn.hutool.core.date.DateTime;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.cyksj.common.constant.Constant;
import com.cyksj.common.exception.BusinessRuntimeException;
import com.cyksj.dto.Result;
import com.cyksj.dto.UserSharedDto;
import com.cyksj.enums.GatewayResponse;
import com.cyksj.mapper.manage.coupon.*;
import com.cyksj.mapper.manage.distribute.UserDistributeMapper;
import com.cyksj.model.entity.*;
import com.cyksj.model.views.GoodsDonSkuView;
import com.cyksj.model.views.NanoPackageView;
import com.cyksj.model.views.NanoUserQuotaInfoView;
import com.cyksj.service.nano.NanoService;
import com.cyksj.service.user.UserService;
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 lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

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

/**
 * server/nano推广
 * Nano推广控制器
 * 项目名: yhlxj11111111
 * 文件名: NanoController
 * 创建者: Claude Code
 * 创建时间:2025/9/4
 */
@Slf4j
@RestController
@RequestMapping("/applet/nano")
@RequiredArgsConstructor
public class NanoController {

	private final BeanSearcher beanSearcher;

	private final HttpServletRequest request;

	private final NanoService nanoService;

	private final UserService userService;

	private final UserDistributeMapper userDistributeMapper;

	private final CouponDistributePopularizeMapper couponDistributePopularizeMapper;

	private final CouponMapper couponMapper;

	private final CouponSkuMapper couponSkuMapper;

	private final CouponRecommendMapper couponRecommendMapper;

	private final CouponUserMapper couponUserMapper;

	/**
	 * 通过车票token获取用户信息
	 */
	@GetMapping("/get/user/token")
	public Result<String> getUserTokenByNanoToken(String usertoken) {
		Long userId = nanoService.getUserTokenByNanoToken(usertoken);
		if (userId == null) {
			throw BusinessRuntimeException.getInstance("车票不存在");
		}
		String userToken = StpUserUtil.getTokenValueByLoginId(userId);
		if (userToken == null) {
			StpUserUtil.login(userId);
			userToken = StpUserUtil.getTokenValue();
		}
		return GatewayResponse.SUCCESS.newBuilder().toResult(userToken);
	}


	/**
	 * 用户订阅车票信息
	 */
	@GetMapping("/get/user/subs/info")
	public Result<NanoUserQuotaInfoView> getUserSubsInfo() {
		long userId = StpUserUtil.getLoginIdAsLong();
		NanoUserQuotaInfoView nanoUserQuotaInfoView = nanoService.getUserSubsInfo(userId);
		return GatewayResponse.SUCCESS.newBuilder().toResult(nanoUserQuotaInfoView);
	}

	/**
	 * nano可选套餐
	 */
	@GetMapping("/get/packages")
	public Result<NanoPackageView> getNanoPackages(String dsCode) {
		Long userId = StpUserUtil.getUserIdAfterLogin();
		NanoPackageView nanoPackageView = new NanoPackageView();
		List<GoodsDonSkuView> goodsDonSkuViews = beanSearcher.searchAll(GoodsDonSkuView.class, MapUtils.builder()
				.field(GoodsDonSkuView::getGoodsId, Constant.NANO_GOODS_ID)
				.field(GoodsDonSkuView::getUserOwns).op(Operator.IsNull)
				.field(GoodsDonSkuView::getGoodsDonSkuStatus, Boolean.TRUE)
				.field(GoodsDonSkuView::getGoodsDonStatus, Boolean.TRUE).build());
		//渠道推广
		setNanoSkuCouponInfo(dsCode, userId, goodsDonSkuViews);
		nanoPackageView.setSkus(goodsDonSkuViews);
		return GatewayResponse.SUCCESS.newBuilder().toResult(nanoPackageView);
	}

	public void setNanoSkuCouponInfo(String dsCode, Long userId, List<GoodsDonSkuView> goodsDonSkuViews) {
		//渠道推广
		Coupon coupon = null;
		if (dsCode != null) {
			UserSharedDto popularizeDto = userService.getUserShredDtoByDsCode(dsCode);
			if (popularizeDto != null) {
				UserDistribute userDistribute = userDistributeMapper.selectOne(Wrappers.lambdaQuery(UserDistribute.class).eq(UserDistribute::getUserId, popularizeDto.getSharedId()).eq(UserDistribute::getDeleted, Boolean.TRUE).last("limit 1"));
				//渠道推广
				if (userDistribute != null) {
					// 这里需要根据实际的nano推广优惠券配置来设置
					// 假设有DISTRIBUTE_NANO_COUPON_ID和DISTRIBUTE_NANO_NO_CODE_COUPON_ID常量
					Integer selectCount = couponDistributePopularizeMapper.selectCount(Wrappers.lambdaQuery(CouponDistributePopularize.class)
							.eq(CouponDistributePopularize::getDistributeId, userDistribute.getId())
							.eq(CouponDistributePopularize::getCouponId, Constant.DISTRIBUTE_NANO_COUPON_ID)
							.eq(CouponDistributePopularize::getDeleted, Boolean.TRUE));
					//已配置使用渠道优惠码
					if (selectCount > 0) {
						coupon = couponMapper.selectById(Constant.DISTRIBUTE_NANO_COUPON_ID);
					}
				}
			}
		}
		Boolean isTjB = false;
		//不存在优惠 查找推荐优惠券
		if (coupon == null) {
			coupon = couponRecommendMapper.getRecommendCouponByGoodsId(Constant.NANO_GOODS_ID);
			isTjB = true;
		}
		if (coupon == null) {
			return;
		}
		if (isTjB) {
			int isTj = couponRecommendMapper.checkPresentRecommendByCouponId(coupon.getId());
			if (isTj == 0) {
				return;
			}
		}
		List<Long> couponSkuIds = couponSkuMapper.selectList(Wrappers.lambdaQuery(CouponSku.class).eq(CouponSku::getCouponId, coupon.getId()).eq(CouponSku::getDeleted, Boolean.TRUE)).stream().map(CouponSku::getSkuId).collect(Collectors.toList());
		//该优惠券是否已经使用
		if (userId != null) {
			Integer selectCount = couponUserMapper.selectCount(Wrappers.lambdaQuery(CouponUser.class).eq(CouponUser::getCouponId, coupon.getId()).eq(CouponUser::getUserId, userId));
			if (selectCount > 0) {
				Integer isUsed = couponUserMapper.selectCount(Wrappers.lambdaQuery(CouponUser.class)
						.eq(CouponUser::getCouponId, coupon.getId())
						.eq(CouponUser::getStatus, CouponUser.Status.unused)
						.eq(CouponUser::getUserId, userId)
						.lt(CouponUser::getValidStartTime, DateTime.now())
						.gt(CouponUser::getValidEndTime, DateTime.now()));
				if (isUsed == 0) {
					return;
				}
			}
		}
		for (GoodsDonSkuView sku : goodsDonSkuViews) {
			if (couponSkuIds.contains(sku.getSkuId())) {
				sku.setCouponId(coupon.getId());
				if (coupon.getType() == Coupon.Type.discount) {
					sku.setDiscount(coupon.getDiscount());
					sku.setDiscountPrice(sku.getMoney().multiply(coupon.getDiscount()));
				} else {
					sku.setReduceMoney(coupon.getReduceMoney());
				}
			}
		}
	}
}