package controllers

import (
	"crypto/md5"
	"encoding/json"
	"errors"
	"fmt"
	"github.com/shopspring/decimal"
	"hongze/hongze_open_api/models/custom"
	"hongze/hongze_open_api/models/tables/open_api_user"
	"hongze/hongze_open_api/utils"
	"math"
	"reflect"
	"sort"
	"strconv"
	"strings"
	"time"
)

// BaseAuth 需要授权token的基类
type BaseAuth struct {
	BaseCommon
	AdminWx *custom.AdminWx `description:"管理员信息"`
	Token   string          `description:"用户token"`

	StartSize int `description:"开始数量"`
	StartPage int `description:"开始页码"`
	PageSize  int `description:"每页数量"`
}

func (c *BaseAuth) Prepare() {
	//var requestBody string
	signData := make(map[string]string)
	method := c.Ctx.Input.Method()

	var pageSize, currentIndex int
	switch method {
	case "GET":
		//requestBody = c.Ctx.Request.RequestURI
		params := c.Ctx.Request.URL.Query()
		signData = convertParam(params)
		pageSize, _ = c.GetInt("_page_size")
		currentIndex, _ = c.GetInt("_page")
	case "POST":
		//requestBody, _ = url.QueryUnescape(string(c.Ctx.Input.RequestBody))

		//请求类型
		contentType := c.Ctx.Request.Header.Get("content-type")
		//fmt.Println("contentType:", contentType)
		//fmt.Println("c.Ctx.Input.RequestBody:", string(c.Ctx.Input.RequestBody))

		switch contentType {
		case "multipart/form-data":
			//文件最大5M
			err := c.Ctx.Request.ParseMultipartForm(-int64(5 << 20))
			if err != nil {
				c.FailWithMessage(fmt.Sprintf("获取参数失败，%v", err))
				//response.FailWithMessage(fmt.Sprintf("获取参数失败，%v", err), c)
				//c.Abort()
				return
			}
			params := c.Ctx.Request.Form
			signData = convertParam(params)
		case "application/x-www-form-urlencoded":
			err := c.Ctx.Request.ParseForm()
			if err != nil {
				c.FailWithMessage(fmt.Sprintf("获取参数失败，%v", err))
				return
			}
			params := c.Ctx.Request.Form
			signData = convertParam(params)
		case "application/json":
			//var v interface{}
			params := make(map[string]interface{})
			err := json.Unmarshal(c.Ctx.Input.RequestBody, &params)
			if err != nil {
				// handle error
				//fmt.Println("err json:", err)
				c.FailWithMessage(fmt.Sprintf("获取参数失败，%v", err))
				return
			}
			//fmt.Println("params:", params)

			signData = convertParamInterface(params)
			//tmpV := v.(map[string]string)
			//fmt.Println("tmpV:", tmpV)
			//fmt.Sprintln("list type is v%", tmpV["list"])
		default: //正常应该是其他方式获取解析的，暂时这么处理吧
			err := c.Ctx.Request.ParseForm()
			if err != nil {
				c.FailWithMessage(fmt.Sprintf("获取参数失败，%v", err))
				return
			}
			params := c.Ctx.Request.Form
			signData = convertParam(params)
		}
	}
	//fmt.Println("signData:", signData)

	//页码数
	var startSize int
	if pageSize <= 0 {
		pageSize = utils.PageSize20
	}
	//如果超过最大分页数，那么就是按照最大分页数返回
	if pageSize > utils.PageMaxSize {
		pageSize = utils.PageMaxSize
	}
	if currentIndex <= 0 {
		currentIndex = 1
	}
	startSize = utils.StartIndex(currentIndex, pageSize)
	c.StartSize = startSize
	c.PageSize = pageSize
	c.StartPage = currentIndex

	ip := c.Ctx.Input.IP()

	//获取签名秘钥
	//key := global.GVA_CONFIG.SignKey.Agent
	////签名校验
	err := checkSign(signData, ip)
	if err != nil {
		c.SignError(fmt.Sprintf("签名校验失败，%v", err))
		return
	}
	uri := c.Ctx.Input.URI()
	utils.FileLog.Info(fmt.Sprintf("URI:%s", uri))
}

//将请求传入的数据格式转换成签名需要的格式
func convertParam(params map[string][]string) (signData map[string]string) {
	signData = make(map[string]string)
	for key := range params {
		signData[key] = params[key][0]
	}
	return signData
}

