package org.springblade.modules.api.controller;

import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.*;
import com.alipay.api.domain.AlipayFundTransUniTransferModel;
import com.alipay.api.domain.AlipayTradeAppPayModel;
import com.alipay.api.domain.Participant;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.*;
import com.alipay.api.response.*;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.AllArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springblade.common.cache.ParamCache;
import org.springblade.common.constant.CommonConstant;
import org.springblade.common.utils.CommonUtil;
import org.springblade.common.utils.NotifyUtils;
import org.springblade.core.boot.ctrl.BladeController;
import org.springblade.core.log.annotation.ApiLog;
import org.springblade.core.log.exception.ServiceException;
import org.springblade.core.log.logger.BladeLogger;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.utils.DateUtil;
import org.springblade.core.tool.utils.StringUtil;
import org.springblade.modules.finance.entity.Order;
import org.springblade.modules.finance.entity.OrderConsign;
import org.springblade.modules.finance.entity.OrderGrant;
import org.springblade.modules.finance.entity.PlatformAuthorization;
import org.springblade.modules.finance.mapper.PlatformAuthorizationMapper;
import org.springblade.modules.finance.pay.entity.AlipayProperties;
import org.springblade.modules.finance.service.IOrderConsignService;
import org.springblade.modules.finance.service.IOrderGrantService;
import org.springblade.modules.finance.service.IOrderService;
import org.springblade.modules.platform.wrapper.UserAppWrapper;
import org.springblade.modules.shopping.entity.Consign;
import org.springblade.modules.shopping.service.IConsignService;
import org.springblade.modules.system.entity.User;
import org.springblade.modules.system.entity.UserApp;
import org.springblade.modules.system.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.*;

@RestController
@AllArgsConstructor
@RequestMapping(CommonConstant.API_URL + "/aliPay/sdk")
@Api(value = "支付宝SDK", tags = "95.支付宝SDK")
public class AliPay01Controller extends BladeController {

	private static final Logger log = LoggerFactory.getLogger(AliPay01Controller.class);

	//渠道
	private static final String PAY_CODE = "aliPay";

	//预授权
	private static final String NOTIFY_URL = "/api/v1/aliPay/sdk/auth_notify_url";

	//平台付款预授权
	private static final String PLATFORM_URL = "/api/v1/aliPay/sdk/platform_authorization_notify_url";

	//抢购
	private static final String TRADE_URL = "/api/v1/aliPay/sdk/trade_notify_url";

	//购买
	private static final String ORDER_URL = "/api/v1/aliPay/sdk/order_notify_url";

	@Autowired
	private AlipayClient client;//支付宝请求sdk客户端

	@Autowired
	private AlipayProperties properties;//支付宝sdk配置

	private final IOrderService orderService;
	private final IOrderGrantService orderGrantService;
	private final IUserService userService;
	private final IOrderConsignService orderConsignService;
	private final IConsignService consignService;

	@Resource
	private PlatformAuthorizationMapper paMapper;

	@Autowired
	private BladeLogger logger;

	@ApiLog("发起交易-证书")
	@PostMapping("/pay_001")
	@ApiOperation(value = "统一收单线下交易查询", notes = "当面付")
	@ApiOperationSupport(order = 1)
	public R pay001(@ApiParam(value = "订单号", required = true) @RequestParam String outTradeNo,
					@ApiParam(value = "支付渠道:aliPay支付宝，wechatPay微信支付，unionPay银联 ", required = true) @RequestParam String payFor) {
		Order order = orderService.getOne(Wrappers.<Order>lambdaQuery().eq(Order::getOutTradeNo, outTradeNo));
		if (order == null){
			return R.fail("请求参数错误！");
		}
		if(StringUtil.isEmpty(payFor)){
			return R.fail("请选择支付方式！");
		}
		if(order.getOrderType() == 3){
			//寄售订单而且寄售方式为寄售
			OrderConsign orderConsign = orderConsignService.getOne(Wrappers.<OrderConsign>lambdaQuery()
				.eq(OrderConsign::getOutTradeNo, outTradeNo));
			if (orderConsign != null){
				Consign consign = consignService.getById(orderConsign.getConsignId());
				if (consign != null && consign.getConsignType() == 2){
					return R.fail("该订单为抢购单，不能发起交易！");
				}
			}
		}
		if("aliPay".equals(payFor)){
			AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest ();
			AlipayTradeAppPayModel model = new AlipayTradeAppPayModel ();
			model.setBody("中宏商城" );
			model.setSubject("中宏商城");
			model.setOutTradeNo(outTradeNo);
			model.setTimeoutExpress("30m");
			model.setTotalAmount(order.getPayFee().toString());
			model.setProductCode("QUICK_MSECURITY_PAY");
			request.setBizModel(model);
			request.setNotifyUrl(properties.getDomain() + ORDER_URL);
			try  {
//				这里和普通的接口调用不同，使用的是sdkExecute
//				普通模式 使用 execute
//				证书使用 使用 sdkExecute
				AlipayTradeAppPayResponse response = client.sdkExecute(request);
				return R.data(response.getBody());
			}  catch (AlipayApiException e ) {
				e.printStackTrace();
				return R.fail("发起支付失败！");
			}
		}
		return R.fail("该支付方式暂不支持！");
	}


