package app

import (
	. "../../../hotime"
	. "../../../hotime/common"
	"time"
)

var userCtr = Ctr{
	"token": func(this *Context) {
		this.Display(0, this.SessionId)
	},
	"test": func(this *Context) {
		this.Session("id", 1)
	},
	//自带的登录
	"login": func(this *Context) {

		phone := RSA_Decrypt(this.Req.FormValue("phone"))
		idcard := RSA_Decrypt(this.Req.FormValue("idcard"))
		name := RSA_Decrypt(this.Req.FormValue("name"))

		if len(phone) != 11 ||
			len(idcard) != 18 ||
			len(name) < 1 {
			this.Display(3, "数据校验不通过")
		}

		user := this.Db.Get("user", "*", Map{"phone": phone})

		if user == nil {
			user = Map{"phone": phone, "idcard": idcard, "name": name, "create_time": time.Now().Unix(), "modify_time": time.Now().Unix()}
			user["id"] = this.Db.Insert("user", user)

		} else {
			user["phone"] = phone
			user["idcard"] = idcard
			user["name"] = name
			user["modify_time"] = time.Now().Unix()
			re := this.Db.Update("user", user, Map{"id": user.GetCeilInt64("id")})
			if re == 0 {
				this.Display(4, "系统错误")
				return
			}
		}

		if user.GetCeilInt64("id") == 0 {
			this.Display(5, "登录失败")
			return
		}
		this.Session("id", user.GetCeilInt("id"))
		this.Display(0, "登录成功")

	},
	"add": func(this *Context) {
		if this.Req.FormValue("code") != this.Session("code").ToStr() ||
			this.Req.FormValue("phone") != this.Session("phone").ToStr() {
			this.Display(3, "短信验证不通过")
			return
		}

		phone := this.Req.FormValue("phone")
		idcard := this.Req.FormValue("idcard")
		name := this.Req.FormValue("name")

		user := this.Db.Get("user", "*", Map{"phone": phone})

		if user == nil {
			user = Map{"phone": phone, "idcard": idcard, "name": name, "create_time": time.Now().Unix(), "modify_time": time.Now().Unix()}
			user["id"] = this.Db.Insert("user", user)

		} else {
			user["phone"] = phone
			user["idcard"] = idcard
			user["name"] = name
			user["modify_time"] = time.Now().Unix()
			re := this.Db.Update("user", user, Map{"id": user.GetCeilInt64("id")})
			if re == 0 {
				this.Display(4, "系统错误")
				return
			}
		}

		if user.GetCeilInt64("id") == 0 {
			this.Display(5, "登录失败")
			return
		}

		this.Session("id", user.GetCeilInt("id"))
		this.Session("code", nil)
		this.Display(0, "登录成功")

	},
}
