package org.springblade.gateway.point_gateway.service.impl;

import cn.hutool.core.lang.generator.SnowflakeGenerator;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yeepay.yop.sdk.service.common.response.YopResponse;
import io.jsonwebtoken.lang.Assert;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springblade.common.enums.AppConstant;
import org.springblade.common.utils.BeanPropertyUtil;
import org.springblade.common.utils.IPUtils;
import org.springblade.core.log.logger.BladeLogger;
import org.springblade.core.tool.utils.DateUtil;
import org.springblade.gateway.goods_gateway.exception.HelpGoodsException;
import org.springblade.gateway.point_gateway.enums.PointTypeEnum;
import org.springblade.gateway.point_gateway.exception.PointExchangeException;
import org.springblade.gateway.point_gateway.service.PointExchangeService;
import org.springblade.sing.goods.entity.GoodsOrder;
import org.springblade.sing.goods.entity.PointGoods;
import org.springblade.sing.goods.enums.GoodsRecordType;
import org.springblade.sing.goods.service.IGoodsOrderService;
import org.springblade.sing.goods.service.IPointGoodsService;
import org.springblade.sing.point.entity.PointRecord;
import org.springblade.sing.point.entity.UserPufaPoint;
import org.springblade.sing.point.service.IPointRecordService;
import org.springblade.sing.point.service.IUserPufaPointService;
import org.springblade.sing.user.entity.UserAddress;
import org.springblade.sing.user.service.ILoginUserService;
import org.springblade.sing.user.service.IUserAddressService;
import org.springblade.sing.yeepay.entity.YeepayOrder;
import org.springblade.sing.yeepay.enums.YeepayOrderPayStatus;
import org.springblade.sing.yeepay.service.IYeepayOrderService;
import org.springblade.wx.config.ConfigForOfficial;
import org.springblade.yeePay.common.YeePayConst;
import org.springblade.yeePay.entity.InitOrderDto;
import org.springblade.yeePay.service.YeePayService;
import org.springblade.yeePay.service.YeepaySaasService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Optional;

@Service
@Slf4j
public class PointExchangeServiceImpl implements PointExchangeService {

