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.ConfigForClient;
import org.springblade.yeePay.api.YeepayCommon;
import org.springblade.yeePay.common.YeePayConst;
import org.springblade.yeePay.entity.*;
import org.springblade.yeePay.utils.Sm4GcmUtils;
import org.springblade.yeePay.utils.YeepayUtils;
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
	ConfigForClient configForClient;
	@Autowired
	YeePayConst yeePayConst;

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

	/**
	 * 	解析解密支付通知数据
	 * @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 cipherText 加密数据
	 * */
	public <T>T deCodeNotifyData(String cipherText, Class<T> clazz) {
		log.info("通知数据："+ cipherText);
		try {
			String decryptData = Sm4GcmUtils.decrypt_GCM_NoPadding(
				yeePayConst.getSm4Key(),
				cipherText,
				"",
				""
			);
			log.info("通知解密数据："+ decryptData);
			return JSON.parseObject(decryptData, clazz);
		} catch (Exception e) {
			log.error("回调解析错误： "+ e.getMessage());
		}
		return null;
	}



	public static void main(String[] args) throws CertificateException, NoSuchProviderException {
		YeePayService yeePayService = new YeePayService();
		System.out.println(yeePayService.deCodeNotifyData("\t\t09unXJPmehVbTMxNxEAf5qA3gWQJwlRW4sZOp4oG2Z2BbwOMJzS9GUkLA5UexRPwLMt2QImN_vikdqgNTKg6cLBeJXdT9unwvpPeCnnt-oYAS0fwaHaBuLE4TvsjJa8YyuzDrDRhWc4PB2unhQDxlc9XhcbXx4rpNaGNQnE240ZSqSgURowTDRHHAqBWsEGRoHRJLQCIp-3XDIAqXU56iv4AI4zvhaJuwDpoWuUaQcypS37D3XiIKLy1kzh9_wJ_ljMZtdn1-BgjnN6wIxwupg6QfyZKwIo2tg"));
	}

	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;
	}


}
