package utils

import (
	"encoding/base64"
	"net/http"
	"strconv"
	"strings"
)

// 客户端类型
const (
	ClientAdmin  = "client-admin"
	ClientWechat = "client-wechat"
	ClientMini   = "client-mini"
)

// 一些 UA 列表
const (
	UAWechat      = "micromessenger"
	UAMiniProgram = "miniprogram"
)

// GetClientType 获取客户端类型
// 默认返回是 管理端
func GetClientType(r *http.Request) string {
	ua := strings.ToLower(r.Header.Get("User-Agent"))

	if strings.Index(ua, UAWechat) > -1 {
		if strings.Index(ua, UAMiniProgram) > -1 {
			return ClientMini
		}

		return ClientWechat
	}

	return ClientAdmin
}

// StrSliceIndexOf slice indexof
func StrSliceIndexOf(s []string, t string) int64 {
	if s == nil || len(s) == 0 {
		return -1
	}

	for k, v := range s {
		if v == t {
			return int64(k)
		}
	}

	return -1
}

// GUIID2IntString guid 转 int 字符串
func GUIID2IntString(id string) []string {
	if id == "" {
		return nil
	}

	res := make([]string, 0)
	for _, part := range strings.Split(id, "-") {
		sum := 0
		for _, r := range []rune(part) {
			sum += int(r)
		}

		res = append(res, strconv.Itoa(sum))
	}

	return res
}

// EncodeBase64TrimTail base64 加密, 去除末尾 =
func EncodeBase64TrimTail(src string) string {
	if src == "" {
		return ""
	}

	enStr := base64.StdEncoding.EncodeToString([]byte(src))

	return strings.TrimRight(enStr, "=")
}

// DecodeBase64NoTail base64解密, 位数不够的, 自动补全
func DecodeBase64NoTail(src string) string {
	if src == "" {
		return ""
	}

	pd := 4 - len(src)%4
	if pd > 0 && pd != 4 {
		src += strings.Repeat("=", pd)
	}

	res, err := base64.StdEncoding.DecodeString(src)
	if err != nil {
		LogError("解密 Base64 字串失败: " + err.Error())
		return ""
	}

	return string(res)
}