	@ApiLog("绑定订单-预授权")
	@PostMapping("/pay_002")
	@ApiOperation(value = "统一收单交易支付接口", notes = "预授权")
	@ApiOperationSupport(order = 2)
	@Transactional(rollbackFor = Exception.class)
	public R pay002(@ApiParam(value = "抢购订单号", required = true) @RequestParam String outTradeNo,
					@ApiParam(value = "预授权订单号", required = true) @RequestParam String orderNo) {
		Order order = orderService.getOne(Wrappers.<Order>lambdaQuery().eq(Order::getOutTradeNo, outTradeNo));
		if (order == null){
			return R.fail("请求参数错误！");
		}
		OrderGrant orderGrant = orderGrantService.getOne(Wrappers.<OrderGrant>lambdaQuery().eq(OrderGrant::getOrderNo, orderNo));
		if (orderGrant == null) {
			return R.fail("请求参数错误！");
		}
		//获取数量
		Integer nowNum = orderGrant.getNowNum();
		UserApp userApp = new UserApp();
		UserApp query = userApp.selectOne(Wrappers.<UserApp>lambdaQuery().eq(UserApp::getUserId, orderGrant.getUserId()));
		if (query == null) {
			return R.fail("用户信息错误！");
		}
		if (StringUtil.isEmpty(query.getAlipayUserId())) {
			return R.fail("请绑定支付宝打款账号");
		}
		JSONObject data = new JSONObject();
		data.put("out_trade_no", outTradeNo);
		data.put("total_amount", orderGrant.getPrice());
		data.put("subject", "中宏酒业");
		data.put("product_code", "PRE_AUTH_ONLINE");
		data.put("auth_no", orderGrant.getAuthNo());
		data.put("body", orderGrant.getAuthNo());
		if (nowNum == 1){
			data.put("auth_confirm_mode", "COMPLETE"); //解冻
		}else{
			data.put("auth_confirm_mode", "NOT_COMPLETE");//不解冻
		}
		data.put("seller_id", properties.getPayeeUserId()); //收款方
		data.put("buyer_id", query.getAlipayUserId()); //买家ID //2088012801069195
		//APP支付
		AlipayTradePayRequest request = new AlipayTradePayRequest();
		request.setNotifyUrl(properties.getDomain() + TRADE_URL); //异步通知地址
		request.setBizContent(data.toJSONString()); //业务参数
		//APP支付
		try {
			Order update = new Order();
			update.setId(order.getId());
			update.setGrantNo(orderGrant.getAuthNo());
			boolean flg = orderService.updateById(update);
			if (!flg){
				logger.info("订单绑定失败",update.toString());
			}
			//普通模式 使用 execute
			//证书使用 使用 certificateExecute
			AlipayTradePayResponse response = client.certificateExecute(request);
			if (response.isSuccess()){
				return R.data(response.getBody());
			}else{
				orderGrantService.remove(Wrappers.<OrderGrant>lambdaQuery()
					.eq(OrderGrant::getId,orderGrant.getId())
					.eq(OrderGrant::getStatus, 0));
				logger.info("订单绑定失败","删除预授权数据");
			}
		} catch (AlipayApiException e) {
			e.printStackTrace();
		}
		return R.fail("发起支付失败！");
	}

	/**
	 * 发起支付宝预授权
	 *
	 * 1、判断用户是否能抢购
	 * 2、查询是否有寄售/进货单
	 * 3、发起支付宝预支付
	 * 4、请求成功 创建预支付订单 默认为未授权
	 * @param userId 用户id
	 * @param batNo 批次ID
	 * @param price 金额
	 * @param num 预授数量
	 * @return R
	 * @throws AlipayApiException
	 */
	@ApiLog("发起支付宝预授权")
	@PostMapping("/pay_003")
	@ApiOperation(value = "线上资金授权冻结接口-调用支付宝预授权", notes = "支付请求")
	@ApiOperationSupport(order = 3)
	public R<String> pay003(@ApiParam(value = "用户号", required = true) @RequestParam Long userId,
							@ApiParam(value = "批次ID", required = true) @RequestParam Long batNo,
							@ApiParam(value = "金额", required = true) @RequestParam Double price,
							@ApiParam(value = "数量", required = true) @RequestParam Integer num) throws AlipayApiException {
		UserApp userApp = new UserApp();
		UserApp query = userApp.selectOne(Wrappers.<UserApp>lambdaQuery().eq(UserApp::getUserId,userId));
		if (ObjectUtil.isNull(query)){
			return R.fail("该用户不存在！");
		}
		boolean flg = UserAppWrapper.build().isTicket(query.getTicket(), price);
		if (!flg){
			return R.fail("您的绿色积分不足！");
		}
		if (query.getEnableAuth() != 2){
			double k = (double)query.getCreditScore() / 100;
			int scoreCount = NumberUtil.roundDown(k, 2).intValue();
			int consignCount = Integer.parseInt(ParamCache.getValue(CommonConstant.DEFAULT_CONDIGN_COUNT));
			if (scoreCount > consignCount){
				scoreCount = consignCount;
			}
			if (scoreCount < num){
				return R.fail("预授数量不能大于单场可抢次数！");
			}
		}
		if(query.getState() != 1 ){
			return R.fail("该账号已冻结！");
		}
		Consign consign = consignService.queryConsign(batNo, userId);
		if (ObjectUtil.isNull(consign)){
			return R.fail("亲，好物已抢完欢迎再来！");
		}
		//判断用户是否在该场次下有预授权
		OrderGrant orderGrant = orderGrantService.getOne(Wrappers.<OrderGrant>lambdaQuery()
			.eq(OrderGrant::getBatNo, batNo)
			.eq(OrderGrant::getUserId, userId)
			.eq(OrderGrant::getStatus,1)
		);
		if(ObjectUtil.isNotNull(orderGrant)){
			return R.fail("您已发起预授权，无需再次发起！");
		}
//		if (!ObjectUtil.isNull(orderGrant)){
//			return R.fail("您已发起预授权，无需再次发起！");
//		}
		JSONObject data = new JSONObject();
		String orderNo = CommonUtil.genTimeID();
		data.put("out_order_no", orderNo);
		data.put("out_request_no", orderNo);
		data.put("order_title","预授权冻结");
		data.put("amount", NumberUtil.mul(price, num));
		data.put("product_code","PRE_AUTH_ONLINE"); //销售产品码。支付宝预授权产品固定为 PRE_AUTH_ONLINE
		data.put("payee_user_id", properties.getPayeeUserId());
		data.put("timeout_express","30m");
		//APP支付
		AlipayFundAuthOrderAppFreezeRequest request = new AlipayFundAuthOrderAppFreezeRequest();
		request.setNotifyUrl(properties.getDomain() + NOTIFY_URL); //异步通知地址
		request.setBizContent(data.toJSONString()); //业务参数
		//APP支付
		//必须使用 sdkExecute
		AlipayFundAuthOrderAppFreezeResponse response = client.sdkExecute(request);
		if(response.isSuccess()){
			String dataDate = DateUtil.format(DateUtil.now(), DateUtil.PATTERN_DATE);
			OrderGrant grant = new OrderGrant();
			grant.setBatNo(batNo);
			grant.setUserId(userId);
			grant.setStatus(0);//未授权
			grant.setOrderNo(orderNo);
			grant.setNum(num);
			grant.setNowNum(num);
			grant.setPrice(price);
			grant.setDataDate(dataDate);
			grant.setCreateTime(DateUtil.now());//创建时间
			orderGrantService.save(grant);
			return R.data(response.getBody());
		}
		return R.fail("授权失败！");
	}

