package com.cyksj.service.order.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.domain.AlipayTradeWapPayModel;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cyksj.common.constant.Constant;
import com.cyksj.common.exception.BusinessRuntimeException;
import com.cyksj.common.snowflake.Sequence;
import com.cyksj.common.util.Codec;
import com.cyksj.common.util.Jsons;
import com.cyksj.config.zfb.AliPayClientFactory;
import com.cyksj.config.zfb.BaseZfbConfig;
import com.cyksj.config.zfb.ZfbProductCode;
import com.cyksj.enums.GatewayApiCode;
import com.cyksj.mapper.*;
import com.cyksj.mapper.channel.ShopConfigMapper;
import com.cyksj.mapper.sys.SysConfigMapper;
import com.cyksj.mapper.vip.VipGoodsSkuMapper;
import com.cyksj.mapper.vip.VipOrderDonDeductRelationMapper;
import com.cyksj.mapper.vip.VipOrderDonMapper;
import com.cyksj.mapper.vip.VipUserMapper;
import com.cyksj.model.dto.AliPayParams;
import com.cyksj.model.dto.VipDeductDto;
import com.cyksj.model.entity.*;
import com.cyksj.model.manage.views.GroupsRelationView;
import com.cyksj.model.request.AlipayOrderDonReq;
import com.cyksj.model.request.OrderAttach;
import com.cyksj.model.request.VipOrderDonPayReq;
import com.cyksj.redis.RedisService;
import com.cyksj.service.chatgpt.ChatGptAccountService;
import com.cyksj.service.claude.ClaudeService;
import com.cyksj.service.order.VipOrderDonService;
import com.cyksj.service.pay.AliPayCommonService;
import com.cyksj.service.relation.GroupRelationFrontService;
import com.cyksj.service.user.UserBenefitsService;
import com.cyksj.service.user.UserBindRelationService;
import com.cyksj.service.vip.VipFrontService;
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.apache.commons.lang3.StringUtils;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 项目名: yhlxj2
 * 文件名: VipOrderDonServiceImpl
 * 创建者: JavaZou
 * 创建时间:2025/5/13 11:14
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class VipOrderDonServiceImpl extends ServiceImpl<VipOrderDonMapper, VipOrderDon> implements VipOrderDonService {
	private static final Sequence SEQUENCE = new Sequence(0);

	private final UserMapper userMapper;

	private final UserBenefitsService userBenefitsService;

	private final VipUserMapper vipUserMapper;

	private final VipGoodsSkuMapper vipGoodsSkuMapper;

	private final UserBindRelationService userBindRelationService;

	private final SysConfigMapper sysConfigMapper;

	private final AliPayCommonService aliPayCommonService;

	private final ShopConfigMapper shopConfigMapper;

	private final GroupRelationFrontService groupRelationFrontService;

	private final GroupsRelationMapper relationMapper;

	private final VipFrontService vipFrontService;

	private final VipOrderDonDeductRelationMapper vipOrderDonDeductRelationMapper;

	private final BeanSearcher beanSearcher;

	private final MidjourneyUserMapper midjourneyUserMapper;

	private final ChatgptUserMapper chatgptUserMapper;

	private final ClaudeUserMapper claudeUserMapper;

	private final LumaUserMapper lumaUserMapper;

	private final GrokUserMapper grokUserMapper;

	private final RedisService redisService;

	private final GoodsDonSkuMapper skuMapper;

	private final ChatGptAccountService chatGptAccountService;

	private final ClaudeService claudeService;

	@Override
	public VipOrderDon submit(VipOrderDonPayReq payRequest) {
		Long userId = payRequest.getUserId();
		User user = userMapper.selectById(userId);
		if (user == null) throw BusinessRuntimeException.getGatewayApiCode(GatewayApiCode.CMS_TOKEN_VALID);
		if (user.getIsBlack()) throw BusinessRuntimeException.getInstance("系统检测操作异常，请稍后再试");
		/* 生成订单 */
		String donNo = SEQUENCE.nextId().toString();
		VipOrderDon orderDon = new VipOrderDon();
		orderDon.setOrderNo(donNo);
		orderDon.setOpenId(user.getOpenId());
		//获取会员价格
		VipDeductDto vipMoneyIfDeduct = getVipMoneyIfDeduct(user, payRequest.getIsDeduct());
		BigDecimal vipMoney = getVipMoney();
		payRequest.setDonMoney(vipMoney);
		if (vipMoneyIfDeduct != null) {
			payRequest.setDonMoney(vipMoney.subtract(vipMoneyIfDeduct.getDeductMoney()));
		}
		orderDon.setMoney(payRequest.getDonMoney());
		//渠道链接id
		if (payRequest.getPopularizeId() != null) {
			orderDon.setPopularizeId(payRequest.getPopularizeId());
		}
		orderDon.setStatus(VipOrderDon.Status.noPayment);
		orderDon.setUserId(user.getId());
		orderDon.setType(VipOrderDon.Type.getType(payRequest.getType()));
		orderDon.setIsWebPay(payRequest.getIsWebPay());
		//扣除使用优惠券、余额的订单金额
		deductOrderMoney(orderDon, user, payRequest);
		//设置订单支付商品信息
		orderDon.setPayTitle(Constant.VIP_TITLE);
		this.saveOrUpdate(orderDon);

		Long orderId = orderDon.getId();
		//存在抵扣 记录抵扣成功后 需清除车票的ids
		if (vipMoneyIfDeduct != null) {
			List<Long> deductRelationIds = vipMoneyIfDeduct.getDeductRelationIds();
			recordVipDeductRelationIds(orderDon.getId(), orderDon.getUserId(), deductRelationIds);
		}
		//余额支付订单
		if (orderDon.getMoney().compareTo(BigDecimal.ZERO) == 0) {
			orderDon = getById(orderId);
			unifiedHandlerOrderNotify(orderDon);
		}
		return orderDon;
	}

	@Override
	public AliPayParams aliPay(AlipayOrderDonReq re) throws Exception {
		String productCode = StrUtil.EMPTY;
		if (re.getType() == 1) {
			productCode = ZfbProductCode.MOBILE_WEB.getProductCode();
		}
		if (re.getType() == 2) {
			productCode = ZfbProductCode.PC_WEB.getProductCode();
		}
		return aliPayCommonService.unifiedPayVip(re.getOrderId(), productCode, re.getPayMode(), re.getReturnUrl());
	}

	@Override
	public void aliPayNotify(Map<String, String> params) throws Exception {
		//调用SDK验证签名
		String body = Codec.DoBase64.custom().setData(params.get("body")).decodeAsText();
		OrderAttach orderAttach = Jsons.parseObject(body, OrderAttach.class);
		Long oderId = orderAttach.getO();
		VipOrderDon orderDon = this.getById(oderId);
		if (null == orderDon) {
			throw BusinessRuntimeException.getInstance("订单不存在.");
		}
		if (orderDon.getPopularizeId() == null) {
			orderDon.setShopId(null);
		}
		String appId = params.get("app_id");
		boolean signVerified = AlipaySignature.rsaCheckV1(params, shopConfigMapper.getByAppId(appId).getPublicKey(), BaseZfbConfig.charset, BaseZfbConfig.signType);
		if (!signVerified) {
			log.error("支付宝回调校验签名错误,自定义入参:{}", params.get("body"));
			throw BusinessRuntimeException.getInstance("支付宝回调校验签名错误");
		}
		String transactionId = params.get("trade_no");
		String payTimeStr = params.get("gmt_payment");
		//买家支付宝账号
		String buyerId = Optional.ofNullable(params.get("buyer_id")).orElse(params.get("buyer_open_id"));
		log.info("支付宝回调信息:{}", Jsons.toJson(params));
		if (!orderDon.getStatus().equals(VipOrderDon.Status.noPayment) && !orderDon.getStatus().equals(VipOrderDon.Status.close)) {
			log.info("支付宝已回调，重复修改状态 id:{}", orderDon.getId());
			return;
		}
		Date payTime = DateTime.now();
		if (StringUtils.isNotBlank(payTimeStr)) {
			payTime = DateUtil.parse(payTimeStr, "yyyy-MM-dd HH:mm:ss");
		}
		// 更改订单状态
		orderDon.setTransactionId(transactionId);
		orderDon.setPayTime(payTime);
		orderDon.setShopId(appId);
		orderDon.setType(VipOrderDon.Type.ALI_PAY);
		orderDon.setBuyerId(buyerId);
		//回调
		unifiedHandlerOrderNotify(orderDon);
	}

	@Override
	public void orderNotify(VipOrderDon orderDon) {
		unifiedHandlerOrderNotify(orderDon);
	}

	@Override
	public VipOrderDon renew(VipOrderDonPayReq payRequest) {
		Long userId = payRequest.getUserId();
		User user = userMapper.selectById(userId);
		List<Long> userIdList = userBindRelationService.getRelationUserIdList(userId, user);
		Integer selectCount = vipUserMapper.selectCount(Wrappers.lambdaQuery(VipUser.class)
				.in(VipUser::getUserId, userIdList)
				.gt(VipUser::getExpiryTime, DateTime.now()));
		if (selectCount == 0) {
			throw BusinessRuntimeException.getInstance("您会员已过期，无法续费");
		}
		/* 生成订单 */
		String donNo = SEQUENCE.nextId().toString();
		VipOrderDon orderDon = new VipOrderDon();
		orderDon.setOrderNo(donNo);
		orderDon.setOpenId(user.getOpenId());
		//获取续费会员价格
		payRequest.setDonMoney(getVipMoney());
		//续费订单
		orderDon.setOrderType(2);
		orderDon.setMoney(payRequest.getDonMoney());
		//渠道链接id
		if (payRequest.getPopularizeId() != null) {
			orderDon.setPopularizeId(payRequest.getPopularizeId());
		}
		orderDon.setStatus(VipOrderDon.Status.noPayment);
		orderDon.setUserId(user.getId());
		orderDon.setType(VipOrderDon.Type.getType(payRequest.getType()));
		orderDon.setIsWebPay(payRequest.getIsWebPay());
		//扣除使用优惠券、余额的订单金额
		deductOrderMoney(orderDon, user, payRequest);
		//设置订单支付商品信息
		orderDon.setPayTitle(Constant.VIP_TITLE);

		this.saveOrUpdate(orderDon);

		Long orderId = orderDon.getId();
		//余额支付订单
		if (orderDon.getMoney().compareTo(BigDecimal.ZERO) == 0) {
			orderDon = getById(orderId);
			unifiedHandlerOrderNotify(orderDon);
		}
		return orderDon;
	}

	@Override
	public void closeOrderDon(long userId, Long orderId) {
		List<Long> userIdList = userBindRelationService.getRelationUserIdList(userId, null);
		VipOrderDon orderDon = getById(orderId);
		if (!userIdList.contains(orderDon.getUserId())) {
			throw BusinessRuntimeException.getInstance("订单错误");
		}
		if (orderDon.getStatus() != VipOrderDon.Status.noPayment) {
			throw BusinessRuntimeException.getInstance("订单状态错误");
		}
		VipOrderDon.Status status = isHasPaid(orderDon);
		if (status == VipOrderDon.Status.noPayment) {
			log.info("关闭订单 orderId:{}", orderId);
			orderDon.setStatus(VipOrderDon.Status.close);
			updateById(orderDon);
		}
	}

	private VipOrderDon.Status isHasPaid(VipOrderDon orderDon) {
		if (orderDon.getType() == VipOrderDon.Type.ALI_PAY) {
			try {
				AlipayTradeQueryResponse zfbOrderDetail = getZfbOrderDetail(orderDon.getShopId(), orderDon.getOrderNo());
				if (zfbOrderDetail != null) {
					String tradeStatus = zfbOrderDetail.getTradeStatus();
					if ("TRADE_SUCCESS".equals(tradeStatus)) {
						orderDon.setStatus(VipOrderDon.Status.complete);
						orderDon.setTransactionId(zfbOrderDetail.getTradeNo());
						Date sendPayDate = zfbOrderDetail.getSendPayDate();
						orderDon.setPayTime(sendPayDate);
						//买家支付宝账号
						String buyerId = Optional.ofNullable(zfbOrderDetail.getBuyerUserId()).orElse(zfbOrderDetail.getBuyerOpenId());
						orderDon.setBuyerId(buyerId);
						unifiedHandlerOrderNotify(orderDon);
					}
				}
			} catch (Exception e) {

			}
		}
		return orderDon.getStatus();
	}

	/**
	 * 查询支付宝订单详情
	 */
	public AlipayTradeQueryResponse getZfbOrderDetail(String shopId, String orderNo) throws AlipayApiException {
		AlipayClient alipayClient = AliPayClientFactory.getAlipayClient(shopId);
		AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
		AlipayTradeWapPayModel bizModel = new AlipayTradeWapPayModel();
		bizModel.setOutTradeNo(orderNo);
		request.setBizModel(bizModel);
		AlipayTradeQueryResponse response;
		ShopConfig shopConfig = shopConfigMapper.selectOne(Wrappers.lambdaQuery(ShopConfig.class).eq(ShopConfig::getAppId, shopId));
		if (shopConfig != null && shopConfig.getIsCert()) {
			response = alipayClient.certificateExecute(request);
		} else {
			response = alipayClient.execute(request);
		}
		if (response.isSuccess()) {
			return response;
		}
		return null;
	}

	private void unifiedHandlerOrderNotify(VipOrderDon orderDon) {
		orderDon.setStatus(VipOrderDon.Status.complete);
		this.updateById(orderDon);
		//余额使用记录
		if (orderDon.getBalance().compareTo(BigDecimal.ZERO) > 0) {
			userBenefitsService.recordBalanceBySource(orderDon.getUserId(), orderDon.getBalance().negate(), UserBalanceSourceRecord.Source.vip_order, orderDon.getId(), UserBalanceSourceRecord.Source.vip_order.getDesc(), null, null);
		}
		Long userId = orderDon.getUserId();
		//只选择一个号
		List<Long> userIdList = userBindRelationService.getRelationUserIdList(userId, null);
		VipUser vipUser = Optional.ofNullable(vipUserMapper.selectOne(Wrappers.lambdaQuery(VipUser.class)
				.in(VipUser::getUserId, userIdList)
				.last("limit 1"))).orElse(new VipUser());
		vipUser.setUserId(userId);
		//发放会员车票 普通订单
		if (orderDon.getOrderType() == 1) {
			vipUser.setStartTime(DateTime.now());
			vipUser.setExpiryTime(DateUtil.offsetMonth(vipUser.getStartTime(), 1));
			if (vipUser.getId() == null) {
				try {
					vipUserMapper.insert(vipUser);
				} catch (DuplicateKeyException e) {
				}
			} else vipUserMapper.updateById(vipUser);
			//发送车票
			sendVipTicketToUser(vipUser.getUserId(), vipUser.getExpiryTime(), userIdList, orderDon.getId());
		} else {
			//续费订单
			vipUser.setExpiryTime(DateUtil.offsetMonth(vipUser.getExpiryTime(), 1));
			vipUserMapper.updateById(vipUser);
			//续费订单
			setTicketToVipExpiryTime(userIdList, vipUser.getUserId(), vipUser.getExpiryTime());
		}
	}

	private void sendVipTicketToUser(Long userId, Date vipExpiryTime, List<Long> userIds, Long orderId) {
		//是否存在抵扣 抵扣成功 清除车票
		VipOrderDonDeductRelation vipOrderDonDeductRelation = vipOrderDonDeductRelationMapper.selectOne(Wrappers.lambdaQuery(VipOrderDonDeductRelation.class)
				.eq(VipOrderDonDeductRelation::getOrderId, orderId)
				.last("limit 1"));
		List<Long> deductRelationIds = null;
		if (vipOrderDonDeductRelation != null) {
			try {
				deductRelationIds = Jsons.parseList(vipOrderDonDeductRelation.getRelationIds(), Long.class);
				vipOrderDonDeductRelation.setStatus(true);
				vipOrderDonDeductRelationMapper.updateById(vipOrderDonDeductRelation);
			} catch (Exception e) {
			}
		}
		List<VipGoodsSku> skus = vipGoodsSkuMapper.selectList(null);
		List<Long> deductSkuIds = null;
		if (CollUtil.isNotEmpty(deductRelationIds)) {
			List<GroupsRelationView> groupsRelationViews = beanSearcher.searchAll(GroupsRelationView.class, MapUtils.builder()
					.field(GroupsRelationView::getUserId, userIds).op(Operator.InList)
					.field(GroupsRelationView::getId, deductRelationIds).op(Operator.InList).build());
			deductSkuIds = groupsRelationViews.stream().map(GroupsRelationView::getSkuId).collect(Collectors.toList());
			//将车票弄成会员类型
			relationMapper.update(null, Wrappers.lambdaUpdate(GroupsRelation.class)
					.set(GroupsRelation::getIsVip, Boolean.TRUE)
					.in(GroupsRelation::getUserId, userIds)
					.in(GroupsRelation::getId, deductRelationIds));
			//重置镜像user
			resetMirrorUser(groupsRelationViews, vipExpiryTime);
		}
		for (VipGoodsSku sku : skus) {
			//未有抵扣 直接发送会员车票
			if (deductSkuIds == null || !deductSkuIds.contains(sku.getSkuId())) {
				groupRelationFrontService.getTicket(userId, sku.getSkuId(), Boolean.TRUE);
			}
		}
	}

	private void deductOrderMoney(VipOrderDon orderDon, User user, VipOrderDonPayReq payRequest) {
		BigDecimal balance = payRequest.getBalance();
		//存在余额
		deductBalancePayOrderMoney(orderDon, balance, user);
	}

	private VipDeductDto getVipMoneyIfDeduct(User user, Boolean isDeduct) {
		//若用户抵扣
		if (isDeduct) {
			return vipFrontService.checkAndGetOrderDeductMoney(user.getId());
		}
		return null;
	}

	public void deductBalancePayOrderMoney(VipOrderDon orderDon, BigDecimal balance, User user) {
		//存在余额
		if (balance != null && balance.compareTo(BigDecimal.ZERO) > 0) {
			BigDecimal money = orderDon.getMoney();
			//去掉余额 多出的部分
			BigDecimal subBalance = balance;
			orderDon.setMoney(money.subtract(subBalance));
			if (balance.compareTo(money) >= 0) {
				orderDon.setMoney(BigDecimal.ZERO);
				orderDon.setBalance(money);
				subBalance = money;
				orderDon.setType(VipOrderDon.Type.BALANCE);
			}
			BigDecimal userBalance = user.getBalance();
			//扣除余额 是否成功
			Integer success = userMapper.deductBalance(user.getId(), subBalance, userBalance);
			if (success != 1) throw BusinessRuntimeException.getInstance("您的余额不足!");
			orderDon.setBalance(subBalance);
		}
	}

	/**
	 * 设置会员车票同一过期时间
	 */
	private void setTicketToVipExpiryTime(List<Long> userIds, Long vipUserId, Date expiryTime) {
		List<Long> vipSkuIds = vipGoodsSkuMapper.selectList(null).stream().map(VipGoodsSku::getSkuId).collect(Collectors.toList());
		List<Long> selfSkuIds = beanSearcher.searchAll(GroupsRelationView.class, MapUtils.builder()
				.field(GroupsRelationView::getUserId, userIds).op(Operator.InList)
				.field(GroupsRelationView::getSkuId, vipSkuIds).op(Operator.InList)
				.field(GroupsRelationView::getIsVip, true)
				.onlySelect(GroupsRelationView::getSkuId)
				.build()).stream().map(GroupsRelationView::getSkuId).collect(Collectors.toList());
		if (selfSkuIds.size() != vipSkuIds.size()) {
			vipSkuIds.forEach(vipSkuId->{
				if (!selfSkuIds.contains(vipSkuId)) {
					//发送 缺少的规格
					groupRelationFrontService.getTicket(vipUserId, vipSkuId, Boolean.TRUE);
				}
			});
		}
		relationMapper.update(null, Wrappers.lambdaUpdate(GroupsRelation.class)
				.set(GroupsRelation::getExpiryTime, expiryTime)
				.set(GroupsRelation::getUpdateTime, DateTime.now())
				.in(GroupsRelation::getUserId, userIds)
				.eq(GroupsRelation::getStatus, GroupsRelation.Status.validity)
				.eq(GroupsRelation::getIsVip, Boolean.TRUE));
	}

	private BigDecimal getVipMoney() {
		SysConfig sysConfig = sysConfigMapper.selectOne(Wrappers.lambdaQuery(SysConfig.class)
				.eq(SysConfig::getSysKey, Constant.VIP_FEE_KEY)
				.last("limit 1"));
		if (sysConfig == null || StrUtil.isEmpty(sysConfig.getSysValue())) {
			throw BusinessRuntimeException.getInstance("系统异常");
		}
		BigDecimal vipFee = BigDecimal.valueOf(Long.valueOf(sysConfig.getSysValue()));
		return vipFee;
	}

	private void recordVipDeductRelationIds(Long orderId, Long userId, List<Long> deductRelationIds) {
		VipOrderDonDeductRelation vipOrderDonDeductRelation = new VipOrderDonDeductRelation();
		vipOrderDonDeductRelation.setOrderId(orderId);
		vipOrderDonDeductRelation.setUserId(userId);
		vipOrderDonDeductRelation.setRelationIds(deductRelationIds.toString());
		vipOrderDonDeductRelationMapper.insert(vipOrderDonDeductRelation);
	}

	/**
	 * 重置镜像user
	 */
	private void resetMirrorUser(List<GroupsRelationView> groupsRelationViews, Date vipExpiryTime) {
		for (GroupsRelationView groupsRelationView : groupsRelationViews) {
			Long skuId = groupsRelationView.getSkuId();
			Long goodsId = groupsRelationView.getGoodsId();
			Long relationId = groupsRelationView.getId();
			GoodsDonSku sku = skuMapper.selectById(skuId);
			if (goodsId == Constant.MJ_GID) {
				MidjourneyUser user = midjourneyUserMapper.selectOne(Wrappers.lambdaQuery(MidjourneyUser.class)
						.eq(MidjourneyUser::getRelationId, relationId)
						.last("limit 1"));
				if (user != null) {
					user.setMjFastNum(sku.getMjFastNum());
					user.setMjRelaxNum(sku.getMjRelaxNum());
					user.setIsVip(Boolean.TRUE);
					user.setExpireTime(vipExpiryTime);
					midjourneyUserMapper.updateById(user);
					redisService.del(RedisService.key.MIDJOURNEY_USER.getName() + user.getUserToken());
				}
			}
			if (goodsId == Constant.GPT_PLUS_GID) {
				ChatgptUser chatgptUser = chatgptUserMapper.selectOne(Wrappers.lambdaQuery(ChatgptUser.class)
						.eq(ChatgptUser::getRelationId, relationId)
						.last("limit 1"));
				if (chatgptUser != null) {
					chatgptUser.setLimitNum(sku.getGptLimitNum());
					chatgptUser.setLimitTime(sku.getGptLimitTime());
					chatgptUser.setDsLimitNum(sku.getDsLimitNum());
					chatgptUser.setDsLimitTime(sku.getDsLimitTime());
					chatgptUser.setOtherLimitNum(sku.getOtherLimitNum());
					chatgptUser.setOtherLimitTime(sku.getOtherLimitTime());
					chatgptUser.setPackageId(0l);
					chatgptUser.setClearPackageTime(null);
					chatgptUser.setRenewOrderId(0l);
					chatgptUser.setRenewSkuId(null);
					chatgptUser.setRenewExpiryTime(null);
					chatgptUser.setIsVip(Boolean.TRUE);
					chatgptUser.setExpireTime(vipExpiryTime);
					chatgptUserMapper.updateById(chatgptUser);
					try {
						//清除次数
						chatGptAccountService.clearGptNum(relationId);
					} catch (Exception e) {
					}
				}
			}
			if (goodsId == Constant.CALUDE_GOODS_ID) {
				ClaudeUser claudeUser = claudeUserMapper.selectOne(Wrappers.lambdaQuery(ClaudeUser.class)
						.eq(ClaudeUser::getRelationId, relationId)
						.last("limit 1"));
				if (claudeUser != null) {
					claudeUser.setLimitNum(sku.getGptLimitNum());
					claudeUser.setLimitTime(sku.getGptLimitTime());
					claudeUser.setRenewOrderId(null);
					claudeUser.setRenewExpiryTime(null);
					claudeUser.setRenewSkuId(null);
					claudeUser.setIsVip(Boolean.TRUE);
					claudeUser.setExpireTime(vipExpiryTime);
					claudeUserMapper.updateById(claudeUser);
					try {
						//清除次数
						claudeService.clearNum(claudeUser.getUserToken());
					} catch (Exception e) {
					}
				}
			}
			if (goodsId == Constant.GROK_GOODS_ID) {
				GrokUser grokUser = grokUserMapper.selectOne(Wrappers.lambdaQuery(GrokUser.class)
						.eq(GrokUser::getRelationId, relationId)
						.last("limit 1"));
				if (grokUser != null) {
					grokUser.setLimitNum(sku.getGptLimitNum());
					grokUser.setLimitTime(sku.getGptLimitTime());
					grokUser.setIsVip(Boolean.TRUE);
					grokUser.setExpireTime(vipExpiryTime);
					grokUserMapper.updateById(grokUser);
				}
			}
			if (goodsId == Constant.LUMA_GOODS_ID) {
				LumaUser lumaUser = lumaUserMapper.selectOne(Wrappers.lambdaQuery(LumaUser.class)
						.eq(LumaUser::getRelationId, relationId)
						.last("limit 1"));
				if (lumaUser != null) {
					lumaUser.setNum(sku.getLumaNum());
					lumaUser.setIsVip(Boolean.TRUE);
					lumaUser.setExpireTime(vipExpiryTime);
					lumaUserMapper.updateById(lumaUser);
					redisService.del(RedisService.key.LUMA_NUM_LIMIT.getName() + lumaUser.getId());
				}
			}
		}
	}
}
