package controllers

import (
	"cc-officialweb/models"
	"cc-officialweb/service"
	"encoding/json"
	beego "github.com/beego/beego/v2/server/web"
	"github.com/go-playground/validator/v10"
)

type LoginController struct {
	beego.Controller
}

// Login 登录接口
func (l *LoginController) Login() {
	var user models.User
	// 获取POST参数
	err := json.Unmarshal(l.Ctx.Input.RequestBody, &user)
	if err != nil {
		l.Data["json"] = &JSON{Code: 103, Msg: "json格式错误"}
		l.ServeJSON()
		return
	}
	// 进行验证和登录检查
	validate := validator.New()
	unva := validate.Var(user.Username, "required")
	pwdva := validate.Var(user.Password, "required")
	if unva != nil || pwdva != nil {
		l.Data["json"] = &JSON{Code: 103, Msg: "用户名密码不能为空"}
		l.ServeJSON()
		return
	} else {
		token := service.Login(user)
		if token != "" {
			l.Data["json"] = &JSON{Code: 200, Msg: "登录成功", Data: token}
			l.ServeJSON()
		} else {
			l.Data["json"] = &JSON{Code: 103, Msg: "用户名密码错误"}
			l.ServeJSON()
			return
		}
	}
}