//将请求传入的数据格式转换成签名需要的格式（目前只能处理简单的类型，数组、对象暂不支持）
func convertParamInterface(params map[string]interface{}) (signData map[string]string) {
	signData = make(map[string]string)
	for key := range params {
		val := ``
		//fmt.Println("key", key, ";val:", params[key], ";type:", reflect.TypeOf(params[key]))
		//signData[key] = params[key][0]
		tmpVal := params[key]
		switch reflect.TypeOf(tmpVal).Kind() {
		case reflect.String:
			val = fmt.Sprint(tmpVal)
		case reflect.Int, reflect.Int16, reflect.Int64, reflect.Int32, reflect.Int8:
			val = fmt.Sprint(tmpVal)
		case reflect.Uint, reflect.Uint32, reflect.Uint16, reflect.Uint8, reflect.Uint64:
			val = fmt.Sprint(tmpVal)
		case reflect.Bool:
			val = fmt.Sprint(tmpVal)
		case reflect.Float64:
			decimalNum := decimal.NewFromFloat(tmpVal.(float64))
			val = decimalNum.String()
			//val = strconv.FormatFloat(tmpVal.(float64), 'E', -1, 64) //float64
		case reflect.Float32:
			decimalNum := decimal.NewFromFloat32(tmpVal.(float32))
			val = decimalNum.String()
		}
		signData[key] = val
	}
	return signData
}

//请求参数签名校验
func checkSign(postData map[string]string, ip string) (err error) {
	isSandbox := postData["is_sandbox"]
	//如果是测试环境，且是沙箱环境的话，那么绕过测试
	if utils.RunMode == "debug" && isSandbox != "" {
		return
	}

	appid := postData["appid"]
	if appid == "" {
		err = errors.New("参数异常，缺少appid")
		return
	}
	openApiUserInfo, tmpErr := open_api_user.GetByAppid(appid)
	if tmpErr != nil {
		if tmpErr.Error() == utils.ErrNoRow() {
			err = errors.New("appid异常，请联系管理员")
		} else {
			err = errors.New("系统异常，请联系管理员")
		}
		return
	}

	if openApiUserInfo == nil {
		err = errors.New("系统异常，请联系管理员")
		return
	}
	//如果有ip限制，那么就添加ip
	if openApiUserInfo.Ip != "" {
		if !strings.Contains(openApiUserInfo.Ip, ip) {
			err = errors.New(fmt.Sprintf("无权限访问该接口,ip:%v，请联系管理员", ip))
			return
		}
	}

	//接口提交的签名字符串
	ownSign := postData["sign"]
	if ownSign == "" {
		err = errors.New("参数异常，缺少签名字符串")
		return
	}
	if postData["nonce_str"] == "" {
		err = errors.New("参数异常，缺少随机字符串")
		return
	}
	if postData["timestamp"] == "" {
		err = errors.New("参数异常，缺少时间戳")
		return
	} else {
		timeUnix := time.Now().Unix() //当前格林威治时间，int64类型
		//将接口传入的时间做转换
		timestamp, timeErr := strconv.ParseInt(postData["timestamp"], 10, 64)
		if timeErr != nil {
			err = errors.New("参数异常，时间戳格式异常")
			return
		}
		if math.Abs(float64(timeUnix-timestamp)) > 300 {
			err = errors.New("当前时间异常，请调整设备时间与北京时间一致")
			return
		}
	}

	//先取出除sign外的所有的提交的参数key
	var keys []string
	for k := range postData {
		if k != "sign" {
			keys = append(keys, k)
		}
	}

	//1,根据参数名称的ASCII码表的顺序排序
	sort.Strings(keys)

	//2 根据排序后的参数名称，取出对应的值，并拼接字符串
	var signStr string
	for _, v := range keys {
		signStr += v + "=" + postData[v] + "&"
	}
	//3,全转小写(md5(拼装的字符串后+分配给你的app_secret))
	//sign := strings.ToLower(fmt.Sprintf("%x", md5.Sum([]byte(strings.Trim(signStr, "&")+key))))

	//md5.Sum([]byte(signStr+"key="+key))  这是md5加密出来后的每个字符的ascall码，需要再转换成对应的字符
	//3,全转大写(md5(拼装的字符串后+分配给你的app_secret))
	sign := strings.ToUpper(fmt.Sprintf("%x", md5.Sum([]byte(signStr+"secret="+openApiUserInfo.Secret))))
	if sign != ownSign {
		utils.ApiLog.Println(fmt.Sprintf("签名校验异常，签名字符串：%v；服务端签名值：%v", signStr, sign))
		return errors.New("签名校验异常，请核实签名")
	}
	return nil
}
