package router

import (
	"context"
	"demo/configs"
	"demo/data/dao"
	"demo/data/domain"
	"demo/share"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/mojocn/base64Captcha"
	"github.com/spf13/cast"
	"net/http"
	"strings"
	"time"
)

func BackRouter(engine *gin.RouterGroup) {
	user := engine.Group("/back")
	{
		user.POST("/login", login)
		user.GET("/code", VerificationCode)
		user.GET("/state", GetBackUserState)
		//获取用户信息

	}
}

var ctx = context.Background()

func login(c *gin.Context) {
	data := share.GetJsonAnyParam(c)
	username, _ := data("username")
	password, _ := data("password")
	code, _ := data("code")
	codeMap := cast.ToStringMapString(code)
	//判断验证码是否正确
	redisCode := configs.RedisDb.Get(ctx, fmt.Sprint("VerificationBackCode_", codeMap["id"]))
	if redisCode.Val() != codeMap["code"] {
		c.JSON(http.StatusOK, CreateResultError(400, "验证码错误!!!"))
		return
	}
	// 定义正则表达式
	user, err := dao.Logins(cast.ToString(username), cast.ToString(password))

	if err == nil && user.Id != 0 {
		fmt.Println("用户登录成功!!!")
		token, err := share.GenerateToken("back" + cast.ToString(user.Id))
		if err == nil {
			c.Header("auth-sign", token)
			c.JSON(http.StatusOK, CreateResultData(map[string]string{"token": token}))
		} else {
			c.JSON(http.StatusOK, CreateResultError(400, "生成token失败!!!"))
		}
	} else {
		fmt.Println("用户登录失败!!!")
		c.JSON(http.StatusOK, CreateResultError(401, "用户密码错误!!!"))
	}
}
func isLogin(c *gin.Context) {
	data := share.GetJsonAnyParam(c)
	username, _ := data("username")
	password, _ := data("password")
	code, _ := data("code")
	codeMap := cast.ToStringMapString(code)
	//判断验证码是否正确
	redisCode := configs.RedisDb.Get(ctx, fmt.Sprint("VerificationCode_", codeMap["id"])).String()
	if redisCode != codeMap["value"] {
		c.JSON(http.StatusOK, CreateResultError(400, "验证码错误!!!"))
		return
	}
	// 定义正则表达式
	user, err := dao.Logins(cast.ToString(username), cast.ToString(password))
	fmt.Println("user:", user)
	if err == nil && user.Id != 0 {
		fmt.Println("用户登录成功!!!")
		token, err := share.GenerateToken("back_" + cast.ToString(user.Id))
		if err == nil {
			c.Header("auth-sign", token)
			c.JSON(http.StatusOK, CreateResultData(map[string]string{"token": token}))
		} else {
			c.JSON(http.StatusOK, CreateResultError(400, "生成token失败!!!"))
		}
	} else {
		fmt.Println("用户登录失败!!!")
		c.JSON(http.StatusOK, CreateResultError(401, "用户密码错误!!!"))
	}
}

func VerificationCode(c *gin.Context) {
	// 配置
	driver := base64Captcha.NewDriverDigit(80, 240, 4, 0.5, 80)
	store := base64Captcha.DefaultMemStore
	captcha := base64Captcha.NewCaptcha(driver, store)

	// 生成验证码
	id, b64s, answer, err := captcha.Generate()
	if err != nil {
		c.JSON(500, gin.H{"error": err.Error()})
		return
	}
	err = configs.RedisDb.Set(ctx, "VerificationBackCode_"+id, answer, 0).Err()
	if err != nil {
		fmt.Println(err)
	}
	err = configs.RedisDb.Expire(ctx, "VerificationBackCode_"+id, 60*time.Second).Err()
	if err != nil {
		panic(err)
	}
	// 返回验证码图片
	c.JSON(200, gin.H{
		"message": "获取成功!!!",
		"expires": time.Now().Add(time.Minute * 5).Unix(),
		"code":    200,
		"data":    map[string]string{"id": id, "image": b64s},
	})
}

func GetBackUserState(c *gin.Context) {
	header := c.GetHeader("auth-sign")
	if header == "" {
		c.JSON(200, CreateResultError(406, "用户未登录"))
		return
	}
	claims, err := share.ParseToken(header)
	if err != nil {
		c.JSON(200, CreateResultError(406, "用户未登录"))
		return
	}

	var userInfo = domain.ManageUser{}
	backUserId := claims["iss"].(string)
	fmt.Println(backUserId, "backUserId")
	if strings.Index(backUserId, "back_") == 0 {
		backUserId = strings.Replace(backUserId, "back_", "", 1)
	} else {
		c.JSON(200, CreateResultError(406, "用户未登录"))
	}

	_, err = configs.Engine.Table("manage_user").Where("id = ?", claims["iss"]).Get(&userInfo)
	if err != nil {
		c.JSON(200, CreateResultError(406, "用户未登录"))
		return
	}
	c.JSON(200, CreateResultData(map[string]any{
		"info": userInfo,
	}))
}