	@GetMapping("/pay_004")
	@ApiOperation(value = "资金授权操作查询接口", notes = "支付请求")
	@ApiOperationSupport(order = 3)
	public R pay004(@ApiParam(value = "订单号", required = true) @RequestParam String outTradeNo,
					@ApiParam(value = "查询明细，1查询冻结明细，2查询解冻明细,3查询支付明细时", required = true)
					@RequestParam Integer type) throws AlipayApiException {
		JSONObject data = new JSONObject();
		if(type == 1){ //查询冻结明细
			data.put("auth_no", outTradeNo);
			data.put("out_order_no", outTradeNo);
			data.put("operation_type","FREEZE");
		}else if(type == 2){ //查询解冻明细
			data.put("auth_no", outTradeNo);
			data.put("out_order_no", outTradeNo);
			data.put("operation_type","UNFREEZE");
		}else if(type == 3){ //查询支付明细时
			data.put("auth_no", outTradeNo);
			data.put("out_order_no", outTradeNo);
			data.put("operation_type","PAY");
		}else{
			return R.fail("参数错误！");
		}
		// 设置整体请求参数
		//APP支付
		AlipayFundAuthOperationDetailQueryRequest request = new AlipayFundAuthOperationDetailQueryRequest();
		request.setBizContent(data.toString());
		//APP支付
		AlipayFundAuthOperationDetailQueryResponse response = client.certificateExecute(request);
		if(response.isSuccess()){
			return R.data(response.getBody());
		}
		return R.fail("授权失败！");
	}

	@ApiLog("抢购打款-测试")
	@PostMapping("/pay_005")
	@ApiOperation(value = "单笔转账到支付宝账户", notes = "单笔转账到支付宝账户")
	@ApiOperationSupport(order = 5)
	public R pay005() throws AlipayApiException {
		String privateKey = "MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCU4XTbNjnNOmuEnwBEgUBOVLK5CaUiUFKEkVW1/2sTlijARZzLtzwXfbkvzHEhCSu+E+OA1Futbh5HwNAC06bvqYDS+TXrFuZ0LcDaU92lk5Hp/ed8NhRXtm0gss1TS0vebOq+3kejErIvVCg9kNMrYMrmdf8G0+zKlCp3vrfdM37IeLXp3GoOckNzHh/LT7rLd7/9QcdSCPixPSwusrfCusw3H093cuWkV9WX4Go/zHTL9rAEwJPOn36OhyVc1oG113ZJiVg7KgsZGOCJJyh9BvlKq2vuKxnylQwq9Kh5e+BfP2FSWs7a1XMj/79JsZTxztJ9tFqcSXQh99vq1nd1AgMBAAECggEAVglIT5oxoxEcq0J7lBshf2Lg+Z/CR2clmKioYImfZm1DVYGlD/DvECA+kYnS4qV7GthBg+S0qi/V3d9mFgwcD6nj4YfVCets+Dyskz8d+p6iFxf820IhVWL+A4Rwta7wxDQrIGwx9+JJCKLYsmNsNUg1WSNdYqO71oHzXMnhVTmYJ6sKOrrBucyI4Ydu9UbfN+DRRGD9seL+Nxh1V2PPXs4ftk2kRlG18LaTPgFba1g8QBIpGDR9gFqM+DvBHUxAWsPRnL1+q0c6o5Ndk7W5f7Ob1zxF/lgqHudiG38jItkwc7MLMOYjbV5wiJPZc93nsHS1CKPSEX9/snNLnx2LQQKBgQDMyLBVVasfTMQpMjyi+Jof9JLHPiRP3dEHwZECUgfdWhPoidLjK9y1wszm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NVNycXdmDrEe7gIB1yCouNK6/DZ7IQH2AajSuvbxmCqO0MzywEfgvLqE0GFVsKKmXvgJebRAnW9RmGhmrxvEIceXCjR3tbxM9gX8lioDlqKnBootTgAbjIJ5VrPvKPwIDAQAB";
		AlipayConfig alipayConfig = new AlipayConfig();
		alipayConfig.setServerUrl("https://openapi.alipay.com/gateway.do");
		alipayConfig.setAppId("2021003125657245");
		alipayConfig.setPrivateKey(privateKey);
		alipayConfig.setFormat("json");
		alipayConfig.setAlipayPublicKey(alipayPublicKey);
		alipayConfig.setCharset("UTF8");
		alipayConfig.setSignType("RSA2");
		//设置应用公钥证书路径//appCertPublicKey_2021003125657245
		alipayConfig.setAppCertPath("D:\\Blade2.9.0\\bladex-boot\\src\\main\\resources\\alipay\\appCertPublicKey_2021003125657245.crt");
		//设置支付宝公钥证书路径//alipayCertPublicKey_RSA2
		alipayConfig.setAlipayPublicCertPath("D:\\Blade2.9.0\\bladex-boot\\src\\main\\resources\\alipay\\alipayCertPublicKey_RSA2.crt");
		//设置支付宝根证书路径
		alipayConfig.setRootCertPath("D:\\Blade2.9.0\\bladex-boot\\src\\main\\resources\\alipay\\alipayRootCert.crt");
		AlipayClient alipayClient = new DefaultAlipayClient(alipayConfig);
		AlipayFundTransUniTransferModel model = new AlipayFundTransUniTransferModel();
		String outBizNo = CommonUtil.genTimeID();
		model.setOutBizNo(outBizNo);
		model.setRemark("20220410退款");
		model.setBusinessParams("{\"payer_show_name_use_alias\":\"true\"}");
		model.setBizScene("DIRECT_TRANSFER");
		Participant payeeInfo = new Participant();
		payeeInfo.setIdentity("2088012801069195");
		payeeInfo.setIdentityType("ALIPAY_USER_ID");
		payeeInfo.setName("丰元权");
		model.setPayeeInfo(payeeInfo);
		model.setTransAmount("100");
		model.setProductCode("TRANS_ACCOUNT_NO_PWD");
		model.setOrderTitle("中宏科技");
		AlipayFundTransUniTransferRequest request = new AlipayFundTransUniTransferRequest();
		request.setBizModel(model);
		AlipayFundTransUniTransferResponse response = alipayClient.certificateExecute(request);
		if (response.isSuccess()){
			logger.info("打款成功", response.getBody());
			JSONUtil.parseObj(response.getBody());
			return R.data(response.getBody());
		}
		logger.info("打款失败", response.getBody());
		return R.success("打款成功！");
	}

