package alipay

import (
	"applet/app/cfg"
	"applet/app/md"
	"applet/app/utils/logx"
	"fmt"

	"github.com/iGoogle-ink/gopay"
	"github.com/iGoogle-ink/gopay/alipay"
)

func commClient(appID, priKey, RSA, PKCS string, paySet *md.PayData) (*alipay.Client, error) {
	client := alipay.NewClient(appID, priKey, true)
	client.DebugSwitch = gopay.DebugOn
	//判断密钥的类型
	rsaType := alipay.RSA2
	pkcsType := alipay.PKCS1
	if RSA == "1" {
		rsaType = alipay.RSA
	}
	if PKCS == "1" {
		pkcsType = alipay.PKCS8
	}
	if paySet.PayAliUseType == "1" {
		rsaType = alipay.RSA2
		pkcsType = alipay.PKCS8
	}
	//配置公共参数
	client.SetCharset("utf-8").
		SetSignType(rsaType).
		SetPrivateKeyType(pkcsType)
	//新支付宝支付
	if paySet.PayAliUseType == "1" {
		appCertSN, err := alipay.GetCertSN(cfg.WxappletFilepath.URL + "/" + paySet.PayAppCertSn)
		if err != nil {
			return nil, err
		}
		if appCertSN == "" {
			return nil, err
		}
		client.SetAppCertSN(appCertSN)
		aliPayRootCertSN := "687b59193f3f462dd5336e5abf83c5d8_02941eef3187dddf3d3b83462e1dfcf6"
		client.SetAliPayRootCertSN(aliPayRootCertSN)
		aliPayPublicCertSN, err := alipay.GetCertSN(cfg.WxappletFilepath.URL + "/" + paySet.PayAlipayrsaPublicKey)
		if err != nil {
			return nil, err
		}
		if aliPayPublicCertSN == "" {
			return nil, err
		}
		client.SetAliPayPublicCertSN(aliPayPublicCertSN)
	}
	return client, nil
}

//(实名证件信息比对验证预咨询)
//https://opendocs.alipay.com/apis/api_2/alipay.user.certdoc.certverify.preconsult
func UserCertverifyPreconsult(appID, priKey, userName, certNo, RSA, PKCS string, paySet *md.PayData) (*md.AlipayUserCertdocCertverifyPreconsult, error) {
	client, _ := commClient(appID, priKey, RSA, PKCS, paySet)
	//请求参数
	body := make(gopay.BodyMap)
	body.Set("user_name", userName)
	body.Set("cert_type", "IDENTITY_CARD")
	body.Set("cert_no", certNo)
	var aliPsp md.AlipayUserCertdocCertverifyPreconsult
	err := client.PostAliPayAPISelfV2(body, "alipay.user.certdoc.certverify.preconsult", aliPsp)
	if err != nil {
		return nil, err
	}
	return &aliPsp, err
}

//(实名证件信息比对验证咨询)
//https://opendocs.alipay.com/apis/api_2/alipay.user.certdoc.certverify.consult
func UserCertverifyConsult(appID, priKey, verifyId, RSA, PKCS string, paySet *md.PayData) (*md.AlipayUserCertdocCertverifyConsult, error) {
	client, _ := commClient(appID, priKey, RSA, PKCS, paySet)
	//请求参数
	body := make(gopay.BodyMap)
	body.Set("verify_id", verifyId)
	var aliPsp md.AlipayUserCertdocCertverifyConsult
	err := client.PostAliPayAPISelfV2(body, "alipay.user.certdoc.certverify.consult", aliPsp)
	if err != nil {
		return nil, err
	}
	return &aliPsp, err
}

