package gw

import (
	"net/url"
	"oit-account-server/library/logger"
	"strconv"

	"github.com/gogf/gf/net/ghttp"
)

// 解码
func decode(r *ghttp.Request, p string) (string, error) {
	dp, err := url.QueryUnescape(p)
	if err != nil {
		logger.Gerror(r, "Decode : url.QueryUnescape() execution failed. err = %v", err)
		return "", err
	}
	return dp, nil
}

// 获取请求头中的User信息
func GetUserInfo(r *ghttp.Request) (string, string, error) {
	id, err := decode(r, r.Header.Get("X-User-Id"))
	if err != nil {
		logger.Gerror(r, "GetUserInfo : decode() execution failed. err = %v", err)
		return "", "", err
	}
	name, err := decode(r, r.Header.Get("X-User-Name"))
	if err != nil {
		logger.Gerror(r, "GetUserInfo : decode() execution failed. err = %v", err)
		return "", "", err
	}

	return id, name, nil
}

// 获取请求头中的账户信息
func GetMerchantInfo(r *ghttp.Request) (string, int64, error) {
	// 玉符商户ID
	merchantId, err := decode(r, r.Header.Get("X-Merchant-Id"))
	if err != nil {
		logger.Gerror(r, "GetMerchantInfo : decode() execution failed. err = %v", err)
		return "", 0, err
	}
	// OIT商户ID
	commercialIdStr, err := decode(r, r.Header.Get("X-Commercial-Id"))
	logger.Ginfo(r, "X-Commercial-Id:", commercialIdStr)
	if err != nil {
		logger.Gerror(r, "GetMerchantInfo : decode() execution failed. err = %v", err)
		return "", 0, err
	}

	var commercialId int64

	if commercialIdStr != "" {
		cid, err := strconv.ParseInt(commercialIdStr, 10, 64)
		if err != nil {
			logger.Gerror(r, "GetMerchantInfo : strconv.ParseInt() execution failed. err = %v", err)
			return "", 0, err
		}
		commercialId = cid
	}

	return merchantId, commercialId, nil
}

// 获取请求头中的RequestID
func GetRequestID(r *ghttp.Request) (string, error) {
	requestId, err := decode(r, r.Header.Get("X-Request-Id"))
	if err != nil {
		logger.Gerror(r, "GetRequestID : decode() execution failed. err = %v", err)
		return "", err
	}
	return requestId, nil
}

// 获取请求头中的权限信息
func GetPerm(r *ghttp.Request) (map[string]string, error) {
	perm, err := decode(r, r.Header.Get("Perms"))
	if err != nil {
		logger.Gerror(r, "GetPerm : decode() execution failed. err = %v", err)
		return nil, err
	}
	//perms := strings.Split(perm, ";")
	m := make(map[string]string)
	//for _, value := range perms {
	//	authName := strings.Split(value, ":")[0]
	//	authValue := strings.Split(value, ":")[1]
	//	m[strings.Trim(authName, " ")] = strings.Trim(authValue, " ")
	//}
	m["Perms"] = perm
	return m, nil
}
