package org.springblade.yeePay.service;

import cn.hutool.core.lang.Assert;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yeepay.yop.sdk.exception.YopClientException;
import com.yeepay.yop.sdk.security.DigestAlgEnum;
import com.yeepay.yop.sdk.service.common.YopClient;
import com.yeepay.yop.sdk.service.common.YopClientBuilder;
import com.yeepay.yop.sdk.service.common.request.YopRequest;
import com.yeepay.yop.sdk.service.common.response.YopResponse;
import com.yeepay.yop.sdk.utils.FileUtils;
import com.yeepay.yop.sdk.utils.Sm2CertUtils;
import com.yeepay.yop.sdk.utils.Sm2Utils;
import lombok.extern.slf4j.Slf4j;
import org.bouncycastle.jcajce.provider.asymmetric.ec.BCECPrivateKey;
import org.springblade.core.tool.api.R;
import org.springblade.wx.config.WXConfiger;
import org.springblade.yeePay.common.YeePayConst;
import org.springblade.yeePay.entity.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Service;
import java.security.NoSuchProviderException;
import java.security.PrivateKey;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.*;

@Service
@Slf4j
public class YeePayService {
	@Autowired
	WXConfiger wxConfiger;
	@Autowired
	YeePayConst yeePayConst;
	@Autowired
	private ApplicationEventPublisher eventPublisher;

	YopClient yopClient = YopClientBuilder.builder().build();

	/**
	 *	易宝 公众号配置
	 * @param configAppDto
	 * @return*/
	public R configApp(ConfigAppDto configAppDto) {
		YopRequest request = new YopRequest(yeePayConst.getWeChatConfigAddUrl(), "POST");
		addMerchantNo(request);
		if(configAppDto.getAppIdList()!=null){
			request.addParameter("appIdList", JSON.toJSONString(configAppDto.getAppIdList()));
		}
		if(configAppDto.getTradeAuthDirList()!=null){
			request.addParameter("tradeAuthDirList", JSON.toJSONString(configAppDto.getTradeAuthDirList()));
		}
		try {
			YopResponse response = yopClient.request(request);
			return R.data(JSON.parseObject(response.getStringResult()));
		} catch (YopClientException e) {
			e.printStackTrace();
		}
		return R.fail("配置失败");
	}

	/**
	 *	易宝 查询公众号配置
	 *
	 * @param appIdType
	 * @return*/
	public R queryApp(String appIdType) {
		YopRequest request = new YopRequest(yeePayConst.getWeChatConfigQueryUrl(), "GET");
		if(appIdType!=null){
			request.addParameter("appIdType",appIdType);
		}
		addMerchantNo(request);
		try {
			YopResponse response = yopClient.request(request);
			return R.data(JSON.parseObject(response.getStringResult()));
		} catch (YopClientException e) {
			e.printStackTrace();
		}
		return R.fail("查询失败");
	}

	/**
	 * 	易宝 统一下单
	 *
	 * @param initOrderDto
	 * @return*/
	public R initOrder(InitOrderDto initOrderDto){
		YopRequest request = new YopRequest(yeePayConst.getPrePayUrl(), "POST");
//		initOrderDto.setNotifyUrl(yeePayConst.getPayNotify());
		addMerchantNo(request);
		addParamsFromObj(initOrderDto,request,initOrderDto.getClass());
		return execute(request);
	}


	/**
	 * 	添加请求参数
	 * @param obj 请求所需DTO对象
	 * @param request 所需添加参数请求
	 * @param clazz */
	private void addParamsFromObj(Object obj, YopRequest request, Class clazz){
		Arrays.stream(clazz.getDeclaredFields())
			.forEach(field -> {
					field.setAccessible(true);
					try {
						String paramValue = Optional.ofNullable(field.get(obj)).orElse("").toString();
						if(paramValue!=null&!"".equals(paramValue)){
							request.addParameter(field.getName(),paramValue);
						}
					} catch (IllegalAccessException e) {
						e.printStackTrace();
					}
				}
			);
	}

