package controllers

import (
	"encoding/base64"
	"fmt"
	"gdsm/models/ec"
	"gdsm/models/userMgr"
	"github.com/astaxie/beego"
	"strings"
	"wb/cc"
	"wb/cs"
	"wb/ctrl"
	"wb/om"
	"wb/st"
)

type LoginController struct {
	ctrl.LoginController
}

func (this *LoginController) Get() {
	_, ok := this.GetSession(cc.SessionUser).(userMgr.User)
	if this.Ctx.Input.URL() == "/" && ok {
		this.Redirect("/index", 302)
		return
	}
	beego.Info("LoginController:", this.Ctx.Input.URL())
	redirectUrl := "/index"
	redirectUrlB64 := this.GetString("redirect")
	if redirectUrlB64 != "" {
		redirectUrlDec, err := base64.URLEncoding.DecodeString(redirectUrlB64)
		if err == nil {
			redirectUrl = string(redirectUrlDec)
		}
	}
	this.TplName = "login/login.html"
	this.Data["redirectUrl"] = redirectUrl
}
func (this *LoginController) Post() {
	loginRet := cs.JsonResult{}
	username := strings.TrimSpace(this.GetString("login_username"))
	password := strings.TrimSpace(this.GetString("login_password"))
	beego.Info("LoginController.Post user", username, " login in from:", this.Ctx.Request.Host)
	if username == "" || password == "" {
		loginRet.Result = "请输入用户名和密码！"
	}
	params := om.Params{
		"username": username,
		"password": password,
	}
	if code, u := userMgr.GetValidUser(params); code == st.Success {
		this.SetSession(ec.SessionDepartment, u.Department)
		this.LoginAs(u)
	} else {
		beego.Error(fmt.Sprintf("[S]User:%s login error code: %s", username, code))
		loginRet.Result = "用户名或密码错误！"
		this.Data["json"] = &loginRet
		this.ServeJSON()
	}
}