package controllers

import (
	"fmt"
	"time"
	"github.com/astaxie/beego"

	"box-gm/models"
	"box-gm/utils"
)

type UserController struct {
	beego.Controller
}

func TimeToStr(t int64) string {
	return time.Unix(t, 0).Format("2006-01-02 15:04:05")
}

func StrToTime(str string) int64 {
	loc, _ := time.LoadLocation("Local")
	theTime, err := time.ParseInLocation("2006-01-02 15:04:05", str, loc)
	if err == nil {
		return theTime.Unix()
	} else {
		return 0
	}
}

func (c *UserController) Get() {
	userinfo := c.GetSession("user")
	if userinfo == nil {
		c.Ctx.Redirect(302, "/accountlogin")
		return
	}

	c.Data["username"] = userinfo.(*LoginInfo).Username
	c.Data["token"] = models.GetToken()

	userPermission := models.GetPermission(userinfo.(*LoginInfo).Username)
	if (userPermission & (1 << uint(models.ModelUser))) == 0 {
		c.Ctx.Redirect(302, "/index")
		return
	}

	users, _ := models.GetUserlist()
	permissions, _ := models.GetRolelist()

	c.Data["users"] = users
	c.Data["permissions"] = permissions
	c.Data["token"] = models.GetToken()
	c.TplName = "user.tpl"
}

func (c *UserController) Post() {
	if !models.CheckToken(c.GetString("token")) {
		c.Data["json"] = &map[string]interface{}{"status": false, "info": "操作失败，请重新刷新界面"}
		c.ServeJSON()
		return
	}

	userinfo := c.GetSession("user")
	if userinfo == nil {
		c.Ctx.Redirect(302, "/accountlogin")
		return
	}

	if !models.CheckPermission(userinfo.(*LoginInfo).Username, models.ModelUser) {
		c.Data["json"] = &map[string]interface{}{"status": false, "info": "没有操作权限"}
		c.ServeJSON()
		return
	}

	username := c.GetString("username")
	user := models.GetUserByUsername(username)
	if user != nil {
		c.Data["json"] = &map[string]interface{}{"status": false, "info": "用户已存在"}
		c.ServeJSON()
		return
	}

	u := new(models.User)
	u.Username = c.GetString("username")
	permission, _ := c.GetInt64("permission")
	u.Role = permission
	u.Password = utils.Strtomd5(c.GetString("password"))
	u.CreateTs = time.Now().Unix()
	u.LastLoginTs = time.Now().Unix()

	_, err := models.AddUser(u)
	if err != nil {
		c.Data["json"] = &map[string]interface{}{"status": false, "info": err}
		c.ServeJSON()
		return
	}

	c.Data["json"] = &map[string]interface{}{"status": true, "info": "创建用户成功"}
	c.ServeJSON()

	go models.SaveLog(username, "创建用户", &map[string]interface{}{"username": u.Username, "permission": permission})
}

func (c *UserController) Put() {
	if !models.CheckToken(c.GetString("token")) {
		c.Data["json"] = &map[string]interface{}{"status": false, "info": "操作失败，请重新刷新界面"}
		c.ServeJSON()
		return
	}

	userinfo := c.GetSession("user")
	if userinfo == nil {
		c.Ctx.Redirect(302, "/accountlogin")
		return
	}

	if !models.CheckPermission(userinfo.(*LoginInfo).Username, models.ModelUser) {
		c.Data["json"] = &map[string]interface{}{"status": false, "info": "没有操作权限"}
		c.ServeJSON()
		return
	}

	id, _ := c.GetInt64("id")
	user := models.GetUserById(id)
	if user == nil {
		c.Data["json"] = &map[string]interface{}{"status": false, "info": "用户不存在"}
		c.ServeJSON()
		return
	}
	username := c.GetString("username")
	nUser := models.GetUserByUsername(username)
	if nUser != nil && nUser.Id != id {
		c.Data["json"] = &map[string]interface{}{"status": false, "info": fmt.Sprintf("用户[%s]已存在", username)}
		c.ServeJSON()
		return
	}
	password := c.GetString("password")
	if password != user.Password {
		password = utils.Strtomd5(password)
	}

	u := new(models.User)
	u.Id = user.Id
	u.Username = c.GetString("username")
	permission, _ := c.GetInt64("permission")
	u.Role = permission
	u.Password = password

	_, err := models.UpdateUser(u)
	if err != nil {
		c.Data["json"] = &map[string]interface{}{"status": false, "info": err}
		c.ServeJSON()
		return
	}

	c.Data["json"] = &map[string]interface{}{"status": true, "info": "更新用户成功"}
	c.ServeJSON()

	go models.SaveLog(userinfo.(*LoginInfo).Username, "修改用户", &map[string]interface{}{"username": u.Username, "permission": permission})
}

func (c *UserController) Delete() {
	if !models.CheckToken(c.GetString("token")) {
		c.Data["json"] = &map[string]interface{}{"status": false, "info": "操作失败，请重新刷新界面"}
		c.ServeJSON()
		return
	}

	userinfo := c.GetSession("user")
	if userinfo == nil {
		c.Ctx.Redirect(302, "/accountlogin")
		return
	}

	if !models.CheckPermission(userinfo.(*LoginInfo).Username, models.ModelUser) {
		c.Data["json"] = &map[string]interface{}{"status": false, "info": "没有操作权限"}
		c.ServeJSON()
		return
	}

	
	id, _ := c.GetInt64("id")
	user := models.GetUserById(id)
	if user == nil {
		c.Data["json"] = &map[string]interface{}{"status": false, "info": fmt.Sprintf("用户[%d]不存在", id)}
		c.ServeJSON()
		return
	}
	models.DelUserById(id)

	c.Data["json"] = &map[string]interface{}{"status": true, "info": "删除用户成功"}
	c.ServeJSON()

	go models.SaveLog(userinfo.(*LoginInfo).Username, "删除用户", &map[string]interface{}{"usernames": user.Username})
}
