package md5

import (
	config "bwallet/conf"
	"bwallet/pkg/handler"
	"bwallet/pkg/util"
	"errors"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/binding"
	"net/url"
	"sort"
	"strconv"
	"strings"
	"time"
)

var AppSecret string

// MD5 组合加密
func Md5() gin.HandlerFunc {
	return func(c *gin.Context) {
		sign, err := verifySign(c)

		if sign != nil {
			handler.SendResponse(c, nil, sign)
			c.Abort()
			return
		}

		if err != nil {
			handler.SendResponse(c, err, nil)
			c.Abort()
			return
		}

		c.Next()
	}
}

// 验证签名
func verifySign(c *gin.Context) (map[string]string, error) {
	var params = make(map[string]interface{})
	if c.Request.Method == "POST" || c.Request.Method == "PUT" {
		c.ShouldBindBodyWith(&params, binding.JSON)

		//var bodyBytes []byte
		//if c.Request.Body != nil {
		//	bodyBytes, _ = ioutil.ReadAll(c.Request.Body)
		//}
		//// 把刚刚读出来的再写进去
		//c.Request.Body = ioutil.NopCloser(bytes.NewBuffer(bodyBytes))
		//json.Unmarshal(bodyBytes, &params)
		//fmt.Println(params)
	}

	if "GET" == c.Request.Method {
		keys := c.Request.URL.Query()
		for k, v := range keys {
			params[k] = v[0]
		}
	}
	_ = c.Request.ParseForm()
	req := c.Request.Form
	for key, value := range params {
		req.Set(key, util.ToString(value))
	}

	debug := strings.Join(req["debug"], "")
	ak := strings.Join(req["ak"], "")
	sn := strings.Join(req["sn"], "")
	ts := strings.Join(req["ts"], "")

	// 验证来源
	value, ok := config.ApiAuthConfig[ak]
	if ok {
		AppSecret = value["md5"]
	} else {
		return nil, errors.New("ak Error")
	}

	if debug == "1" {
		currentUnix := util.GetCurrentUnix()
		req.Set("ts", strconv.FormatInt(currentUnix, 10))
		res := map[string]string{
			"ts": strconv.FormatInt(currentUnix, 10),
			"sn": createSign(req),
		}
		return res, nil
	}

	// 验证过期时间
	timestamp := time.Now().Unix()
	exp, _ := strconv.ParseInt(config.AppSignExpiry, 10, 64)
	tsInt, _ := strconv.ParseInt(ts, 10, 64)
	if tsInt > timestamp || timestamp-tsInt >= exp {
		return nil, errors.New("ts Error")
	}

	// 验证签名
	if sn == "" || sn != createSign(req) {
		return nil, errors.New("sn Error")
	}

	return nil, nil
}

// 创建签名
func createSign(params url.Values) string {
	// 自定义 MD5 组合
	return util.EncodeMD5(AppSecret + createEncryptStr(params) + AppSecret)
}

func createEncryptStr(params url.Values) string {
	var key []string
	var str = ""
	for k := range params {
		if k != "sn" && k != "debug" {
			key = append(key, k)
		}
	}
	sort.Strings(key)
	for i := 0; i < len(key); i++ {
		if i == 0 {
			str = fmt.Sprintf("%v=%v", key[i], params.Get(key[i]))
		} else {
			str = str + fmt.Sprintf("&%v=%v", key[i], params.Get(key[i]))
		}
	}
	return str
}
