package controllers

import (
	"github.com/astaxie/beego"
	"box-gm/models"
	"box-gm/utils"
	// "log"
	"time"
	)

type AccountLoginController struct {
	beego.Controller
}

type LoginInfo struct {
	Username string `form:"username"`
	Passward string `form:"pwd"`
}


func (c *AccountLoginController) Get() {
	c.SetSession("user", nil)
	c.Data["title"] = beego.AppConfig.String("apptitle")

	// if beego.AppConfig.String("run_test") == "true" {
	// 	c.Data["lu"] = "admin"
	// 	c.Data["lp"] = "123456"
	// }

	c.TplName = "accountlogin.tpl"
}

func (c *AccountLoginController) Post() {
	username := c.GetString("username")
	password := c.GetString("password")

	if username == "" || password == "" {
		c.Data["json"] = &map[string]interface{}{"status": false, "info": "帐号密码不能为空"}
		c.ServeJSON()
		return
	}
	user := models.GetUserByUsername(username)
	// log.Printf("AccountLoginController post user[%v] password[%s]", user, utils.Strtomd5(password))
	if user == nil || user.Password != utils.Strtomd5(password) {
		c.Data["json"] = &map[string]interface{}{"status": false, "info": "密码错误"}
		c.ServeJSON()
		return
	}

	c.SetSession("user", &LoginInfo{username, password})

	user.LastLoginTs = time.Now().Unix()
	models.UpdateUser(user)

	//c.Data["json"] = &map[string]interface{}{"status": true, "info": "登陆成功"}
	//c.ServeJSON()

	c.Ctx.Redirect(302, "/index")
}
