package controllers

import (
	"ai_developer_admin/libs/redis"
	"ai_developer_admin/libs/utils"
	"ai_developer_admin/models"
	"errors"
	beego "github.com/beego/beego/v2/server/web"
	"strconv"
	"time"
)

type MainController struct {
	beego.Controller
}

func (server *MainController) Get() {
	server.Data["Website"] = "beego.me"
	server.Data["Email"] = "astaxie@gmail.com"
	server.TplName = "index.tpl"
}

func (server *MainController) respond(code int, message string, data ...interface{}) {
	status := 200
	if code == 401 {
		status = code
	}
	server.Ctx.Output.SetStatus(status)
	var d interface{}
	if len(data) > 0 {
		d = data[0]
	}
	//reData := struct {
	//	Code int         `json:"code"`
	//	Data interface{} `json:"data,omitempty"`
	//}{
	//	Code: code,
	//	Data: d,
	//}
	server.Data["json"] = struct {
		Code    int         `json:"code"`
		Message string      `json:"message"`
		Data    interface{} `json:"data,omitempty"`
	}{
		Code:    code,
		Message: message,
		Data:    d,
	}
	server.ServeJSON()
}

func (server *MainController) Check() (*models.JwtPayload, error) {
	token := server.Ctx.Input.Header("Authorization")
	if token == "" {
		return nil, errors.New("error: 登陆失效")
	}
	// token := "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MSwianNvbiI6ImdhbmdhbiIsImV4cCI6MTU3ODU1NDMyOCwiaWF0IjoxNTc4NTUzNzI4LCJpc3MiOiJnYW5nYW4ifQ.jOlMlfLMFBJvyrJTLagrwQx2931LzM7Z0EVMFZ75xYI"
	info, err := utils.ValidateToken(token)
	if err != nil {
		return nil, err
		// this.respond(401, "登陆失效")
	}
	key := "token:user-" + strconv.Itoa(info.UserID)
	session, err := redis.GetDataToString(key)
	if err != nil {
		redis.DeleteKey(key)
		return nil, errors.New("error: 登陆失效")
	}
	//session := c.GetSession(key)
	if session == "" {
		return nil, errors.New("error: 登陆失效")
	}
	if !(token == session) {
		//c.DelSession(info.UserID)
		redis.DeleteKey(key)
		return nil, errors.New("error: 登陆失效")
	}
	if info.ExpiresAt <= time.Now().Unix() {
		//c.DelSession(info.UserID)
		redis.DeleteKey(key)
		return nil, errors.New("error: 登陆已过期")
	}

	return info, err
}

func (server *MainController) StoreToken(name interface{}, value interface{}) error {
	return server.SetSession("username", "liuxuzhong")
}
