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.lang.Assert;
import cn.hutool.core.util.StrUtil;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.cyksj.common.EnvCommonService;
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.common.util.SmsUtil;
import com.cyksj.common.util.StringUtil;
import com.cyksj.config.zfb.BaseZfbConfig;
import com.cyksj.mapper.*;
import com.cyksj.mapper.channel.ShopConfigMapper;
import com.cyksj.mapper.sys.SysConfigMapper;
import com.cyksj.model.dto.AliPayParams;
import com.cyksj.model.dto.GoodsWholesaleUserDepositDto;
import com.cyksj.model.entity.*;
import com.cyksj.model.request.AlipayOrderDonReq;
import com.cyksj.model.request.GoodsWholesaleOrderPayReq;
import com.cyksj.model.request.OrderAttach;
import com.cyksj.model.views.GoodsWholesaleOrderDonView;
import com.cyksj.model.views.GoodsWholesaleUserDepositView;
import com.cyksj.service.order.GoodsWholesalePayService;
import com.cyksj.service.order.OrderDonService;
import com.cyksj.service.order.OrderRefundService;
import com.cyksj.service.pay.AliPayCommonService;
import com.cyksj.service.user.UserBenefitsService;
import com.cyksj.service.user.UserBindRelationService;
import com.cyksj.service.wechat.WeChatService;
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.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;

