package svc

import (
	"applet/app/db"
	"applet/app/e"
	"applet/app/md"
	"applet/app/utils"
	"fmt"
	"github.com/gin-gonic/gin"
	"math/rand"
	"unicode"
)

// 检测获取邀请码
func UserInviteCode(c *gin.Context, user *md.User) string {
	//已经有邀请码了就中断
	if user.Profile.InviteCode != "" {
		return user.Profile.InviteCode
	}
	var code string
	//读取后台配置判断是数字还是 数字+字母
	inviteData := db.SysCfgFind(c, "app_invite_length", "app_invite_type")
	l := utils.StrToInt(inviteData["app_invite_length"])
	types := utils.StrToInt(inviteData["app_invite_type"])
	////匹配最新的用户的邀请码长度
	//newUser, _ := db.UserProfileOrderByNew(db.DBs[c.GetString("mid")])
	//if newUser.InviteCode != "" {
	//	l = len(newUser.InviteCode)
	//}
	//读取code
	code = returnCode(c, l, types, 0)
	//查询用户信息
	userProfile, err := db.UserProfileFindByID(db.DBs[c.GetString("mid")], user.Info.Uid)
	if err != nil {
		e.OutErr(c, e.ERR_DB_ORM, err)
		return ""
	}
	//写入code
	userProfile.InviteCode = code
	fmt.Println(userProfile)
	db.UserProfileUpdate(db.DBs[c.GetString("mid")], user.Info.Uid, userProfile)
	return code
}
func returnCode(c *gin.Context, l, types, num int) string {
	if num > 5 {
		return ""
	}
	//循环3次判断是否存在该邀请码
	var code string
	var (
		codes []string
	)
	for i := 0; i < 3; i++ {
		oneCode := GetRandomString(l, types)
		codes = append(codes, oneCode)
	}

	//判断是不是存在邀请码了
	tmp, _ := db.UserProfileFindByInviteCodes(db.DBs[c.GetString("mid")], codes...)
	//判断自定义是不是存在邀请码了
	customTmp, _ := db.UserProfileFindByCustomInviteCodes(db.DBs[c.GetString("mid")], codes...)
	//循环生成的邀请码 判断tmp里有没有这个邀请码 如果邀请码没有就赋值 再判断是否存在 存在就清空
	for _, v := range codes {
		if code != "" { //如果存在并且数据库没有就跳过
			continue
		}
		code = v
		for _, v1 := range *tmp {
			//如果存在就清空
			if v1.InviteCode == v {
				code = ""
			}
		}
		for _, v1 := range *customTmp {
			//如果存在就清空
			if v1.CustomInviteCode == v {
				code = ""
			}
		}
	}
	//如果都没有就继续加一位继续查
	if code == "" {
		return returnCode(c, l+1, types, num+1)
	}
	return code
}

// 随机生成指定位数的大写字母和数字的组合
func GetRandomString(l, isLetter int) string {
	str := "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
	if isLetter != 1 {
		str = "0123456789"
	}
	strs := []rune(str)
	result := make([]rune, l)
	for i := range result {
		result[i] = strs[rand.Intn(len(strs))]
	}
	fmt.Println(result)
	if IsLetter(string(result)) && isLetter == 1 {
		return GetRandomString(l, isLetter)
	}
	return string(result)
}
func IsLetter(s string) bool {
	for _, r := range s {
		if !unicode.IsLetter(r) {
			return false
		}
	}
	return true
}