	@Autowired
	private IPointGoodsService pointGoodsService;
	@Autowired
	private IPointRecordService pointRecordService;
	@Autowired
	private IUserPufaPointService userPufaPointService;
	@Autowired
	private IUserAddressService userAddressService;
	@Autowired
	private IGoodsOrderService goodsOrderService;
	@Autowired
	private HttpServletRequest request;
	@Autowired
	private YeepaySaasService yeepaySaasService;
	@Autowired
	private IYeepayOrderService yeepayOrderService;
	@Autowired
	private YeePayConst yeePayConst;
	@Autowired
	private BladeLogger bladeLogger;
	@Autowired
	private YeePayService yeePayService;
	@Autowired
	private ConfigForOfficial configForOfficial;

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void pointExchange(YeepayOrder yeepayOrder) {
/*		UserPufaPoint user = userPufaPointService.getOne(new LambdaQueryWrapper<UserPufaPoint>().eq(UserPufaPoint::getPhone, yeepayOrder.getPhone()));
		Assert.notNull(user, "用户不存在");
		PointGoods goods = pointGoodsService.getById(yeepayOrder.getPointGoodsId());
		Assert.notNull(goods, "商品不存在");
		UserAddress address = userAddressService.getById(yeepayOrder.getAddressId());
		Assert.notNull(address, "请添加收货地址");
		Assert.notNull(yeepayOrder.getActiveId(), "兑换失败");

		Boolean isLimit = Optional.ofNullable(goods.getIsLimit()).orElse(false);
		if (isLimit) {
			int size = goodsOrderService.list(new LambdaQueryWrapper<GoodsOrder>()
				.eq(GoodsOrder::getPhone, yeepayOrder.getPhone()).eq(GoodsOrder::getPointGoodsId, yeepayOrder.getPointGoodsId())).size();
			System.out.println(size);
			if ((yeepayOrder.getNum() + size) > goods.getLimitBuy()) {
				throw new PointExchangeException("超过限购数量");
			}
		}
		if (goods.getRemain() < yeepayOrder.getNum()) {
			throw new PointExchangeException("库存不足");
		}
		if (user.getPufaPoint().compareTo(BigDecimal.ZERO) <= 0) {
			throw new PointExchangeException("积分不足");
		}
		//商品所需积分
		BigDecimal exchangeNum = BigDecimal.valueOf(yeepayOrder.getNum());
		BigDecimal exchangePoint = goods.getPoint().multiply(exchangeNum);

		BigDecimal userPoint = user.getPufaPoint().subtract(exchangePoint);

		if (userPoint.compareTo(BigDecimal.ZERO) < 0) {
			throw new PointExchangeException("积分不足");
		}

		user.setPufaPoint(userPoint);
		Assert.isTrue(userPufaPointService.saveOrUpdate(user), "兑换失败");
		//下单
		yeepayOrder.setUserId(user.getUserId());
		yeepayOrder.setUsePoint(exchangePoint);
		createOrder(yeepayOrder);

		//添加积分消费
		PointRecord pointRecord = new PointRecord();
		pointRecord.setPoint(goods.getPoint());
		pointRecord.setUserId(user.getUserId());
		pointRecord.setPointGoodsId(yeepayOrder.getPointGoodsId());
		pointRecord.setPointType(PointTypeEnum.PUFA_POINT_EXCHANGE);
		pointRecord.setPhone(yeepayOrder.getPhone());
		pointRecord.setActiveId(yeepayOrder.getActiveId());
		Assert.isTrue(pointRecordService.save(pointRecord), "兑换失败");*/

	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public HashMap<String, Object> cashExchange(YeepayOrder yeepayOrder) throws Exception {
/*		UserPufaPoint user = userPufaPointService.getOne(new LambdaQueryWrapper<UserPufaPoint>().eq(UserPufaPoint::getPhone, yeepayOrder.getPhone()));
		Assert.notNull(user, "用户不存在");
		PointGoods goods = pointGoodsService.getById(yeepayOrder.getPointGoodsId());
		Assert.notNull(goods, "商品不存在");
		UserAddress address = userAddressService.getById(yeepayOrder.getAddressId());
		Assert.notNull(address, "请添加收货地址");
		Assert.notNull(yeepayOrder.getActiveId(), "兑换失败");

		Boolean isLimit = Optional.ofNullable(goods.getIsLimit()).orElse(false);
		if (isLimit) {
			int size = goodsOrderService.list(new LambdaQueryWrapper<GoodsOrder>().eq(GoodsOrder::getPhone, yeepayOrder.getPhone())
				.eq(GoodsOrder::getPointGoodsId, yeepayOrder.getPointGoodsId())).size();
			if ((yeepayOrder.getNum() + size) > goods.getLimitBuy()) {
				throw new PointExchangeException("超过限购数量");
			}
		}
		if (goods.getRemain() < yeepayOrder.getNum()) {
			throw new PointExchangeException("库存不足");
		}
		//商品所需积分
		BigDecimal exchangeNum = BigDecimal.valueOf(yeepayOrder.getNum());
		BigDecimal needPoint = goods.getPoint().multiply(exchangeNum);
		BigDecimal amount = needPoint.divide(BigDecimal.valueOf(100));

		//判断兑换数量(判断兑换次数大于零)
		Assert.isTrue(Integer.valueOf(-1).equals(BigDecimal.ZERO.compareTo(BigDecimal.valueOf(yeepayOrder.getNum()))), "兑换数量必须大于零");

		//回调地址
		String callbackUrl = new StringBuilder(yeePayConst.getServiceUrl())
			.append("/app/point/callbackUrl").toString();
		yeepayOrder.setId(new SnowflakeGenerator().next());
		yeepayOrder.setPayStatus(YeepayOrderPayStatus.待付款);
		yeepayOrder.setAmount(amount);
		yeepayOrder.setHelpGoodsName(goods.getName());
		yeepayOrder.setCallbackUrl(callbackUrl);
		yeepayOrder.setCreateTime(new Date());
		yeepayOrder.setUserId(user.getUserId());
		yeepayOrder.setUsePoint(BigDecimal.ZERO);
		yeepayOrder.setPointGoodsName(goods.getName());
		yeepayOrder.setIp(IPUtils.getRealIp(request));

		// 请求易宝
		try {
			InitOrderDto initOrderDto = InitOrderDto
				.builder()
				.orderId(yeepayOrder.getId().toString())
				.orderAmount(amount.doubleValue())
				.goodsName(goods.getName())
				.scene("OFFLINE")
				.payWay("WECHAT_OFFIACCOUNT")
				.userIp(yeepayOrder.getIp())
				.channel("WECHAT")
				.userId(yeepayOrder.getOpenId())
				.appId(configForOfficial.getAppId())
				//支付订单有效期为一天
				.expiredTime(DateUtil.format(cn.hutool.core.date.DateUtil.offsetDay(DateUtil.now(), 1), DateUtil.PATTERN_DATETIME))
				.notifyUrl(callbackUrl)
				.build();
			//设置易宝配置内容
			initOrderDto.setParentMerchantNo(yeePayConst.getPlatformServiceNo());
			initOrderDto.setMerchantNo(yeePayConst.getMerchantNo());
			YopResponse yopResponse = yeepaySaasService.aggPrepay(initOrderDto);

			//返回数据
			String stringResult = yopResponse.getStringResult();
			JSONObject jsonObject = JSONObject.parseObject(stringResult);
			//返回给前端
			String prePayTn = jsonObject.getString("prePayTn");

			if (!StringUtils.equals(jsonObject.getString("code"), "00000")) {
				bladeLogger.error("创建道具订单错误", jsonObject.getString("message"));
				log.error("创建道具订单错误:{}", jsonObject.getString("message"));
				throw new HelpGoodsException("创建订单失败");
			}
			yeepayOrder.setUniqueOrderNo(jsonObject.getString(BeanPropertyUtil.getFieldName(YeepayOrder::getUniqueOrderNo)));
			yeepayOrder.setQrCodeUrl(jsonObject.getString(BeanPropertyUtil.getFieldName(YeepayOrder::getQrCodeUrl)));
			yeepayOrder.setBankOrderId(jsonObject.get("bankOrderId").toString());
			yeepayOrder.setPrePayTn(prePayTn);
			//保存订单
			Assert.isTrue(yeepayOrderService.save(yeepayOrder), "创建订单失败");

			JSONObject prePayTnJson = JSONObject.parseObject(prePayTn);

			HashMap<String, Object> map = new HashMap<>();
			map.put("appId", prePayTnJson.get("appId"));
			map.put("timeStamp", prePayTnJson.get("timeStamp"));
			map.put("nonceStr", prePayTnJson.get("nonceStr"));
			map.put("package", prePayTnJson.get("package"));
			map.put("signType", prePayTnJson.get("signType"));
			map.put("paySign", prePayTnJson.get("paySign"));

			return map;
		} catch (Exception e) {
			throw new Exception(e.getMessage());
		}*/
		return null;
	}

	@Transactional(rollbackFor = Exception.class)
	void createOrder(YeepayOrder yeepayOrder) {

		//添加商品记录表
		GoodsOrder goodsOrder = new GoodsOrder();
		goodsOrder.setPointGoodsId(yeepayOrder.getPointGoodsId());
		goodsOrder.setAddressId(yeepayOrder.getAddressId());
		goodsOrder.setNum(yeepayOrder.getNum());
		goodsOrder.setType(GoodsRecordType.POINT_GOODS_EXCHANGE);
		goodsOrder.setCash(yeepayOrder.getAmount());
		PointGoods pointGoods = pointGoodsService.getById(yeepayOrder.getPointGoodsId());
		goodsOrder.setGoodsImgUrl(pointGoods.getImgUrl());
		goodsOrder.setGoodsName(pointGoods.getName());
		UserAddress address = userAddressService.getById(yeepayOrder.getAddressId());
		String consigneeAddress = address.getProvinceName() + "-" + address.getCityName()
			+ "-" + address.getAreaName() + " " + address.getAddress();
		goodsOrder.setAddress(consigneeAddress);
		goodsOrder.setPhone(yeepayOrder.getPhone());
		goodsOrder.setConsignee(address.getConsignee());
		goodsOrder.setGoodsStatus(AppConstant.GOODS_STATUS.待发货);
		goodsOrder.setGoodsPoint(pointGoods.getPoint());
		goodsOrder.setActiveId(yeepayOrder.getActiveId());
		goodsOrder.setUserId(yeepayOrder.getUserId());
		if (yeepayOrder.getAmount() == null || yeepayOrder.getAmount().equals(BigDecimal.ZERO)) {
			goodsOrder.setCash(BigDecimal.ZERO);
		} else {
			goodsOrder.setCash(yeepayOrder.getAmount());
		}
		goodsOrder.setUsePoint(yeepayOrder.getUsePoint());

		Assert.isTrue(goodsOrderService.save(goodsOrder), "兑换失败");

		//更新商品库存
		pointGoods.setRemain(pointGoods.getRemain() - yeepayOrder.getNum());
		pointGoodsService.updateById(pointGoods);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void goodsHandlerCasePropsOrder(HttpServletRequest request) {
		String cipherText = request.getParameterMap().get("cipherText")[0];
		JSONObject jsonObject = yeePayService.deCodeNotifyData(cipherText);
		log.info("易宝道具订单支付回调支付解密回调密文{}", jsonObject.toJSONString());
		bladeLogger.info("易宝道具订单支付回调支付解密回调密文{}", jsonObject.toJSONString());
		//根据回调信息，获取订单
		Long orderId = jsonObject.getLong(BeanPropertyUtil.getFieldName(InitOrderDto::getOrderId));
		YeepayOrder yeepayOrder = yeepayOrderService.getById(orderId);
		UserPufaPoint user = userPufaPointService.getOne(new LambdaQueryWrapper<UserPufaPoint>().eq(UserPufaPoint::getPhone, yeepayOrder.getPhone()));

		if (yeepayOrder.getUsePoint() != null && !yeepayOrder.getUsePoint().equals(BigDecimal.ZERO)) {

			//更新用户积分
			user.setPufaPoint(user.getPufaPoint().subtract(yeepayOrder.getUsePoint()));
			Assert.isTrue(userPufaPointService.saveOrUpdate(user), "兑换失败");
			//添加积分消费记录
			PointRecord pointRecord = new PointRecord();
			pointRecord.setPoint(yeepayOrder.getUsePoint());
			pointRecord.setUserId(user.getUserId());
			pointRecord.setPointGoodsId(yeepayOrder.getPointGoodsId());
			pointRecord.setPointType(PointTypeEnum.PUFA_POINT_EXCHANGE);
			pointRecord.setPhone(yeepayOrder.getPhone());
			pointRecord.setActiveId(yeepayOrder.getActiveId());
			Assert.isTrue(pointRecordService.save(pointRecord), "兑换失败");
		}

		//设置订单状态
		yeepayOrder.setPayStatus(YeepayOrderPayStatus.付款成功);
		yeepayOrder.setCipherText(cipherText);
		Assert.isTrue(yeepayOrderService.updateById(yeepayOrder), "修改订单状态错误");
		//下单
		yeepayOrder.setUserId(user.getUserId());

		createOrder(yeepayOrder);

	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public HashMap<String, Object> hybridExchange(YeepayOrder yeepayOrder) throws Exception {

/*		UserPufaPoint user = userPufaPointService.getOne(new LambdaQueryWrapper<UserPufaPoint>().eq(UserPufaPoint::getPhone, yeepayOrder.getPhone()));
		Assert.notNull(user, "用户不存在");
		PointGoods goods = pointGoodsService.getById(yeepayOrder.getPointGoodsId());
		Assert.notNull(goods, "商品不存在");
		UserAddress address = userAddressService.getById(yeepayOrder.getAddressId());
		Assert.notNull(address, "请添加收货地址");
		Assert.notNull(yeepayOrder.getActiveId(), "兑换失败");

		Boolean isLimit = Optional.ofNullable(goods.getIsLimit()).orElse(false);
		if (isLimit) {
			int size = goodsOrderService.list(new LambdaQueryWrapper<GoodsOrder>().eq(GoodsOrder::getPhone, yeepayOrder.getPhone()).eq(GoodsOrder::getPointGoodsId, yeepayOrder.getPointGoodsId())).size();
			if ((yeepayOrder.getNum() + size) > goods.getLimitBuy()) {
				throw new PointExchangeException("超过限购数量");
			}
		}
		if (goods.getRemain() < yeepayOrder.getNum()) {
			throw new PointExchangeException("库存不足");
		}
		if (user.getPufaPoint().compareTo(yeepayOrder.getUsePoint()) <= 0) {
			throw new PointExchangeException("积分不足");
		}
		//商品所需积分
		BigDecimal exchangeNum = BigDecimal.valueOf(yeepayOrder.getNum());
		BigDecimal exchangePoint = goods.getPoint().multiply(exchangeNum);

		if (user.getPufaPoint().compareTo(exchangePoint) >= 0) {
			log.info("积分兑换");
			this.pointExchange(yeepayOrder);
			return null;
		}

		//需要的现金
		BigDecimal usePoint = exchangePoint.subtract(yeepayOrder.getUsePoint());
		BigDecimal useCash = usePoint.divide(BigDecimal.valueOf(100));

		//判断兑换数量(判断兑换次数大于零)
		Assert.isTrue(Integer.valueOf(-1).equals(BigDecimal.ZERO.compareTo(BigDecimal.valueOf(yeepayOrder.getNum()))), "兑换数量必须大于零");

		//回调地址
		String callbackUrl = new StringBuilder(yeePayConst.getServiceUrl())
			.append("/app/point/callbackUrl").toString();
		yeepayOrder.setId(new SnowflakeGenerator().next());
		yeepayOrder.setPayStatus(YeepayOrderPayStatus.待付款);
		yeepayOrder.setAmount(useCash);
		yeepayOrder.setHelpGoodsName(goods.getName());
		yeepayOrder.setCallbackUrl(callbackUrl);
		yeepayOrder.setCreateTime(new Date());
		yeepayOrder.setPointGoodsName(goods.getName());
		yeepayOrder.setUserId(user.getUserId());

		// 请求易宝
		try {
			InitOrderDto initOrderDto = InitOrderDto
				.builder()
				.orderId(yeepayOrder.getId().toString())
				.orderAmount(useCash.doubleValue())
				.goodsName(goods.getName())
				.scene("OFFLINE")
				.payWay("WECHAT_OFFIACCOUNT")
				.userIp(yeepayOrder.getIp())
				.channel("WECHAT")
				.userId(yeepayOrder.getOpenId())
				.appId(configForOfficial.getAppId())
				//支付订单有效期为一天
				.expiredTime(DateUtil.format(cn.hutool.core.date.DateUtil.offsetDay(DateUtil.now(), 1), DateUtil.PATTERN_DATETIME))
				.notifyUrl(callbackUrl)
				.build();
			//设置易宝配置内容
			initOrderDto.setParentMerchantNo(yeePayConst.getPlatformServiceNo());
			initOrderDto.setMerchantNo(yeePayConst.getMerchantNo());
			YopResponse yopResponse = yeepaySaasService.aggPayPayLink(initOrderDto);

			//返回数据
			String stringResult = yopResponse.getStringResult();
			JSONObject jsonObject = JSONObject.parseObject(stringResult);
			String prePayTn = jsonObject.getString("prePayTn");
			if (!StringUtils.equals(jsonObject.getString("code"), "00000")) {
				bladeLogger.error("创建道具订单错误", jsonObject.getString("message"));
				log.error("创建道具订单错误:{}", jsonObject.getString("message"));
				throw new HelpGoodsException("创建订单失败");
			}
			yeepayOrder.setUniqueOrderNo(jsonObject.getString(BeanPropertyUtil.getFieldName(YeepayOrder::getUniqueOrderNo)));
			yeepayOrder.setQrCodeUrl(jsonObject.getString(BeanPropertyUtil.getFieldName(YeepayOrder::getQrCodeUrl)));
			yeepayOrder.setBankOrderId(jsonObject.get("bankOrderId").toString());
			yeepayOrder.setPrePayTn(prePayTn);

			//保存订单
			Assert.isTrue(yeepayOrderService.save(yeepayOrder), "创建订单失败");
			JSONObject prePayTnJson = JSONObject.parseObject(prePayTn);

			HashMap<String, Object> map = new HashMap<>();
			map.put("appId", prePayTnJson.get("appId"));
			map.put("timeStamp", prePayTnJson.get("timeStamp"));
			map.put("nonceStr", prePayTnJson.get("nonceStr"));
			map.put("package", prePayTnJson.get("package"));
			map.put("signType", prePayTnJson.get("signType"));
			map.put("paySign", prePayTnJson.get("paySign"));

			return map;
		} catch (Exception e) {
			throw new Exception(e.getMessage());
		}*/
		return null;
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public HashMap<String, Object> merge(YeepayOrder yeepayOrder, int type) throws Exception {
		HashMap<String, Object> map = new HashMap<>();
		if (yeepayOrder.getUsePoint() != null && (yeepayOrder.getUsePoint().compareTo(BigDecimal.ZERO) < 0)) {
			throw new PointExchangeException("请输入有效积分值");
		}
		UserPufaPoint user = userPufaPointService.getOne(new LambdaQueryWrapper<UserPufaPoint>().eq(UserPufaPoint::getPhone, yeepayOrder.getPhone()));
		Assert.notNull(user, "用户不存在");
		PointGoods goods = pointGoodsService.getById(yeepayOrder.getPointGoodsId());
		Assert.notNull(goods, "商品不存在");
		UserAddress address = userAddressService.getById(yeepayOrder.getAddressId());
		Assert.notNull(address, "请添加收货地址");
		Assert.notNull(yeepayOrder.getActiveId(), "兑换失败");

		Boolean isLimit = Optional.ofNullable(goods.getIsLimit()).orElse(false);
		if (isLimit) {
			int size = goodsOrderService.list(new LambdaQueryWrapper<GoodsOrder>()
				.eq(GoodsOrder::getPhone, yeepayOrder.getPhone()).eq(GoodsOrder::getPointGoodsId, yeepayOrder.getPointGoodsId())).size();
			System.out.println(size);
			if ((yeepayOrder.getNum() + size) > goods.getLimitBuy()) {
				throw new PointExchangeException("超过限购数量");
			}
		}
		if (goods.getRemain() < yeepayOrder.getNum()) {
			throw new PointExchangeException("库存不足");
		}

		//商品所需积分
		BigDecimal exchangeNum = BigDecimal.valueOf(yeepayOrder.getNum());
		BigDecimal exchangePoint = goods.getPoint().multiply(exchangeNum);

		if (type == 1){
			if (user.getPufaPoint().compareTo(BigDecimal.ZERO) <= 0) {
				throw new PointExchangeException("积分不足");
			}

			BigDecimal userPoint = user.getPufaPoint().subtract(exchangePoint);

			if (userPoint.compareTo(BigDecimal.ZERO) < 0) {
				throw new PointExchangeException("积分不足");
			}
			user.setPufaPoint(userPoint);
			Assert.isTrue(userPufaPointService.saveOrUpdate(user), "兑换失败");
			yeepayOrder.setUserId(user.getUserId());
			yeepayOrder.setUsePoint(exchangePoint);
			//下单
			createOrder(yeepayOrder);
			//添加积分消费
			PointRecord pointRecord = new PointRecord();
			pointRecord.setPoint(goods.getPoint());
			pointRecord.setUserId(user.getUserId());
			pointRecord.setPointGoodsId(yeepayOrder.getPointGoodsId());
			pointRecord.setPointType(PointTypeEnum.PUFA_POINT_EXCHANGE);
			pointRecord.setPhone(yeepayOrder.getPhone());
			pointRecord.setActiveId(yeepayOrder.getActiveId());
			Assert.isTrue(pointRecordService.save(pointRecord), "兑换失败");
			//map.put("msg","兑换成功");
			//return map;
		}
		if (type == 2 || type == 0){
			BigDecimal amount;
			if (type == 2){
				if (user.getPufaPoint().compareTo(yeepayOrder.getUsePoint()) < 0) {
					throw new PointExchangeException("积分不足");
				}

				//如果用户输入的积分足够,则使用积分支付
				if (yeepayOrder.getUsePoint().compareTo(exchangePoint) > 0) {
					type = 1;
					return this.merge(yeepayOrder,type);
				}
				//需要的现金
				BigDecimal usePoint = exchangePoint.subtract(yeepayOrder.getUsePoint());
				amount = usePoint.divide(BigDecimal.valueOf(100));
			}else {
				amount = exchangePoint.divide(BigDecimal.valueOf(100));
			}

			//判断兑换数量(判断兑换次数大于零)
			Assert.isTrue(Integer.valueOf(-1).equals(BigDecimal.ZERO.compareTo(BigDecimal.valueOf(yeepayOrder.getNum()))), "兑换数量必须大于零");

			//回调地址
			String callbackUrl = new StringBuilder(yeePayConst.getServiceUrl())
				.append("/app/point/callbackUrl").toString();
			yeepayOrder.setId(new SnowflakeGenerator().next());
			yeepayOrder.setPayStatus(YeepayOrderPayStatus.待付款);
			yeepayOrder.setAmount(amount);
			yeepayOrder.setHelpGoodsName(goods.getName());
			yeepayOrder.setCallbackUrl(callbackUrl);
			yeepayOrder.setCreateTime(new Date());
			yeepayOrder.setUserId(user.getUserId());
			yeepayOrder.setUsePoint(BigDecimal.ZERO);
			yeepayOrder.setPointGoodsName(goods.getName());
			yeepayOrder.setIp(IPUtils.getRealIp(request));

			// 请求易宝
			try {
				InitOrderDto initOrderDto = InitOrderDto
					.builder()
					.orderId(yeepayOrder.getId().toString())
					.orderAmount(amount.doubleValue())
					.goodsName(goods.getName())
					.scene("OFFLINE")
					.payWay("WECHAT_OFFIACCOUNT")
					.userIp(yeepayOrder.getIp())
					.channel("WECHAT")
					.userId(yeepayOrder.getOpenId())
					.appId(configForOfficial.getAppId())
					//支付订单有效期为一天
					.expiredTime(DateUtil.format(cn.hutool.core.date.DateUtil.offsetDay(DateUtil.now(), 1), DateUtil.PATTERN_DATETIME))
					.notifyUrl(callbackUrl)
					.build();
				//设置易宝配置内容
				initOrderDto.setParentMerchantNo(yeePayConst.getPlatformServiceNo());
				initOrderDto.setMerchantNo(yeePayConst.getMerchantNo());
				YopResponse yopResponse = yeepaySaasService.aggPrepay(initOrderDto);

				//返回数据
				String stringResult = yopResponse.getStringResult();
				JSONObject jsonObject = JSONObject.parseObject(stringResult);
				String uniqueOrderNo = jsonObject.getString("bankOrderId");

				//返回给前端
				String prePayTn = jsonObject.getString("prePayTn");

				if (!StringUtils.equals(jsonObject.getString("code"), "00000")) {
					bladeLogger.error("创建道具订单错误", jsonObject.getString("message"));
					log.error("创建道具订单错误:{}", jsonObject.getString("message"));
					throw new HelpGoodsException("创建订单失败");
				}
				yeepayOrder.setUniqueOrderNo(jsonObject.getString(BeanPropertyUtil.getFieldName(YeepayOrder::getUniqueOrderNo)));
				yeepayOrder.setQrCodeUrl(jsonObject.getString(BeanPropertyUtil.getFieldName(YeepayOrder::getQrCodeUrl)));
				yeepayOrder.setBankOrderId(jsonObject.get("bankOrderId").toString());
				yeepayOrder.setPrePayTn(prePayTn);
				//保存订单
				Assert.isTrue(yeepayOrderService.save(yeepayOrder), "创建订单失败");

				JSONObject prePayTnJson = JSONObject.parseObject(prePayTn);

				map.put("appId", prePayTnJson.get("appId"));
				map.put("timeStamp", prePayTnJson.get("timeStamp"));
				map.put("nonceStr", prePayTnJson.get("nonceStr"));
				map.put("package", prePayTnJson.get("package"));
				map.put("signType", prePayTnJson.get("signType"));
				map.put("paySign", prePayTnJson.get("paySign"));
				map.put("orderId",uniqueOrderNo);

			} catch (Exception e) {
				throw new Exception(e.getMessage());
			}
		}
		return map;
	}
}
