package tonglianpayapi

import (
	"crypto/md5"
	"fmt"
	"git.rosy.net.cn/jx-callback/globals"
	"net/http"
	"sort"
	"strings"

	"git.rosy.net.cn/baseapi/platformapi"
	"git.rosy.net.cn/baseapi/utils"
)

const (
	prodURL     = "https://vsp.allinpay.com/apiweb"
	prodURL2    = "https://syb.allinpay.com/apiweb"
	sepcAction  = "unitorder/pay"
	sepcAction2 = "h5unionpay/unionorder"

	sigKey           = "sign"
	PayTypeWxXcx     = "W06"
	PayTypeWxCode    = "W01"
	PayTypeZfbApp    = "A03"
	PayTypeZfbQrcode = "A01"
	PayTypeZfbJS     = "A02"
	PayTypeH5        = "H5"

	ResponseCodeSuccess = "SUCCESS"
	ResponseCodeFail    = "FAIL"
)

type API struct {
	appID  string
	cusID  string
	appKey string

	client *http.Client
	config *platformapi.APIConfig
}

type CreateUnitorderOrderParam struct {
	CusID     string `json:"cusid"`
	AppID     string `json:"appid"`
	Trxamt    int    `json:"trxamt"`    //交易金额 单位为分
	Reqsn     string `json:"reqsn"`     //商户交易单号
	NotifyUrl string `json:"notifyUrl"` //接收微信支付异步通知回调地址，通知url必须为直接可访问的url，不能携带参数。
	Acct      string `json:"acct"`
	PayType   string `json:"paytype"`
	SubAppID  string `json:"subAppID"`
}

type CreateUnitOrderOrderResult struct {
	RetCode   string `json:"retCode"`
	RetMsg    string `json:"retMsg"`
	CusID     string `json:"cusID"`
	AppID     string `json:"appID"`
	TrxID     string `json:"trxID"`
	ChnltrxID string `json:"chnltrxID"`
	Reqsn     string `json:"reqsn"`
	RandomStr string `json:"randomStr"`
	TrxStatus string `json:"trxStatus"`
	FinTime   string `json:"finTime"`
	ErrMsg    string `json:"errMsg"`
	PayInfo   string `json:"payInfo"`
	Sign      string `json:"sign"`
}

type PayInfo struct {
	AppID     string `json:"appID"`
	TimeStamp string `json:"timeStamp"`
	NonceStr  string `json:"nonceStr"`
	Package   string `json:"package"`
	SignType  string `json:"signType"`
	PaySign   string `json:"paySign"`
}

type PayRefundParam struct {
	CusID     string `json:"cusid"`
	AppID     string `json:"appid"`
	Trxamt    int    `json:"trxamt"` //交易金额 单位为分
	Reqsn     string `json:"reqsn"`  //商户交易单号
	OldReqsn  string `json:"oldReqsn"`
	Remark    string `json:"remark"`
	RandomStr string `json:"randomStr"`
	Sign      string `json:"sign"`
	TrxID     string `json:"trxID"`
	OldTrxID  string `json:"oldTrxID"`
}

type PayRefundResult struct {
	RetCode   string `json:"retCode"`
	RetMsg    string `json:"retMsg"`
	CusID     string `json:"cusID"`
	AppID     string `json:"appID"`
	TrxID     string `json:"trxID"`
	Reqsn     string `json:"reqsn"`
	TrxStatus string `json:"trxStatus"`
	FinTime   string `json:"finTime"`
	ErrMsg    string `json:"errMsg"`
	RandomStr string `json:"randomStr"`
	Sign      string `json:"sign"`
	Fee       string `json:"fee"`
	TrxCode   string `json:"trxCode"`
}

type CreateH5UnitorderOrderParam struct {
	Trxamt    int    `json:"trxamt"`    //交易金额 单位为分
	Reqsn     string `json:"reqsn"`     //商户交易单号
	NotifyUrl string `json:"notifyUrl"` //接收微信支付异步通知回调地址，通知url必须为直接可访问的url，不能携带参数。
	Charset   string `json:"charset"`
	Returl    string `json:"returl"`
	Body      string `json:"body"`
}