	/**
	 * 	解析解密支付通知数据
	 * @param response 加密数据
	 * */
	public JSONObject deCodeNotifyData(Map<String, Object> response) {
		log.info("回调数据："+ JSON.toJSONString(response));
//		Map<String,String> params = notifyParams(response.get("params").toString());

		try {
			String decryptData = Sm4GcmUtils.decrypt_GCM_NoPadding(
				yeePayConst.getSm4Key(),
				response.get("cipherText")+"",
				"",
				""
			);
			log.info("通知解密数据："+ decryptData);
			return JSON.parseObject(decryptData);
		} catch (Exception e) {
			log.error("回调解析错误： "+ e.getMessage());
		}
		return null;
	}

	/**
	 * 	解析解密支付通知数据
	 * @param cipherText 加密数据
	 * */
	public JSONObject deCodeNotifyData(String cipherText) {
		try {
			String decryptData = Sm4GcmUtils.decrypt_GCM_NoPadding(
				yeePayConst.getSm4Key(),
				cipherText,
				"",
				""
			);
//			log.info("通知解密数据："+ decryptData);
			return JSON.parseObject(decryptData);
		} catch (Exception e) {
			log.error("回调解析错误： "+ e.getMessage());
		}
		return null;
	}


	/**
	 *	代付：转账到银行卡(单笔出款)
	 * @param transferDto 转账信息
	 * */
	public R transferToCard(TransferDto transferDto) {
		YopRequest request = new YopRequest(yeePayConst.getTransferOrderUrl(), "POST");
		transferDto.setNotifyUrl(yeePayConst.getTransferNotify());
		addMerchantNo(request);
//		request.addParameter("requestNo", IdUtil.simpleUUID());
		addParamsFromObj(transferDto,request, transferDto.getClass());

		return execute(request);
	}

	/**
	 *	代付：转账到银行卡(批量出款)
	 * @param batchTransferDto 转账信息
	 * */
	public R batchTransferToCard(BatchTransferDto batchTransferDto) {
		YopRequest request = new YopRequest(yeePayConst.getBatchTransferUrl(), "GET");
		batchTransferDto.setNotifyUrl(yeePayConst.getBatchTransferNotify());
		batchTransferDto.setParentMerchantNo(yeePayConst.getParentMerchantNo());
		batchTransferDto.setMerchantNo(yeePayConst.getMerchantNo());
//		RequestConfig requestConfig = request.getRequestConfig();
		request.setContent(JSONObject.toJSONString(batchTransferDto));
		return execute(request);
	}

	private R execute(YopRequest request){
		YopResponse response = null;
		try {
			response = yopClient.request(request);
			return R.data(JSON.parseObject(response.getStringResult()));
		} catch (YopClientException e) {
			e.printStackTrace();
		}
		return R.fail("操作失败");
	}

	/**
	 * 	转账订单查询
	 * @param requestNo 易宝订单号
	 * */
	public R queryTransferOrder(String requestNo ){
		YopRequest request = new YopRequest(yeePayConst.getQueryTransferOrderUrl(), "GET");
		addMerchantNo(request);
		request.addParameter("requestNo", requestNo);
		return execute(request);
	}


	private void addMerchantNo(YopRequest request){
		request.addParameter("parentMerchantNo",yeePayConst.getParentMerchantNo());
		request.addParameter("merchantNo",yeePayConst.getMerchantNo());
	}



	/**
	 * 	查询账户余额
	 * */
	public R queryBalance() {
		YopRequest request = new YopRequest(yeePayConst.getQueryBalanceUrl(), "GET");
		request.addParameter("merchantNo", yeePayConst.getMerchantNo());
		return execute(request);
	}