	@ApiLog("抢购打款-测试")
	@PostMapping("/pay_006")
	@ApiOperation(value = "单笔转账到支付宝账户", notes = "单笔转账到支付宝账户")
	@ApiOperationSupport(order = 5)
	public R pay006(@ApiParam(value = "id", required = true) @RequestParam String id,
					@ApiParam(value = "真实姓名", required = true) @RequestParam String name,
					@ApiParam(value = "金额", required = true) @RequestParam String amount) {
		transfer(id, amount, name);
		return R.fail("正在打款...");
	}

	@ApiLog("资金解冻")
	@GetMapping("/pay_unfreeze")
	@ApiOperation(value = "资金授权解冻", notes = "支付请求")
	@ApiOperationSupport(order = 3)
	public R payUnfreeze(@ApiParam(value = "支付宝资金授权订单号", required = true) @RequestParam String authNo,
						 @ApiParam(value = "解冻金额", required = true) @RequestParam Double amount) throws AlipayApiException {
		AlipayFundAuthOrderUnfreezeRequest request = new AlipayFundAuthOrderUnfreezeRequest();
		JSONObject bizContent = new JSONObject();
		bizContent.put("auth_no", authNo);
		bizContent.put("out_request_no","outRequestNo123");
		bizContent.put("amount", amount);
		bizContent.put("remark","解冻资金");
		JSONObject extraParam = new JSONObject();
		JSONObject unfreezeBizInfo = new JSONObject();
		unfreezeBizInfo.put("bizComplete",true);
		extraParam.put("unfreezeBizInfo",unfreezeBizInfo);
		bizContent.put("extra_param",extraParam);
		// 设置整体请求参数
		request.setBizContent(bizContent.toString());
		// 使用execute方法发起请求
		AlipayFundAuthOrderUnfreezeResponse response = client.certificateExecute(request);
		if(response.isSuccess()){
			logger.info("解冻资金成功", response.getBody());
			return R.fail("解冻资金成功！");
		}
		logger.info("解冻资金失败", response.getBody());
		return R.fail("解冻资金失败！");
	}

	@GetMapping("/getAlipay_sign")
	@ApiOperation(value = "获取签名", notes = "获取签名")
	@ApiOperationSupport(order = 97)
	public R getAlipaySign() throws AlipayApiException, UnsupportedEncodingException {
		String content = "apiname=com.alipay.account.auth" +
			"&app_id=" + properties.getAppId() +
			"&app_name=mc" +
			"&auth_type=AUTHACCOUNT&biz_type=openservice" +
			"&method=alipay.open.auth.sdk.code.get" +
			"&pid=2088341967443472" +
			"&product_id=APP_FAST_LOGIN" +
			"&scope=kuaijie" +
			"&sign_type=RSA2" +
			"&target_id=" + CommonUtil.genTimeID();
		String sign = AlipaySignature.rsaSign(content, properties.getPrivateKey(),"utf-8","RSA2");
		String urlencoder = URLEncoder.encode(sign,"UTF-8");
		return R.data(content + "&sign=" + urlencoder);
	}

	@ApiLog("获取支付宝用户信息")
	@GetMapping("/setAlipay_userInfo")
	@ApiOperation(value = "设置用户信息", notes = "设置用户信息")
	@ApiOperationSupport(order = 97)
	public R getAlipayUserinfo(@ApiParam(value = "用户ID", required = true) @RequestParam String userId,
							   @ApiParam(value = "支付宝用户ID", required = true) @RequestParam String aliPayUserId)  {
		UserApp userApp = new UserApp();
		UserApp query = userApp.selectOne(Wrappers.<UserApp>lambdaQuery().eq(UserApp::getUserId,userId));
		if (query == null){
			return R.fail("用户不存在");
		}
		UserApp param = new UserApp();
		param.setId(query.getId());
		param.setAlipayUserId(aliPayUserId);
		return R.status(param.updateById());
	}