func New(appID, appKey, cusID string, config ...*platformapi.APIConfig) *API {
	curConfig := platformapi.DefAPIConfig
	if len(config) > 0 {
		curConfig = *config[0]
	}
	return &API{
		appID:  appID,
		appKey: appKey,
		cusID:  cusID,
		client: &http.Client{Timeout: curConfig.ClientTimeout},
		config: &curConfig,
	}
}

func (a *API) signParam(params map[string]interface{}) (sig string) {
	var valueList []string
	for k, v := range params {
		if k != sigKey {
			if str := fmt.Sprint(v); str != "" {
				valueList = append(valueList, fmt.Sprintf("%s=%s", k, str))
			}
		}
	}
	valueList = append(valueList, fmt.Sprintf("key=%s", a.appKey))
	sort.Sort(sort.StringSlice(valueList))
	sig = strings.Join(valueList, "&")
	binSig := md5.Sum([]byte(sig))
	sig = fmt.Sprintf("%X", binSig)
	return sig
}

func (a *API) AccessAPI(action string, bizParams map[string]interface{}) (retVal map[string]interface{}, err error) {
	params := make(map[string]interface{})
	params["appid"] = a.appID
	params["cusid"] = a.cusID
	params["randomstr"] = utils.GetUUID()
	params["version"] = "12"
	params = utils.MergeMaps(params, bizParams)
	signStr := a.signParam(params)
	params["sign"] = signStr
	var fullURL string
	if action == sepcAction2 {
		fullURL = utils.GenerateGetURL(prodURL2, action, nil)
	} else {
		fullURL = utils.GenerateGetURL(prodURL, action, nil)
	}
	err = platformapi.AccessPlatformAPIWithRetry(a.client,
		func() *http.Request {
			request, _ := http.NewRequest(http.MethodPost, fullURL, strings.NewReader(utils.Map2URLValues(params).Encode()))
			request.Header.Set("charset", "UTF-8")
			request.Header.Set("Content-Type", "application/x-www-form-urlencoded")
			return request
		},
		a.config,
		func(response *http.Response, bodyStr string, jsonResult1 map[string]interface{}) (errLevel string, err error) {
			if jsonResult1 == nil {
				return platformapi.ErrLevelRecoverableErr, fmt.Errorf("mapData is nil")
			}
			if err == nil {
				returnCode := utils.Interface2String(jsonResult1["trxstatus"])
				if returnCode != TrxStatusSuccess {
					errLevel = platformapi.ErrLevelGeneralFail
					err = utils.NewErrorCode(utils.Interface2String(jsonResult1["errmsg"])+utils.Interface2String(jsonResult1["retmsg"]), returnCode)
				}
				retVal = jsonResult1
			}
			return errLevel, err
		})
	return retVal, err
}

func (a *API) CreateUnitorderOrder(param *CreateUnitorderOrderParam) (result *CreateUnitOrderOrderResult, err error) {
	params := make(map[string]interface{})
	params["trxamt"] = param.Trxamt
	params["notify_url"] = param.NotifyUrl
	params["reqsn"] = param.Reqsn
	params["acct"] = param.Acct
	params["paytype"] = param.PayType
	params["sub_appid"] = param.SubAppID
	retVal, err := a.AccessAPI(sepcAction, params)
	globals.SugarLogger.Debugf("===========err := %s", utils.Format4Output(retVal, false))
	globals.SugarLogger.Debugf("===========err := %s", utils.Format4Output(err, false))
	if err == nil {
		utils.Map2StructByJson(retVal, &result, false)
	}
	return result, err
}

func (a *API) PayRefund(param *PayRefundParam) (result *PayRefundResult, err error) {
	params := make(map[string]interface{})
	params["trxamt"] = param.Trxamt
	params["reqsn"] = param.Reqsn
	//params["oldreqsn"] = param.OldReqsn
	params["remark"] = param.Remark
	params["oldtrxid"] = param.OldTrxID
	retVal, err := a.AccessAPI("unitorder/refund", params)
	if err == nil {
		utils.Map2StructByJson(retVal, &result, false)
	}
	return result, err
}

func (a *API) CreateH5UnitorderOrder(param *CreateH5UnitorderOrderParam) (err error) {
	params := make(map[string]interface{})
	params["trxamt"] = param.Trxamt
	params["reqsn"] = param.Reqsn
	params["charset"] = param.Charset
	params["body"] = param.Body
	params["returl"] = param.Returl
	_, err = a.AccessAPI(sepcAction2, params)
	return
}