// TradeAppPay is 支付宝APP支付
// 抖音头条小程序使用APP调起
func TradeAppPay(appID, priKey, subject, orderID, amount, notiURL, RSA, PKCS string, paySet *md.PayData) (string, error) {
	//初始化支付宝客户端
	// appID 是在支付宝申请的APPID
	// priKey 是支付宝私钥
	// subject 是支付订单的主题
	// orderID 是智莺这边生成的订单id
	// amount 是付费金额
	// notiURL 通知地址url
	// passback_params 回调通知参数

	client := alipay.NewClient(appID, priKey, true)
	client.DebugSwitch = gopay.DebugOn
	//判断密钥的类型
	rsa_type := alipay.RSA2
	pkcs_type := alipay.PKCS1
	if RSA == "1" {
		rsa_type = alipay.RSA
	}
	if PKCS == "1" {
		pkcs_type = alipay.PKCS8
	}
	if paySet.PayAliUseType == "1" {
		rsa_type = alipay.RSA2
		pkcs_type = alipay.PKCS8
	}
	//配置公共参数
	client.SetCharset("utf-8").
		SetSignType(rsa_type).
		SetPrivateKeyType(pkcs_type)
	if notiURL != "" {
		client.SetNotifyUrl(notiURL)
	}
	//新支付宝支付
	if paySet.PayAliUseType == "1" {
		appCertSN, err := alipay.GetCertSN(cfg.WxappletFilepath.URL + "/" + paySet.PayAppCertSn)
		fmt.Println("-应用-")
		fmt.Println(appCertSN)
		if err != nil {
			fmt.Println(err)
			return "", err
		}
		if appCertSN == "" {
			fmt.Println(err)
			return "", err
		}
		client.SetAppCertSN(appCertSN)
		//aliPayRootCertSN, err := alipay.GetCertSN(cfg.WxappletFilepath.URL + "/" + paySet.PayAlipayRootCertSn)
		aliPayRootCertSN := "687b59193f3f462dd5336e5abf83c5d8_02941eef3187dddf3d3b83462e1dfcf6"
		client.SetAliPayRootCertSN(aliPayRootCertSN)
		aliPayPublicCertSN, err := alipay.GetCertSN(cfg.WxappletFilepath.URL + "/" + paySet.PayAlipayrsaPublicKey)
		fmt.Println("-公钥-")
		fmt.Println(aliPayPublicCertSN)

		if err != nil {
			fmt.Println(err)
			return "", err
		}
		if aliPayPublicCertSN == "" {
			fmt.Println(err)
			return "", err
		}
		client.SetAliPayPublicCertSN(aliPayPublicCertSN)
	}
	fmt.Println(client)
	//请求参数
	body := make(gopay.BodyMap)
	body.Set("subject", subject)
	body.Set("body", subject)
	body.Set("out_trade_no", orderID)
	body.Set("total_amount", amount)
	body.Set("timeout_express", "30m")

	// body.Set("passback_params", orderID)
	//手机APP支付参数请求
	payParam, err := client.TradeAppPay(body)
	if err != nil {
		return "", logx.Warn(err)
	}
	return payParam, nil
}

// TradeAppPay is 支付宝H5支付
func TradeWapPay(appID, priKey, subject, orderID, amount, notiURL, RSA, PKCS, page_url string, paySet *md.PayData) (string, error) {
	//aliPayPublicKey := "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA1wn1sU/8Q0rYLlZ6sq3enrPZw2ptp6FecHR2bBFLjJ+sKzepROd0bKddgj+Mr1ffr3Ej78mLdWV8IzLfpXUi945DkrQcOUWLY0MHhYVG2jSs/qzFfpzmtut2Cl2TozYpE84zom9ei06u2AXLMBkU6VpznZl+R4qIgnUfByt3Ix5b3h4Cl6gzXMAB1hJrrrCkq+WvWb3Fy0vmk/DUbJEz8i8mQPff2gsHBE1nMPvHVAMw1GMk9ImB4PxucVek4ZbUzVqxZXphaAgUXFK2FSFU+Q+q1SPvHbUsjtIyL+cLA6H/6ybFF9Ffp27Y14AHPw29+243/SpMisbGcj2KD+evBwIDAQAB"
	privateKey := priKey
	//判断密钥的类型
	rsa_type := alipay.RSA2
	pkcs_type := alipay.PKCS1
	if RSA == "1" {
		rsa_type = alipay.RSA
	}
	if PKCS == "1" {
		pkcs_type = alipay.PKCS8
	}
	if paySet.PayAliUseType == "1" {
		rsa_type = alipay.RSA2
		pkcs_type = alipay.PKCS8
	}
	//初始化支付宝客户端
	//    appId：应用ID
	//    privateKey：应用秘钥
	//    isProd：是否是正式环境
	client := alipay.NewClient(appID, privateKey, true)
	//配置公共参数
	client.SetCharset("utf-8").
		SetSignType(rsa_type).
		SetPrivateKeyType(pkcs_type).
		SetReturnUrl(page_url).
		SetNotifyUrl(notiURL)
	//新支付宝支付
	if paySet.PayAliUseType == "1" {
		appCertSN, err := alipay.GetCertSN(cfg.WxappletFilepath.URL + "/" + paySet.PayAppCertSn)
		if err != nil {
			fmt.Println(err)
			return "", err
		}
		if appCertSN == "" {
			fmt.Println(err)
			return "", err
		}
		client.SetAppCertSN(appCertSN)
		//aliPayRootCertSN, err := alipay.GetCertSN(cfg.WxappletFilepath.URL + "/" + paySet.PayAlipayRootCertSn)
		//if err != nil {
		//	fmt.Println(err)
		//	return "", err
		//}
		//if aliPayRootCertSN == "" {
		//	fmt.Println(err)
		//	return "", err
		//}
		aliPayRootCertSN := "687b59193f3f462dd5336e5abf83c5d8_02941eef3187dddf3d3b83462e1dfcf6"
		client.SetAliPayRootCertSN(aliPayRootCertSN)
		aliPayPublicCertSN, err := alipay.GetCertSN(cfg.WxappletFilepath.URL + "/" + paySet.PayAlipayrsaPublicKey)
		if err != nil {
			fmt.Println(err)
			return "", err
		}
		if aliPayPublicCertSN == "" {
			fmt.Println(err)
			return "", err
		}
		client.SetAliPayPublicCertSN(aliPayPublicCertSN)
	}
	//请求参数
	body := make(gopay.BodyMap)
	body.Set("subject", subject)
	body.Set("out_trade_no", orderID)
	// quit_url is 用户付款中途退出返回商户网站的地址
	body.Set("quit_url", notiURL)
	body.Set("total_amount", amount)
	// product_code is 销售产品码，商家和支付宝签约的产品码
	body.Set("product_code", "QUICK_WAP_WAY")
	//手机网站支付请求
	payUrl, err := client.TradeWapPay(body)
	if err != nil {
		return "", logx.Warn(err)

	}
	return payUrl, nil
}