	/**
	 * 	生成订单聚合码
	 * @param createCodeDto
	 * */
	public R createCode(CreateCodeDto createCodeDto) {
		YopRequest request = new YopRequest(yeePayConst.getCreateCodeUrl(), "POST");
		addMerchantNo(request);
		addParamsFromObj(createCodeDto,request,createCodeDto.getClass());
		return execute(request);
	}



	/**
	 * 	网关--充值
	 * @param payGateWayDto 网关入参实体
	 * */
	public R payByGateWay(PayGateWayDto payGateWayDto) {
		YopRequest request = new YopRequest(yeePayConst.getPayGateWayUrl(), "POST");
		payGateWayDto.setNotifyUrl(yeePayConst.getGatewayNotify());
		addMerchantNo(request);
		addParamsFromObj(payGateWayDto,request,payGateWayDto.getClass());
		YopResponse response = null;
		String token = null;
		try {
			response = yopClient.request(request);
			token= JSON.parseObject(response.getStringResult()).getString("token");
		} catch (YopClientException e) {
			e.printStackTrace();
			return R.fail("付款失败！");
		}
		Assert.notNull(token,"获取订单token失败，下单异常");
		List<KeyAndValue> params = new ArrayList<>();
		String timeStr = System.currentTimeMillis() / 1000 + "";
		params.add(KeyAndValue.builder().key("appKey").value(yeePayConst.getAppKey()).build());
		params.add(KeyAndValue.builder().key("merchantNo").value(yeePayConst.getMerchantNo()).build());
		params.add(KeyAndValue.builder().key("token").value(token).build());
		params.add(KeyAndValue.builder().key("timestamp").value(timeStr).build());
		params.add(KeyAndValue.builder().key("directPayType").value("").build());
		params.add(KeyAndValue.builder().key("cardType").value("").build());
		params.add(KeyAndValue.builder().key("userNo").value("").build());
		params.add(KeyAndValue.builder().key("userType").value("").build());
		params.add(KeyAndValue.builder().key("ext").value("").build());

		String payUrl = "https://cash.yeepay.com/cashier/std?" +
			"appKey="+yeePayConst.getAppKey()+
			"&merchantNo=" + yeePayConst.getMerchantNo()+
			"&token=" +token+
			"&timestamp=" +timeStr+
			"&directPayType=" +
			"&cardType=" +
			"&userNo=" +
			"&userType=" +
			"&ext=" +
			"&sign="+this.sign(params);
		return R.data(JSONObject.parseObject("{\n" +
			" \"payUrl\": \""+payUrl+"\"\n" +
			"}"));


	}

	public static void main(String[] args) throws CertificateException, NoSuchProviderException {
		X509Certificate x509Certificate = Sm2CertUtils.getX509Certificate(FileUtils.getResourceAsStream("config/certs/4421256739.cer"));
		System.out.println(x509Certificate);
	}

	private	 String sign(List<KeyAndValue> params){
		StringBuilder stringBuilder = new StringBuilder();
		params.stream().forEach(item ->
			stringBuilder.append(item.getKey()+"="+item.getValue()+"&")
		);
		String s = stringBuilder.deleteCharAt(stringBuilder.length() - 1).toString();
		System.out.println(s);
		String priKey = yeePayConst.getPrivateKey();
		PrivateKey privateKey1 = Sm2Utils.string2PrivateKey(priKey);
		String sign = Sm2Utils.sign(s, (BCECPrivateKey) privateKey1)+"$"+ DigestAlgEnum.SM3.getValue();
		return sign;
	}


	/**
	 * 	扫码支付
	 * @param chargeDto
	 * */
	public R chargePay(ChargeDto chargeDto) {
		YopRequest request = new YopRequest(yeePayConst.getChargeUrl(), "POST");
		addMerchantNo(request);
		request.addParameter("notifyUrl",yeePayConst.getChargeNotify());
		addParamsFromObj(chargeDto,request,chargeDto.getClass());
		return execute(request);
	}

}
