package controllers

import (
	"wechat-conf/models/model"
	"wechat-conf/service/user"
	"wechat-conf/utils"

	"github.com/astaxie/beego"
)

// UserController 用户
type UserController struct {
	serv *user.UserServ
	BaseController
}

// Constructor 初始化 Controller
// @Title Constructor
// @Description 初始化 Controller, 系统自动调用
func (c *UserController) Constructor() {
	c.serv = user.NewUserServ(c.Context)
}

// Login 用户登录
func (c *UserController) Login() {

	var user *model.SysUser
	var err error
	// 如果有 session 就算已经登录
	userId := c.GetSession(SESSION_USER)
	if userId != nil {
		c.ResponseError(utils.LogError("用户已经登录!"))
	}
	userName := c.GetString("UserName")
	pwd := c.GetString("UserPass")
	if userName == "" || pwd == "" {
		c.ResponseError(utils.LogError("用户名或密码不能为空!"))
	}
	user, err = c.serv.ValidUserNameLogin(userName, pwd)
	if err != nil {
		beego.Error("用户登录失败, ", err)
		c.ResponseError(utils.LogError("用户名或密码错误"))
	}

	// 密码不能送到前端
	user.Pwd = ""

	c.SetSession(SESSION_USER, user.UserId)
	c.ResponseJSON(user)
}

// SignOut 登出
// @Title 登出
// @Description 登出
// @Success 200 string ok-string
// @Failure >300 error message
func (c *UserController) SignOut() {
	c.Context.Set("user", nil)
	c.DestroySession()

	c.ResponseJSON("ok")
}

// UpdatePassword 更新用户密码
// @Title 更新用户密码
// @Description 更新用户密码
// @Param   oriPasswd     form    string  true        "旧密码"
// @Param   newPasswd     form    string  true        "新密码"
// @Success 200 string ok-string
// @Failure >300 error message
func (c *UserController) UpdatePassword() {
	oriPasswd := c.GetString("oriPasswd")
	newPasswd := c.GetString("newPasswd")
	user := c.Context.Get("user").(*model.SysUser)

	if !c.serv.ValidatePassword(user, oriPasswd) {
		c.ResponseError(utils.LogError("原始密码不正确"))
	}

	if err := c.serv.UpdatePassword(user.UserId, newPasswd); err != nil {
		c.ResponseError(err)
	}

	c.ResponseJSON("ok")
}

// GetUser 获取用户信息
func (c *UserController) GetUser() {
	user := c.Context.Get("user").(*model.SysUser)
	c.ResponseJSON(user)
}