/**
 * 项目名: yhlxj
 * 文件名: GoodsWholesalePayServiceImpl
 * 创建者: JavaZou
 * 创建时间:2024/8/26 18:43
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class GoodsWholesalePayServiceImpl implements GoodsWholesalePayService {
	private final GoodsWholesaleOrderDonMapper goodsWholesaleOrderDonMapper;

	private final UserBindRelationService userBindRelationService;

	private final GoodsWholesaleMapper goodsWholesaleMapper;

	private final GoodsDonSkuMapper skuMapper;

	private static final Sequence SEQUENCE = new Sequence(0);

	private final AliPayCommonService aliPayCommonService;

	private final ShopConfigMapper shopConfigMapper;

	private final GoodsWholesaleUserReturnRecordMapper goodsWholesaleUserReturnRecordMapper;

	private final SysConfigMapper sysConfigMapper;

	private final GoodsWholesaleUserDepositMapper depositMapper;

	private final OrderRefundService orderRefundService;

	private final UserBenefitsService userBenefitsService;

	private final UserMapper userMapper;

	private final BeanSearcher beanSearcher;

	private final OrderDonService orderDonService;

	private final WeChatService weChatService;

	private final GoodsDonMapper goodsDonMapper;

	private final GoodsWholesaleUserSkuPayRecordMapper goodsWholesaleUserSkuPayRecordMapper;

	private final EnvCommonService envCommonService;

	@Override
	public GoodsWholesaleOrderDon unifiedPay(GoodsWholesaleOrderPayReq payReq) throws Exception {
		Long userId = payReq.getUserId();
		Long id = payReq.getId();
		GoodsWholesale goodsWholesale = goodsWholesaleMapper.selectById(id);
		Assert.notNull(goodsWholesale, "商品不存在");

		if (!goodsWholesale.getStatus()) {
			Assert.notNull(goodsWholesale, "商品已下架");
		}
		if (!goodsWholesale.getDeleted()) {
			throw BusinessRuntimeException.getInstance("商品不存在");
		}
		List<Long> userIdList = userBindRelationService.getRelationUserIdList(userId, null);
		Integer selectCount = goodsWholesaleOrderDonMapper.selectCount(Wrappers.lambdaQuery(GoodsWholesaleOrderDon.class)
				.eq(GoodsWholesaleOrderDon::getSkuId, goodsWholesale.getSkuId())
				.in(GoodsWholesaleOrderDon::getUserId, userIdList)
				.eq(GoodsWholesaleOrderDon::getStatus, GoodsWholesaleOrderDon.Status.noPayment));
		if (selectCount > 0) {
			throw BusinessRuntimeException.getInstance("已有待支付订单");
		}
		GoodsDonSku sku = skuMapper.selectById(goodsWholesale.getSkuId());
		if (sku == null) {
			throw BusinessRuntimeException.getInstance("规格不存在");
		}
		if (!sku.getStatus()) {
			throw BusinessRuntimeException.getInstance("规格已下架");
		}
		GoodsWholesaleOrderDon orderDon = new GoodsWholesaleOrderDon();
		//设置订单金额
		getNeedPaySinglePrice(orderDon, sku, payReq.getNum(), goodsWholesale, userIdList);
		User user = userMapper.selectById(userId);
		BigDecimal balance = payReq.getBalance();
		orderDon.setUserId(userId);
		orderDon.setGoodsId(goodsWholesale.getGoodsId());
		orderDon.setSkuId(goodsWholesale.getSkuId());
		//批发id
		orderDon.setPid(id);
		String orderNo = SEQUENCE.nextId().toString();
		orderDon.setOrderNo(orderNo);
		orderDon.setStatus(GoodsWholesaleOrderDon.Status.noPayment);
		orderDon.setNum(payReq.getNum());
		if (balance != null) {
			deductBalancePayOrderMoney(orderDon, balance, user);
		}
		//余额支付
		if (orderDon.getMoney().compareTo(BigDecimal.ZERO) == 0) {
			orderDon.setStatus(GoodsWholesaleOrderDon.Status.hasPayment);
			orderDon.setType(GoodsWholesaleOrderDon.Type.BALANCE);
			orderDon.setPayTime(DateTime.now());
		}
		orderDon.setType(GoodsWholesaleOrderDon.Type.ALI_PAY);
		goodsWholesaleOrderDonMapper.insert(orderDon);
		//是否需要记录差价
		if (orderDon.getIsRecordDiffer()) {
			//记录此时购买该级别的数量 返差价
			recordUserPaySkuDifferPrice(orderDon);
		}
		//已支付回调
		if (orderDon.getStatus() == GoodsWholesaleOrderDon.Status.hasPayment) {
			//处理批发订单回调
			unifiedHandleGoodsWholesaleOrderDon(orderDon);
		}
		return orderDon;
	}

	private void recordUserPaySkuDifferPrice(GoodsWholesaleOrderDon orderDon) {
		GoodsWholesaleUserSkuPayRecord skuPayRecord = new GoodsWholesaleUserSkuPayRecord();
		skuPayRecord.setSkuId(orderDon.getSkuId());
		skuPayRecord.setGoodsId(orderDon.getGoodsId());
		skuPayRecord.setNum(orderDon.getNum());
		BigDecimal totalMoney = orderDon.getMoney().add(Optional.ofNullable(orderDon.getBalance()).orElse(BigDecimal.ZERO));
		BigDecimal single = totalMoney.divide(BigDecimal.valueOf(orderDon.getNum()));
		skuPayRecord.setSingle(single);
		skuPayRecord.setOrderId(orderDon.getId());
		skuPayRecord.setUserId(orderDon.getUserId());
		goodsWholesaleUserSkuPayRecordMapper.insert(skuPayRecord);
	}

	@Override
	public AliPayParams aliPayWholesale(AlipayOrderDonReq re, String productCode, String qrPayMode) throws Exception {
		if (re.getIsDeposit()) {
			return aliPayCommonService.aliPayUnifiedWholesaleDeposit(re, productCode, qrPayMode);
		}
		return aliPayCommonService.aliPayUnifiedWholesale(re, productCode, qrPayMode);
	}

	@Override
	public AliPayParams zfbWholesaleWebQrCode(AlipayOrderDonReq re, String productCode, String qrPayMode) throws Exception {
		if (re.getIsDeposit()) {
			return aliPayCommonService.aliPayUnifiedWholesaleDeposit(re, productCode, qrPayMode);
		}
		return aliPayCommonService.aliPayUnifiedWholesale(re, productCode, qrPayMode);
	}

	@Override
	public void aliPayWholesaleNotify(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();
		String orderNo = params.get("out_trade_no");
		GoodsWholesaleOrderDon orderDon = goodsWholesaleOrderDonMapper.selectOne(Wrappers.lambdaQuery(GoodsWholesaleOrderDon.class)
				.eq(GoodsWholesaleOrderDon::getOrderNo, orderNo)
				.last("limit 1"));
		if (null == orderDon) {
			throw BusinessRuntimeException.getInstance("订单不存在.");
		}
		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(GoodsWholesaleOrderDon.Status.noPayment) && !orderDon.getStatus().equals(GoodsWholesaleOrderDon.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.setStatus(GoodsWholesaleOrderDon.Status.hasPayment);
		orderDon.setTransactionId(transactionId);
		orderDon.setPayTime(payTime);
		orderDon.setShopId(appId);
		orderDon.setType(GoodsWholesaleOrderDon.Type.ALI_PAY);
		orderDon.setBuyerId(buyerId);
		goodsWholesaleOrderDonMapper.updateById(orderDon);
		//处理批发订单回调
		unifiedHandleGoodsWholesaleOrderDon(orderDon);
	}

	private void returnWholesaleBalanceDiffer(GoodsWholesaleOrderDon orderDon, List<Long> userIdList) throws Exception {
		//批发补差价
		Long skuId = orderDon.getSkuId();
		GoodsWholesale goodsWholesale = goodsWholesaleMapper.selectOne(Wrappers.lambdaQuery(GoodsWholesale.class)
				.eq(GoodsWholesale::getSkuId, skuId)
				.eq(GoodsWholesale::getDeleted, 1)
				.eq(GoodsWholesale::getStatus, 1)
				.last("limit 1"));
		if (goodsWholesale != null && goodsWholesale.getIsReturn()) {
			//目前购买多少个
			Integer payNum = goodsWholesaleOrderDonMapper.getUserWholesaleNumByUserIds(userIdList, orderDon.getSkuId());
			log.info("目前用户userId:{}购买批发数量:{}", orderDon.getUserId(), payNum);
			List<GoodsWholesale.GoodsWholesaleConfig> configs = Jsons.parseList(goodsWholesale.getConfig(), GoodsWholesale.GoodsWholesaleConfig.class);
			if (configs.size() == 1) {
				return;
			}
			GoodsWholesale.GoodsWholesaleConfig firstConfig = configs.get(0);
			GoodsWholesale.GoodsWholesaleConfig endConfig = configs.get(configs.size() - 1);
			//未超过第一档
			if (payNum <= firstConfig.getEnd()) {
				return;
			}
			configs.remove(endConfig);
			GoodsWholesaleUserReturnRecord goodsWholesaleUserReturnRecord = goodsWholesaleUserReturnRecordMapper.selectGoodsWholeReturnBalanceRecordByUserId(userIdList, skuId);
			if (goodsWholesaleUserReturnRecord != null) {
				log.info("用户:{}之前已返差价", orderDon.getUserId());
				return;
			}
			//最高
			if (payNum >= endConfig.getStart()) {
				BigDecimal returnBalance = BigDecimal.ZERO;
				List<GoodsWholesaleUserSkuPayRecord> userHasPaySkuDifferRecord = goodsWholesaleUserSkuPayRecordMapper.selectUserHasPaySkuDifferRecord(userIdList, skuId);
				if (CollUtil.isEmpty(userHasPaySkuDifferRecord)) {
					log.info("用户:{}无skuId:{}返差价的数量", orderDon.getUserId(), orderDon.getSkuId());
					return;
				}
				BigDecimal endConfigSingle = endConfig.getSingle();
				for (GoodsWholesaleUserSkuPayRecord skuPayRecord : userHasPaySkuDifferRecord) {
					Integer num = skuPayRecord.getNum();
					BigDecimal thisLevelSingle = skuPayRecord.getSingle();
					returnBalance = returnBalance.add(thisLevelSingle.subtract(endConfigSingle).multiply(BigDecimal.valueOf(num)));
				}
				try {
					log.info("用户:{}批发返skuId:{}差价", orderDon.getUserId(), skuId);
					GoodsWholesaleUserReturnRecord newRecord = new GoodsWholesaleUserReturnRecord();
					newRecord.setNum(endConfig.getStart() - 1);
					newRecord.setGoodsId(orderDon.getGoodsId());
					newRecord.setSkuId(orderDon.getSkuId());
					newRecord.setReturnBalance(returnBalance);
					newRecord.setUserId(orderDon.getUserId());
					goodsWholesaleUserReturnRecordMapper.insert(newRecord);
					//返余额差价
					userBenefitsService.addUserBalance(orderDon.getUserId(), returnBalance, UserBalanceSourceRecord.Source.wholesale_differ, 0l, orderDon.getId(), UserBalanceSourceRecord.Source.wholesale_differ.getDesc(), true);
				} catch (Exception e) {
					log.error("返用户:{}差价错误：{}", orderDon.getUserId(), StringUtil.getErrorText(e));
				}
			}
		}
	}

	@Override
	public GoodsWholesaleUserDeposit submitDeposit(Long userId) throws Exception {
		//是否已支付押金
		List<Long> userIdList = userBindRelationService.getRelationUserIdList(userId, null);

		GoodsWholesaleUserDeposit deposit = depositMapper.selectOne(Wrappers.lambdaQuery(GoodsWholesaleUserDeposit.class).in(GoodsWholesaleUserDeposit::getUserId, userIdList));
		if (deposit != null && deposit.getStatus() == GoodsWholesaleUserDeposit.Status.hasPayment) {
			throw BusinessRuntimeException.getInstance("您已支付过押金");
		}

		if (deposit == null) {
			deposit = new GoodsWholesaleUserDeposit();
			deposit.setUserId(userId);
			String orderNo = SEQUENCE.nextId().toString();
			deposit.setOrderNo(orderNo);
			deposit.setType(GoodsWholesaleUserDeposit.Type.ALI_PAY);
		}
		deposit.setStatus(GoodsWholesaleUserDeposit.Status.noPayment);
		SysConfig sysConfig = sysConfigMapper.selectOne(Wrappers.lambdaQuery(SysConfig.class)
				.eq(SysConfig::getSysKey, Constant.WHOLESALE_DEPOSIT_KEY)
				.last("limit 1"));
		if (sysConfig == null || StrUtil.isEmpty(sysConfig.getSysValue())) {
			throw BusinessRuntimeException.getInstance("未配置押金，请联系客服");
		}
		GoodsWholesaleUserDepositDto goodsWholesaleUserDepositDto = Jsons.parseObject(sysConfig.getSysValue(), GoodsWholesaleUserDepositDto.class);
		deposit.setMoney(goodsWholesaleUserDepositDto.getDeposit());

		if (deposit.getId() == null) {
			depositMapper.insert(deposit);
		} else {
			if (StrUtil.isNotBlank(deposit.getRefundOutNo())) {
				deposit.setOrderNo(SEQUENCE.nextId().toString());
			}
			depositMapper.updateById(deposit);
		}
		return deposit;
	}

	@Override
	public void aliPayWholesaleDepositNotify(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();
		GoodsWholesaleUserDeposit orderDon = depositMapper.selectById(oderId);
		if (null == orderDon) {
			throw BusinessRuntimeException.getInstance("订单不存在.");
		}
		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(GoodsWholesaleUserDeposit.Status.noPayment)) {
			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.setStatus(GoodsWholesaleUserDeposit.Status.hasPayment);
		orderDon.setTransactionId(transactionId);
		orderDon.setPayTime(payTime);
		orderDon.setShopId(appId);
		orderDon.setType(GoodsWholesaleUserDeposit.Type.ALI_PAY);
		orderDon.setBuyerId(buyerId);
		orderDon.setRefundOutNo(StrUtil.EMPTY);
		depositMapper.updateById(orderDon);
	}

	@Override
	public void closeWholesaleOrder(Long orderId, long userId) throws Exception {
		List<Long> userIdList = userBindRelationService.getRelationUserIdList(userId, null);
		GoodsWholesaleOrderDon orderDon = goodsWholesaleOrderDonMapper.selectOne(Wrappers.lambdaQuery(GoodsWholesaleOrderDon.class)
				.eq(GoodsWholesaleOrderDon::getId, orderId)
				.in(GoodsWholesaleOrderDon::getUserId, userIdList)
				.last("limit 1"));
		if (orderDon == null) {
			return;
		}
		if (orderDon.getStatus() != GoodsWholesaleOrderDon.Status.noPayment) {
			return;
		}
		orderDon.setStatus(GoodsWholesaleOrderDon.Status.close);
		GoodsWholesaleOrderDon.Status hasPaid = isHasPaid(orderDon);
		if (hasPaid == GoodsWholesaleOrderDon.Status.hasPayment) {
			unifiedHandleGoodsWholesaleOrderDon(orderDon);
		}
		goodsWholesaleOrderDonMapper.updateById(orderDon);
	}

	@Override
	public Object getOrderStatus(Long userId, Integer type, Long orderId) {
		List<Long> userIdList = userBindRelationService.getRelationUserIdList(userId, null);
		if (type == 1) {
			GoodsWholesaleUserDepositView goodsWholesaleUserDepositView = beanSearcher.searchFirst(GoodsWholesaleUserDepositView.class, MapUtils.builder().field(GoodsWholesaleUserDepositView::getUserId, userIdList).op(Operator.InList).build());
			if (goodsWholesaleUserDepositView != null) {
				goodsWholesaleUserDepositView.setIsDeposit(true);
			}
			return goodsWholesaleUserDepositView;
		}
		GoodsWholesaleOrderDonView orderDon = beanSearcher.searchFirst(GoodsWholesaleOrderDonView.class, MapUtils.builder().field(GoodsWholesaleOrderDonView::getUserId, userIdList).op(Operator.InList)
				.field(GoodsWholesaleOrderDonView::getOrderId, orderId).build());
		if (orderDon != null) {
			orderDon.setIsDeposit(false);
		}
		return orderDon;
	}


	/**
	 * 退还押金
	 */
	public void returnDeposit(GoodsWholesaleOrderDon orderDon, List<Long> userIdList) throws Exception {
		GoodsWholesaleUserDeposit goodsWholesaleUserDeposit = depositMapper.selectOne(Wrappers.lambdaQuery(GoodsWholesaleUserDeposit.class)
				.in(GoodsWholesaleUserDeposit::getUserId, userIdList)
				.eq(GoodsWholesaleUserDeposit::getStatus, GoodsWholesaleUserDeposit.Status.hasPayment)
				.last("limit 1"));
		if (goodsWholesaleUserDeposit != null) {
			//是否已满足 批发足够账号
			SysConfig sysConfig = sysConfigMapper.selectOne(Wrappers.lambdaQuery(SysConfig.class)
					.eq(SysConfig::getSysKey, Constant.WHOLESALE_DEPOSIT_KEY)
					.last("limit 1"));
			if (sysConfig == null || StrUtil.isEmpty(sysConfig.getSysValue())) {
				log.error("押金配置已失效");
				return;
			}
			GoodsWholesaleUserDepositDto goodsWholesaleUserDepositDto = Jsons.parseObject(sysConfig.getSysValue(), GoodsWholesaleUserDepositDto.class);
			Integer num = goodsWholesaleUserDepositDto.getNum();
			Integer payNum = goodsWholesaleOrderDonMapper.getUserWholesaleNumByUserIds(userIdList, null);
			if (payNum >= num) {
				//腿还押金
				try {
					String outNo = orderRefundService.refundWholesaleUserDeposit(goodsWholesaleUserDeposit);
					goodsWholesaleUserDeposit.setRefundOutNo(outNo);
					goodsWholesaleUserDeposit.setStatus(GoodsWholesaleUserDeposit.Status.refund);
					//批发数量已达
					goodsWholesaleUserDeposit.setIsGoal(true);
					depositMapper.updateById(goodsWholesaleUserDeposit);
				} catch (Exception e) {
					log.info("押金退款错误:{}", StringUtil.getErrorText(e));
				}
			}
		}
	}

	private void getNeedPaySinglePrice(GoodsWholesaleOrderDon orderDon, GoodsDonSku sku, Integer thisPayNum, GoodsWholesale goodsWholesale, List<Long> userIdList) throws Exception {
		//是否交过押金
		GoodsWholesaleUserDeposit deposit = depositMapper.selectOne(Wrappers.lambdaQuery(GoodsWholesaleUserDeposit.class)
				.in(GoodsWholesaleUserDeposit::getUserId, userIdList)
				.last("limit 1"));
		//未支付押金 或批发数量未达到且已退款 使用规格单价
		if (deposit == null || (!deposit.getIsGoal() && deposit.getStatus() == GoodsWholesaleUserDeposit.Status.refund)) {
			orderDon.setMoney(BigDecimal.valueOf(thisPayNum).multiply(sku.getPrice()));
			return;
		}
		String configStr = goodsWholesale.getConfig();
		List<GoodsWholesale.GoodsWholesaleConfig> configs = Jsons.parseList(configStr, GoodsWholesale.GoodsWholesaleConfig.class);
		GoodsWholesale.GoodsWholesaleConfig firstConfig = configs.get(0);
		Integer hasPaidNum = goodsWholesaleOrderDonMapper.getUserWholesaleNumByUserIds(userIdList, goodsWholesale.getSkuId());
		Integer endPayNum = hasPaidNum + thisPayNum;
		//未超过第一档
		if (endPayNum <= firstConfig.getEnd()) {
			orderDon.setIsRecordDiffer(true);
			orderDon.setMoney(BigDecimal.valueOf(thisPayNum).multiply(firstConfig.getSingle()));
			return;
		}
		if (configs.size() == 1) {
			throw BusinessRuntimeException.getInstance("您已无法批发下单该规格");
		}
		GoodsWholesale.GoodsWholesaleConfig endConfig = configs.get(configs.size() - 1);
		//超过最后
		if (endPayNum >= endConfig.getStart()) {
			orderDon.setMoney(BigDecimal.valueOf(thisPayNum).multiply(endConfig.getSingle()));
			return;
		}
		if (endConfig.getEnd().intValue() != 999 && endPayNum > endConfig.getEnd()) {
			throw BusinessRuntimeException.getInstance("您已超过购买该规格批发数量");
		}
		Optional<GoodsWholesale.GoodsWholesaleConfig> first = configs.stream().filter(config -> config.getStart() <= endPayNum && config.getEnd() >= endPayNum).collect(Collectors.toList()).stream().findFirst();
		GoodsWholesale.GoodsWholesaleConfig thisLevel = first.get();
		BigDecimal single = thisLevel.getSingle();
		BigDecimal needPayMoney = BigDecimal.valueOf(thisPayNum).multiply(single);
		orderDon.setMoney(needPayMoney);
		//是否需要记录差价
		orderDon.setIsRecordDiffer(true);


//		//之前的
//		List<GoodsWholesale.GoodsWholesaleConfig> before = configs.stream().filter(config -> config.getEnd() < finalLevel.getStart() && config.getEnd() > hasPaidNum).collect(Collectors.toList());
//		BigDecimal finalPayMoney = BigDecimal.ZERO;
//		Integer finalLevelPayNum = thisPayNum;
//		Integer beforeHasPayNum = hasPaidNum;
//		for (GoodsWholesale.GoodsWholesaleConfig goodsWholesaleConfig : before) {
//			Integer thisLevelPayNum = goodsWholesaleConfig.getEnd() - beforeHasPayNum;
//			beforeHasPayNum = goodsWholesaleConfig.getEnd();
//			finalPayMoney = finalPayMoney.add(BigDecimal.valueOf(thisLevelPayNum).multiply(goodsWholesaleConfig.getSingle()));
//			finalLevelPayNum -= thisLevelPayNum;
//		}
//		if (finalLevelPayNum > 0) {
//			finalPayMoney = finalPayMoney.add(BigDecimal.valueOf(finalLevelPayNum).multiply(finalLevel.getSingle()));
//		}
//		orderDon.setMoney(finalPayMoney);
	}

	/**
	 * 统一处理批发订单回调
	 */
	public void unifiedHandleGoodsWholesaleOrderDon(GoodsWholesaleOrderDon orderDon) throws Exception {
		List<Long> userIdList = userBindRelationService.getRelationUserIdList(orderDon.getUserId(), null);
		//退还押金
		returnDeposit(orderDon, userIdList);
		//返批发余额差价
		returnWholesaleBalanceDiffer(orderDon, userIdList);

		//余额使用记录
		if (orderDon.getBalance() != null && orderDon.getBalance().compareTo(BigDecimal.ZERO) > 0) {
			Long goodsId = orderDon.getGoodsId();
			GoodsDon goodsDon = goodsDonMapper.selectById(goodsId);
			userBenefitsService.recordBalanceBySource(orderDon.getUserId(), orderDon.getBalance().negate(), UserBalanceSourceRecord.Source.wholesale_order, orderDon.getId(), goodsDon.getTitle() + UserBalanceSourceRecord.Source.wholesale_order.getDesc(), null, null);
		}
		try {
			//发送短信给新科
			User user = userMapper.selectById(orderDon.getUserId());
			Integer num = orderDon.getNum();
			GoodsDon goodsDon = goodsDonMapper.selectById(orderDon.getGoodsId());
			GoodsDonSku sku = skuMapper.selectById(orderDon.getSkuId());
			List<String> phones = List.of("18260166919");
			if (envCommonService.isPrdEnv()) {
				phones = Constant.GOODS_WHOLESALE_PHONE;
			}
			String msg = String.format(Constant.GOODS_WHOLESALE_MSG, user.getNickname(), num, goodsDon.getTitle() + sku.getSpecVal());
			log.info("批发通知短信内容：{}", msg);
			SmsUtil.batchSendLuoKey2Msg(phones, msg);
		} catch (Exception e) {
			log.error("发送批发通知短信失败:{}", StringUtil.getErrorText(e));
		}
	}
	/**
	 * 扣除余额
	 */
	public void deductBalancePayOrderMoney(GoodsWholesaleOrderDon 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(GoodsWholesaleOrderDon.Type.BALANCE);
			}
			BigDecimal userBalance = user.getBalance();
			//扣除余额 是否成功
			Integer success = userMapper.deductBalance(user.getId(), subBalance, userBalance);
			if (success != 1) throw BusinessRuntimeException.getInstance("您的余额不足!");
			orderDon.setBalance(subBalance);
		}
	}

	public GoodsWholesaleOrderDon.Status isHasPaid(GoodsWholesaleOrderDon orderDon) {
		if (orderDon.getType() == GoodsWholesaleOrderDon.Type.WeChat) {
			try {
				Map<String, String> reMap = weChatService.getWxOrderDetail(orderDon.getShopId(), orderDon.getOrderNo());
				if (reMap != null) {
					String orderStatus = reMap.get("trade_state");
					if ("SUCCESS".equals(orderStatus)) {
						orderDon.setStatus(GoodsWholesaleOrderDon.Status.hasPayment);
						orderDon.setPayTime(DateTime.now());
						orderDon.setTransactionId(reMap.get("transaction_id"));
					}
				}
			} catch (Exception e) {

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

			}
		}
		return orderDon.getStatus();
	}

}