// TradeAppPay is 支付宝小程序本身支付
func TradeCreate(appID, priKey, subject, orderID, amount, notiURL, RSA, PKCS string, paySet *md.PayData) (*alipay.TradeCreateResponse, error) {
	//aliPayPublicKey := "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA1wn1sU/8Q0rYLlZ6sq3enrPZw2ptp6FecHR2bBFLjJ+sKzepROd0bKddgj+Mr1ffr3Ej78mLdWV8IzLfpXUi945DkrQcOUWLY0MHhYVG2jSs/qzFfpzmtut2Cl2TozYpE84zom9ei06u2AXLMBkU6VpznZl+R4qIgnUfByt3Ix5b3h4Cl6gzXMAB1hJrrrCkq+WvWb3Fy0vmk/DUbJEz8i8mQPff2gsHBE1nMPvHVAMw1GMk9ImB4PxucVek4ZbUzVqxZXphaAgUXFK2FSFU+Q+q1SPvHbUsjtIyL+cLA6H/6ybFF9Ffp27Y14AHPw29+243/SpMisbGcj2KD+evBwIDAQAB"
	privateKey := priKey
	rsa_type := alipay.RSA2
	pkcs_type := alipay.PKCS1
	if RSA == "1" {
		rsa_type = alipay.RSA
	}
	if PKCS == "1" {
		pkcs_type = alipay.PKCS8
	}
	if paySet.PayAliUseType == "1" {
		rsa_type = alipay.RSA2
		pkcs_type = alipay.PKCS8
	}
	//初始化支付宝客户端
	//    appId：应用ID
	//    privateKey：应用私钥，支持PKCS1和PKCS8
	//    isProd：是否是正式环境
	client := alipay.NewClient(appID, privateKey, true)
	//配置公共参数
	client.SetCharset("utf-8").
		SetSignType(rsa_type).
		SetPrivateKeyType(pkcs_type).
		SetNotifyUrl(notiURL)
	if paySet.PayAliUseType == "1" {
		appCertSN, err := alipay.GetCertSN(cfg.WxappletFilepath.URL + "/" + paySet.PayAppCertSn)
		if err != nil {
			fmt.Println(err)
			return nil, err
		}
		if appCertSN == "" {
			fmt.Println(err)
			return nil, err
		}
		client.SetAppCertSN(appCertSN)
		//aliPayRootCertSN, err := alipay.GetCertSN(cfg.WxappletFilepath.URL + "/" + paySet.PayAlipayRootCertSn)
		//if err != nil {
		//	fmt.Println(err)
		//	return nil, err
		//}
		//if aliPayRootCertSN == "" {
		//	fmt.Println(err)
		//	return nil, err
		//}
		aliPayRootCertSN := "687b59193f3f462dd5336e5abf83c5d8_02941eef3187dddf3d3b83462e1dfcf6"
		client.SetAliPayRootCertSN(aliPayRootCertSN)
		aliPayPublicCertSN, err := alipay.GetCertSN(cfg.WxappletFilepath.URL + "/" + paySet.PayAlipayrsaPublicKey)
		if err != nil {
			fmt.Println(err)
			return nil, err
		}
		if aliPayPublicCertSN == "" {
			fmt.Println(err)
			return nil, err
		}
		client.SetAliPayPublicCertSN(aliPayPublicCertSN)
	}
	//请求参数
	body := make(gopay.BodyMap)
	body.Set("subject", subject)
	// 支付宝小程序支付时 buyer_id 为必传参数，需要提前获取，获取方法如下两种
	//    1、alipay.SystemOauthToken()     返回取值：rsp.SystemOauthTokenResponse.UserId
	//    2、client.SystemOauthToken()    返回取值：aliRsp.SystemOauthTokenResponse.UserId
	buyer_id, err := client.SystemOauthToken(body)
	if err != nil {
		return nil, logx.Warn(err)
	}
	body.Set("buyer_id", buyer_id)
	body.Set("out_trade_no", orderID)
	body.Set("total_amount", amount)
	//创建订单
	aliRsp, err := client.TradeCreate(body)

	if err != nil {
		return nil, logx.Warn(err)
	}
	logx.Warn("aliRsp:", *aliRsp)
	logx.Warn("aliRsp.TradeNo:", aliRsp.Response.TradeNo)
	return aliRsp, nil

}
