package svc

import (
	"applet/app/cfg"
	"applet/app/db"
	"applet/app/e"
	"applet/app/md"
	"applet/app/utils"
	"applet/app/utils/logx"
	"code.fnuoos.com/go_rely_warehouse/zyos_go_pay.git/pay"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/iGoogle-ink/gopay/alipay"
)

// 支付宝回调处理
func AlipayCallback(c *gin.Context) (string, error) {
	data, ok := c.Get("callback")
	if data == nil || !ok {
		return "", e.NewErrCode(e.ERR_INVALID_ARGS)
	}
	args := data.(*md.AliPayCallback)
	_, ok = db.DBs[args.MasterID]
	if !ok {
		return "", logx.Warn("Alipay Failed : master_id not found")
	}
	c.Set("mid", args.MasterID)
	// 回调交易状态失败
	if args.TradeStatus != "TRADE_SUCCESS" {
		return "", logx.Warn("Alipay Failed : trade status failed")
	}
	return args.OutTradeNo, nil
}

func PrepareAlipayCode(c *gin.Context, p *md.AliPayPayParams) (interface{}, error) {
	req, err := CommAlipayConfig(c, p)
	if err != nil {
		return "", err
	}
	var param interface{}
	switch req["platform"] {
	case md.PLATFORM_ALIPAY_APPLET:
		param, err = pay.AlipayApplet(req)
	case md.PLATFORM_WAP:
		param, err = pay.AlipayWap(req)
	case md.PLATFORM_ANDROID, md.PLATFORM_IOS:
		param, err = pay.AlipayApp(req)
	default:
		return "", e.NewErrCode(e.ERR_PLATFORM)
	}
	if err != nil {
		fmt.Println("支付宝错误日志")
		fmt.Println(param)
		fmt.Println(err)
		return "", e.NewErrCode(e.ERR_ALIPAY_ORDER_ERR)
	}
	return utils.AnyToString(param), nil

}

func CommAlipayConfig(c *gin.Context, p *md.AliPayPayParams) (map[string]string, error) {
	//获取支付配置
	req := map[string]string{
		"pay_ali_use_type": SysCfgGet(c, "pay_ali_use_type"),
		"private_key":      SysCfgGet(c, "pay_ali_private_key"),
		"app_id":           SysCfgGet(c, "pay_ali_app_id"),
		"rsa":              SysCfgGet(c, "pay_ali_key_len_type"),
		"pkcs":             SysCfgGet(c, "pay_ali_key_format_type"),
	}
	if req["pay_ali_use_type"] == "1" {
		req["private_key"] = SysCfgGet(c, "pay_ali_new_private_key")
		req["app_id"] = SysCfgGet(c, "pay_ali_new_app_id")
		appCertSN, err := alipay.GetCertSN(cfg.WxappletFilepath.URL + "/" + SysCfgGet(c, "pay_app_cert_sn"))
		if err != nil {
			fmt.Println(err)
			return nil, err
		}
		if appCertSN == "" {
			fmt.Println(err)
			return nil, err
		}
		req["pay_app_cert_sn"] = appCertSN
		aliPayPublicCertSN, err := alipay.GetCertSN(cfg.WxappletFilepath.URL + "/" + SysCfgGet(c, "pay_alipayrsa_public_key"))
		if err != nil {
			fmt.Println(err)
			return nil, err
		}
		if aliPayPublicCertSN == "" {
			fmt.Println(err)
			return nil, err
		}
		req["pay_alipayrsa_public_key"] = aliPayPublicCertSN
	}
	if req["private_key"] == "" || req["app_id"] == "" {
		return req, e.NewErr(400, "请在后台正确配置支付宝")
	}
	req["ord_id"] = p.OrdId
	req["amount"] = p.Amount
	req["subject"] = p.Subject
	req["order_type"] = p.OrderType
	req["notify_url"] = fmt.Sprintf(md.CALLBACK_URL, c.Request.Host, c.GetString("mid"), p.OrderType, md.ALIPAY)
	req["platform"] = c.GetHeader("Platform")
	req["page_url"] = c.Query("page_url")
	utils.FilePutContents(c.GetString("mid")+"alipay", utils.SerializeStr(req))
	return req, nil
}