	@ApiLog("平台付款预授权回调")
	@RequestMapping(value = "/platform_authorization_notify_url", method = {RequestMethod.GET, RequestMethod.POST})
	@ApiOperation(value = "异步通知相应-预授回调", notes = "异步通知相应")
	public void platformAuthorizationNotify(HttpServletRequest request){
		String errMsg = "预授回调";
		logger.info(errMsg, request.getParameterMap().toString());
		if (!NotifyUtils.rsaCheck(properties, request.getParameterMap())) {
			//这里处理验签失败
			log.info(errMsg + "-处理验签失败");
		}
		String status = request.getParameter("status");
		String auth_no = request.getParameter("auth_no");
		if (!"SUCCESS".equals(status)){
			log.info(errMsg + "-预授权失败");
		}
		String out_request_no = request.getParameter("out_request_no");
		LambdaQueryWrapper<PlatformAuthorization> query = Wrappers.lambdaQuery(PlatformAuthorization.class);
		query.eq(PlatformAuthorization::getOrderNo, out_request_no);
		PlatformAuthorization platformAuthorization = paMapper.selectOne(query);
		if(ObjectUtil.isNotNull(platformAuthorization)){
			platformAuthorization.setAuthNo(auth_no);
			platformAuthorization.setState(1);
			paMapper.updateById(platformAuthorization);
		}

	}

	/**
	 * 发起支付宝预授权
	 *
	 * 1、判断用户是否能抢购
	 * 2、查询是否有寄售/进货单
	 * 3、发起支付宝预支付
	 * 4、请求成功 创建预支付订单 默认为未授权
	 * @param userId 用户id
	 * @param batNo 批次ID
	 * @param price 金额
	 * @param num 预授数量
	 * @return R
	 * @throws AlipayApiException
	 */
	@ApiLog("发起支付宝预授权")
	@PostMapping("/platfromAuth")
	@ApiOperation(value = "线上资金授权冻结接口-调用支付宝预授权", notes = "支付请求")
	@ApiOperationSupport(order = 3)
	public R<String> platfromAuth(@ApiParam(value = "用户号", required = true) @RequestParam Long userId,
								  @ApiParam(value = "批次ID", required = true) @RequestParam Long batNo,
								  @ApiParam(value = "金额", required = true) @RequestParam BigDecimal price,
								  @ApiParam(value = "数量", required = true) @RequestParam Integer num) throws AlipayApiException {
		UserApp userApp = new UserApp();
		UserApp query = userApp.selectOne(Wrappers.<UserApp>lambdaQuery().eq(UserApp::getUserId,userId));
		if (ObjectUtil.isNull(query)){
			return R.fail("该用户不存在！");
		}
		if (query.getEnableAuth() != 2){
			double k = (double)query.getCreditScore() / 100;
			int scoreCount = NumberUtil.roundDown(k, 2).intValue();
			int consignCount = Integer.parseInt(ParamCache.getValue(CommonConstant.DEFAULT_CONDIGN_COUNT));
			if (scoreCount > consignCount){
				scoreCount = consignCount;
			}
			if (scoreCount < num){
				return R.fail("预授数量不能大于单场可抢次数！");
			}
		}
		if(query.getState() != 1 ){
			return R.fail("该账号已冻结！");
		}

		JSONObject data = new JSONObject();
		String orderNo = CommonUtil.genTimeID();
		data.put("out_order_no", orderNo);
		data.put("out_request_no", orderNo);
		data.put("order_title","预授权冻结");
		data.put("amount", price.multiply(new BigDecimal(num)));
		data.put("product_code","PRE_AUTH_ONLINE"); //销售产品码。支付宝预授权产品固定为 PRE_AUTH_ONLINE
		data.put("payee_user_id", properties.getPayeeUserId());
		data.put("timeout_express","30m");
		//APP支付
		AlipayFundAuthOrderAppFreezeRequest request = new AlipayFundAuthOrderAppFreezeRequest();
		request.setNotifyUrl(properties.getDomain() + PLATFORM_URL); //异步通知地址
		request.setBizContent(data.toJSONString()); //业务参数
		//APP支付
		//必须使用 sdkExecute
		AlipayFundAuthOrderAppFreezeResponse response = client.sdkExecute(request);
		if(response.isSuccess()){
			PlatformAuthorization platformAuthorization = new PlatformAuthorization();
			platformAuthorization.setConsignConfigId(batNo);//场次id
			platformAuthorization.setTotalNum(num);//授权数量
			platformAuthorization.setCreateUserId(getUser().getUserId());//创建用户id
			platformAuthorization.setState(0);//未授权
			platformAuthorization.setOrderNo(orderNo);//订单编号
			platformAuthorization.setAuthPrice(price.multiply(new BigDecimal(num)).setScale(2, BigDecimal.ROUND_DOWN));//订单金额
			platformAuthorization.setCreateTime(new Date());
			paMapper.insert(platformAuthorization);
			return R.data(response.getBody());
		}
		return R.fail("授权失败！");
	}

	@ApiLog("预授回调")
	@RequestMapping(value = "/auth_notify_url", method = {RequestMethod.GET, RequestMethod.POST})
	@ApiOperation(value = "异步通知相应-预授回调", notes = "异步通知相应")
	@ApiOperationSupport(order = 99)
	public String authNotify(HttpServletRequest request) {
		String errMsg = "预授回调";
		logger.info(errMsg, request.getParameterMap().toString());
		if (!NotifyUtils.rsaCheck(properties, request.getParameterMap())) {
			//这里处理验签失败
			log.info(errMsg + "-处理验签失败");
			return "error";
		}
		String status = request.getParameter("status");
		String auth_no = request.getParameter("auth_no");
		if (!"SUCCESS".equals(status)){
			log.info(errMsg + "-预授权失败");
			return "error";
		}
		String out_request_no = request.getParameter("out_request_no");
		if (out_request_no == null){
			log.info(errMsg + "-无法获取预授订单");
			return "error";
		}
		OrderGrant grant = new OrderGrant();
		grant.setOrderNo(out_request_no);
		OrderGrant query = orderGrantService.getOne(Wrappers.<OrderGrant>lambdaQuery().eq(OrderGrant::getOrderNo,out_request_no));
		if (query == null){
			log.info(errMsg + "-查询预授权数据错误");
			return "error";
		}
		OrderGrant grantUpdate = new OrderGrant();
		grantUpdate.setId(query.getId());
		grantUpdate.setStatus(1);//已授权
		grantUpdate.setAuthNo(auth_no);
		grantUpdate.setFreezeTime(DateUtil.now());
		boolean flg =  orderGrantService.updateById(grantUpdate);
		if (!flg){
			log.info(errMsg + "-更新数据失败");
			return "error";
		}
		return "success";
	}

	@ApiLog("购买回调")
	@RequestMapping(value = "/order_notify_url", method = {RequestMethod.GET, RequestMethod.POST})
	@ApiOperation(value = "异步通知相应-购买回调", notes = "异步通知相应")
	@ApiOperationSupport(order = 100)
	public String orderNotify(HttpServletRequest request) throws AlipayApiException {
		String errMsg = "购买回调";
		//获取支付宝POST过来反馈信息
		Map<String,String> params = new HashMap<>();
		Map requestParams = request.getParameterMap();
		for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext ();) {
			String name =  ( String )iter.next();
			String[] values = (String[])requestParams.get(name);
			String valueStr="";
			for(int i = 0;i < values.length; i++){
				valueStr = (i== values.length-1)?valueStr+values[i]:valueStr+values[i] + ",";
			}
			//乱码解决，这段代码在出现乱码时使用。
			//valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
			params.put(name,valueStr);
		}
		log.info("params === " + params.toString());
		//切记alipayPublicCertPath是支付宝公钥证书路径，请去open.alipay.com对应应用下载。
		//boolean AlipaySignature.rsaCertCheckV1(Map<String, String> params, String publicKeyCertPath, String charset,String signType)
		boolean flag = AlipaySignature.rsaCertCheckV1(params,properties.getAliPayCertPath(), AlipayConstants.CHARSET_UTF8,"RSA2");
		log.info("flag === " + flag);
		String out_trade_no = request.getParameter("out_trade_no");//获取请求参数中的商户订单号
		Order order = orderService.getOne(Wrappers.<Order>lambdaQuery().eq(Order::getOutTradeNo, out_trade_no));
		if (order == null){
			log.info(errMsg + "-订单无数据");
			return "error";
		}
		//寄售和购买
		orderService.payCommonSuccess(order, PAY_CODE);
		return "success";
	}

	@ApiLog("进货回调")
	@RequestMapping(value = "/trade_notify_url", method = {RequestMethod.GET, RequestMethod.POST})
	@ApiOperation(value = "异步通知相应-进货回调", notes = "异步通知相应")
	@ApiOperationSupport(order = 100)
	public String tradeNotify(HttpServletRequest request) {
		String errMsg = "进货回调";//抢购改为进货
		log.info(errMsg, request.getParameterMap().toString());
		if (!NotifyUtils.rsaCheck(properties, request.getParameterMap())) {
			//这里处理验签失败
			log.info(errMsg + "-处理验签失败" + request.getParameterMap());
			//打款失败
			return "error";
		}
		String out_trade_no = request.getParameter("out_trade_no");//获取请求参数中的商户订单号
		log.info(errMsg, "out_trade_no == " + out_trade_no);
		Order order = orderService.getOne(Wrappers.<Order>lambdaQuery().eq(Order::getOutTradeNo, out_trade_no));
		if (ObjectUtil.isNull(order)){
			log.info(errMsg + "-订单无数据");
			return "error";
		}
		if(order.getOrderType() == 3){
			log.info(errMsg, "寄售订单 == " + order.getOrderType());
			//查询寄售订单信息
			OrderConsign orderConsign  = orderConsignService.getOne(Wrappers.<OrderConsign>lambdaQuery().eq(OrderConsign::getOutTradeNo, out_trade_no));
			if (ObjectUtil.isNull(orderConsign)){
				log.info(errMsg + "-寄售订单无数据");
				return "error";
			}
			//寄售金额
			Double price = orderConsign.getConsignPrice();
			//查询寄售订单中的寄售人
			Consign consign  = consignService.getOne(Wrappers.<Consign>lambdaQuery().eq(Consign::getId, orderConsign.getConsignId()));
			if (ObjectUtil.isNull(consign)){
				log.info(errMsg + "-寄售无数据");
				return "error";
			}
			//授权号
			String body = request.getParameter("body");
			OrderGrant orderGrant = orderGrantService.getOne(Wrappers.<OrderGrant>lambdaQuery().eq(OrderGrant::getAuthNo, body));
			if (orderGrant != null){
				logger.info(errMsg + "-授权无数据", orderGrant.toString());
				//以单个授权金额为准
				if (!Objects.equals(price, orderGrant.getPrice())){
					price = orderGrant.getPrice();
				}
			}
			log.info(errMsg + "-body：" + body);
			//寄售来源为后台 不打款 订单的打款 2是订单
			if (consign.getConsignFor() == 2){
				//判断商品抢购价和进货价是否产生收益
				if(consign.getObtainPrice() < consign.getConsignPrice()){
					//收益金额 收益金额等于抢购价减去取得价
					BigDecimal bigDecimal = new BigDecimal(price).subtract(new BigDecimal(consign.getObtainPrice())).setScale(2, BigDecimal.ROUND_HALF_UP);
					//获取配置参数
					BigDecimal taxRatio = new BigDecimal(ParamCache.getValue(CommonConstant.PLATFORM_TAX_RATIO));
					//税费金额
					BigDecimal bigDecimal1 = bigDecimal.multiply(taxRatio).setScale(2, BigDecimal.ROUND_HALF_UP);
					//收款金额需扣除税费
					price = new BigDecimal(consign.getConsignPrice()).subtract(bigDecimal1).setScale(2, BigDecimal.ROUND_DOWN).doubleValue();
				}
				//获取寄售人信息
				UserApp userApp = new UserApp();
				UserApp query = userApp.selectOne(Wrappers.<UserApp>lambdaQuery().eq(UserApp::getUserId,consign.getConsignUserId()));
				transfer(query, Double.toString(price), orderConsign.getId());
			}else{
				log.info(errMsg, "寄售来源为后台  == 无需打款" );
				OrderConsign updateConsign = new OrderConsign();
				updateConsign.setId(orderConsign.getId());
				updateConsign.setConfirmTime(DateUtil.now());
				updateConsign.setIsConfirm(4);
				updateConsign.setBody("平台无需打款");
				orderConsignService.updateById(updateConsign);
			}
		}else{
			log.info(errMsg + "-购买订单回调");
		}
		//修改订单状态
		orderService.payCommonSuccess(order,PAY_CODE);
		return "success";
	}

	/**
	 * 用户仓单收款
	 * 1、向用户打款
	 * 2、修改寄售订单金额
	 * @param name 用户
	 * @param transAmount 金额
	 */
	public void transfer(String identity, String transAmount, String name){
		try {
			String privateKey = "MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCU4XTbNjnNOmuEnwBEgUBOVLK5CaUiUFKEkVW1/2sTlijARZzLtzwXfbkvzHEhCSu+E+OA1Futbh5HwNAC06bvqYDS+TXrFuZ0LcDaU92lk5Hp/ed8NhRXtm0gss1TS0v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c1kN5AoGARaRHrt3TeojCuONJBUiyERKDseFgxCC9QeLkY3/Cx86yoTMWxlRRSyuHyUTYAwXApSC65GLsntcUJwsLiLmcvfVtEK6vuhKRh/Nuy5ACFfa/Gawrci/DQ43Q+opmFaoctH+OGHuaLfJywO64xNZKx1F8nGjTEgHQlB3oJ3P1zXECgYBW/GRUU+SevGeLjZTZ9WqG+ztseItnmEwmar9tGhR9TNv3vDiL5/fsAfI8ApMiIzDe6+QfS5Lxx5rD6V4Et/zBpsf8JzqP2eDiTe9UiHxDr2v5NIxelf404VZcdRh83u84lCJTa/ZYanFu94UW6h70MHhDWtiWddtFR3EXt5hD9w==";
			String alipayPublicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAhIxPBQL0OKBc6fcU/9PdVTMA7L2s314oU2w1q06ywQSDdhF3RY1Bo0Eqh4Zg8QpPirFeyAc4rhFjyKZRlngQXrybcAhUfswD86QQGodObe3aA9bbWdXiTt10Q5CBk5GImadNiEW6Adh+0bY5ezf1RbxIjbGDfH6x5gatZnpjPswiHMQnskZtg9JSfE2u8WEKuSaH8yhnkllHpIHWnWvFvXwNVNycXdmDrEe7gIB1yCouNK6/DZ7IQH2AajSuvbxmCqO0MzywEfgvLqE0GFVsKKmXvgJebRAnW9RmGhmrxvEIceXCjR3tbxM9gX8lioDlqKnBootTgAbjIJ5VrPvKPwIDAQAB";
			AlipayConfig alipayConfig = new AlipayConfig();
			alipayConfig.setServerUrl("https://openapi.alipay.com/gateway.do");
			alipayConfig.setAppId("2021003125657245");
			alipayConfig.setPrivateKey(privateKey);
			alipayConfig.setFormat("json");
			alipayConfig.setAlipayPublicKey(alipayPublicKey);
			alipayConfig.setCharset("UTF8");
			alipayConfig.setSignType("RSA2");
			//设置应用公钥证书路径//appCertPublicKey_2021003125657245
			alipayConfig.setAppCertPath(properties.getAppCertPath());
			//设置支付宝公钥证书路径//alipayCertPublicKey_RSA2
			alipayConfig.setAlipayPublicCertPath(properties.getAliPayCertPath());
			//设置支付宝根证书路径
			alipayConfig.setRootCertPath(properties.getAliPayRootCertPath());
			AlipayClient alipayClient = new DefaultAlipayClient(alipayConfig);
			AlipayFundTransUniTransferModel model = new AlipayFundTransUniTransferModel();
			model.setOutBizNo(CommonUtil.genTimeID());
			model.setRemark("贵州中宏科技有限公司进货仓单收款");
			model.setBusinessParams("{\"payer_show_name_use_alias\":\"true\"}");
			model.setBizScene("DIRECT_TRANSFER");
			Participant payeeInfo = new Participant();
			payeeInfo.setIdentity(identity);
			payeeInfo.setIdentityType("ALIPAY_USER_ID");
			payeeInfo.setName(name);
			model.setPayeeInfo(payeeInfo);
			model.setTransAmount(transAmount);
			model.setProductCode("TRANS_ACCOUNT_NO_PWD");
			model.setOrderTitle("进货仓单收款");
			AlipayFundTransUniTransferRequest request = new AlipayFundTransUniTransferRequest();
			request.setBizModel(model);
			AlipayFundTransUniTransferResponse response = alipayClient.certificateExecute(request);
			if (!response.isSuccess()){
				log.info("向用户【" + name +"】打款失败，打款账号："  + identity);
				logger.info("打款失败", ",打款人：" + name + "支付宝账号：" + identity);
			}else{
				log.info("向用户【" + name +"】打款成功，打款账号："  + identity);
				logger.info("打款成功", ",打款人：" + name + "支付宝账号：" + identity);
			}
		} catch (AlipayApiException e) {
			e.printStackTrace();
			String msg = "打款失败, ,打款人：" + name + "支付宝账号：" + identity;
			logger.info(msg, e.getMessage());
			logger.info("打款失败", ",打款人：" + name + "支付宝账号：" + identity);
		}

	}

	/**
	 * 用户仓单收款
	 * 1、向用户打款
	 * 2、修改寄售订单金额
	 * @param user 用户
	 * @param transAmount 金额
	 * @param orderConsignId 寄售（进货）Id
	 */
	private void transfer(UserApp user, String transAmount, Long orderConsignId){
		OrderConsign orderConsign = new OrderConsign();
		orderConsign.setId(orderConsignId);
		orderConsign.setConfirmTime(DateUtil.now());
		if (user == null){
			orderConsign.setIsConfirm(3);//异常
			orderConsign.setBody("该用户不存在");
			orderConsignService.updateById(orderConsign);
			return;
		}
		if (StringUtil.isEmpty(user.getAlipayUserId())){
			orderConsign.setIsConfirm(3);//异常
			orderConsign.setBody("用户【" + user.getUserId() +" 】无支付宝账号数据");
			orderConsignService.updateById(orderConsign);
			return;
		}
		User u = userService.getById(user.getUserId());
		if (u == null){
			orderConsign.setIsConfirm(3);//异常
			orderConsign.setBody("该用户不存在,可能被删除或者冻结");
			orderConsignService.updateById(orderConsign);
			return;
		}
		if (StringUtil.isEmpty(u.getRealName())){
			orderConsign.setIsConfirm(3);//异常
			orderConsign.setBody("该用户无法获取真实名字");
			orderConsignService.updateById(orderConsign);
			return;
		}
		String identity = user.getAlipayUserId();
		String name = u.getRealName();
		try {
			String privateKey = "MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCU4XTbNjnNOmuEnwBEgUBOVLK5CaUiUFKEkVW1/2sTlijARZzLtzwXfbkvzHEhCSu+E+OA1Futbh5HwNAC06bvqYDS+TXrFuZ0LcDaU92lk5Hp/ed8NhRXtm0gss1TS0vebOq+3kejErIvVCg9kNMrYMrmdf8G0+zKlCp3vrfdM37IeLXp3GoOckNzHh/LT7rLd7/9QcdSCPixPSwusrfCusw3H093cuWkV9WX4Go/zHTL9rAEwJPOn36OhyVc1oG113ZJiVg7KgsZGOCJJyh9BvlKq2vuKxnylQwq9Kh5e+BfP2FSWs7a1XMj/79JsZTxztJ9tFqcSXQh99vq1nd1AgMBAAECggEAVglIT5oxoxEcq0J7lBshf2Lg+Z/CR2clmKioYImfZm1DVYGlD/DvECA+kYnS4qV7GthBg+S0qi/V3d9mFgwcD6nj4YfVCets+Dyskz8d+p6iFxf820IhVWL+A4Rwta7wxDQrIGwx9+JJCKLYsmNsNUg1WSNdYqO71oHzXMnhVTmYJ6sKOrrBucyI4Ydu9UbfN+DRRGD9seL+Nxh1V2PPXs4ftk2kRlG18LaTPgFba1g8QBIpGDR9gFqM+DvBHUxAWsPRnL1+q0c6o5Ndk7W5f7Ob1zxF/lgqHudiG38jItkwc7MLMOYjb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q5CBk5GImadNiEW6Adh+0bY5ezf1RbxIjbGDfH6x5gatZnpjPswiHMQnskZtg9JSfE2u8WEKuSaH8yhnkllHpIHWnWvFvXwNVNycXdmDrEe7gIB1yCouNK6/DZ7IQH2AajSuvbxmCqO0MzywEfgvLqE0GFVsKKmXvgJebRAnW9RmGhmrxvEIceXCjR3tbxM9gX8lioDlqKnBootTgAbjIJ5VrPvKPwIDAQAB";
			AlipayConfig alipayConfig = new AlipayConfig();
			alipayConfig.setServerUrl("https://openapi.alipay.com/gateway.do");
			alipayConfig.setAppId("2021003125657245");
			alipayConfig.setPrivateKey(privateKey);
			alipayConfig.setFormat("json");
			alipayConfig.setAlipayPublicKey(alipayPublicKey);
			alipayConfig.setCharset("UTF8");
			alipayConfig.setSignType("RSA2");
			//设置应用公钥证书路径//appCertPublicKey_2021003125657245
			alipayConfig.setAppCertPath(properties.getAppCertPath());
			//设置支付宝公钥证书路径//alipayCertPublicKey_RSA2
			alipayConfig.setAlipayPublicCertPath(properties.getAliPayCertPath());
			//设置支付宝根证书路径
			alipayConfig.setRootCertPath(properties.getAliPayRootCertPath());
			AlipayClient alipayClient = new DefaultAlipayClient(alipayConfig);
			AlipayFundTransUniTransferModel model = new AlipayFundTransUniTransferModel();
			model.setOutBizNo(CommonUtil.genTimeID());
			model.setRemark("贵州中宏科技有限公司进货仓单收款");
			model.setBusinessParams("{\"payer_show_name_use_alias\":\"true\"}");
			model.setBizScene("DIRECT_TRANSFER");
			Participant payeeInfo = new Participant();
			payeeInfo.setIdentity(identity);
			payeeInfo.setIdentityType("ALIPAY_USER_ID");
			payeeInfo.setName(name);
			model.setPayeeInfo(payeeInfo);
			model.setTransAmount(transAmount);
			model.setProductCode("TRANS_ACCOUNT_NO_PWD");
			model.setOrderTitle("进货仓单收款");
			AlipayFundTransUniTransferRequest request = new AlipayFundTransUniTransferRequest();
			request.setBizModel(model);
			AlipayFundTransUniTransferResponse response = alipayClient.certificateExecute(request);
			if (!response.isSuccess()){
				log.info("向用户【" + name +" 】打款失败，打款账号："  + identity);
				logger.info("打款失败", ",打款人：" + name + "支付宝账号：" + identity);
				orderConsign.setBody("向用户【" + name +" 】打款失败，打款账号："  + identity);
				orderConsign.setIsConfirm(3);//异常
			}else{
				log.info("向用户【" + name +" 】打款成功，打款账号："  + identity);
				logger.info("打款成功", ",打款人：" + name + "支付宝账号：" + identity);
				orderConsign.setBody("向用户【" + name +" 】打款成功，打款账号："  + identity);
				orderConsign.setIsConfirm(2);//确认
			}
			orderConsignService.updateById(orderConsign);
		} catch (AlipayApiException e) {
			e.printStackTrace();
			logger.info("打款失败", ",打款人：" + name + "支付宝账号：" + identity);
			orderConsign.setIsConfirm(3);//异常
			orderConsign.setBody(e.getMessage());
			orderConsignService.updateById(orderConsign);
		}

	}
}
