package admin

import (
	"fmt"
	"math"
	"net/http"

	c "ciyon/zciyon"
)

func Login_login(w http.ResponseWriter, r *http.Request) bool {
	post := c.NewCiyPost(w, r)
	targettype := post.Getint("targettype", 10)
	user := post.Get("user")
	if user == "" {
		return c.ErrJSON(w, "请填写用户名")
	}
	csql := c.NewCiySQL("zc_admin")
	csql.Where("mobile", user)
	userrow, err := c.CiyDB.Getone(csql)
	if err != nil {
		return c.ErrJSON(w, "遇到读取错误", err)
	}
	if userrow == nil {
		SaveLog(c.CiyDB, "LOGINERR", "用户["+user+"]不存在，在尝试登录")
		return c.ErrJSON(w, "用户不存在", fmt.Errorf("用户[%v]在尝试登录,ip=", user))
	}
	if c.Toint(userrow["trytime"]) > 10 {
		if c.Tostamp()-c.Toint(userrow["logintimes"]) < 600 {
			SaveLog(c.CiyDB, "LOGINERR", "用户["+user+"]登录连续失败")
			return c.ErrJSON(w, "连续输入密码错误，10分钟后再来登录.", fmt.Errorf("用户[%v]在撞库,ip=", user))
		}
	}
	if c.Toint(userrow["stpstatus"]) != 10 {
		SaveLog(c.CiyDB, "LOGINERR", "用户["+user+"]被禁用，在尝试登录")
		return c.ErrJSON(w, "您的账户已经被禁用.")
	}
	authtime := post.Getint("auth")
	if math.Abs(c.Tofloat(authtime/1000-c.Tostamp())) > 300 {
		return c.ErrJSON(w, "您的本地时间与服务器时间相差超过5分钟，请调整本机时间.<br/>服务器时间: "+c.Todate(-1, "Y-m-d H:i:s")+"<br/>您本机时间: "+c.Todate(authtime/1000, "Y-m-d H:i:s"))
	}
	if post.Get("pass") != c.Sha256(c.Tostr(userrow["password"])+fmt.Sprintf("%d", authtime)) {
		updata := map[string]any{}
		updata["trytime"] = []string{"trytime+1"}
		updata["logintimes"] = c.Tostamp()
		csql = c.NewCiySQL("zc_admin")
		csql.Where("id", userrow["id"])
		c.CiyDB.Update(csql, updata)
		SaveLog(c.CiyDB, "LOGINERR", "用户["+user+"]登录密码错误 "+Gdefpass+" ["+c.Sha256(Gdefpass+Gtokensalt)+"]")
		return c.ErrJSON(w, "用户["+user+"]登录密码错误")
	}
	syncdict, err := getsync(userrow)
	if err != nil {
		return c.ErrJSON(w, "遇到同步错误", err)
	}

	userid := c.Toint(userrow["id"])
	c.CiyDB.Execute("delete from zc_online where exptimes<? and user=?", c.Tostamp(), userid)
	sid := c.Randstr(10)
	exptimes := c.Tostamp() + Gtokenswapsec
	updata := map[string]any{}
	updata["user"] = userid
	updata["targettype"] = targettype
	updata["sid"] = sid
	updata["addtimes"] = c.Tostamp()
	updata["exptimes"] = exptimes
	updata["ip"] = post.GetIP()
	csql = c.NewCiySQL("zc_online")
	oid, err := c.CiyDB.Insert(csql, updata)
	if err != nil {
		return c.ErrJSON(w, "online数据库更新失败", err)
	}
	updata = map[string]any{}
	updata["logintimes"] = c.Tostamp()
	updata["trytime"] = 0
	csql = c.NewCiySQL("zc_admin")
	csql.Where("id", userid)
	_, err = c.CiyDB.Update(csql, updata)
	if err != nil {
		return c.ErrJSON(w, "user数据库更新失败", err)
	}
	auth := map[string]any{}
	auth["id"] = userid
	auth["_o"] = oid
	auth["_s"] = sid
	authstr := c.JSON_Str(auth)

	newauth := c.Encrypt(authstr, "E", Gtokensalt)
	syncdict["_ciyauth"] = newauth
	//post.W.Header().Set(Gtokenfield, newauth)
	SaveLog(c.CiyDB, "LOGIN", "登录成功")
	return c.SuccJSON(w, r, syncdict)
}

func Login_restorage(w http.ResponseWriter, r *http.Request) bool {
	post := c.NewCiyPost(w, r)
	rsuser, _ := Verifyfast(r, c.CiyDB, post)
	csql := c.NewCiySQL("zc_admin")
	csql.Where("id", rsuser["id"])
	userrow, err := c.CiyDB.Getone(csql)
	if err != nil {
		return c.ErrJSON(w, "遇到读取错误", err)
	}
	syncdict, err := getsync(userrow)
	if err != nil {
		return c.ErrJSON(w, "遇到同步错误", err)
	}
	c.CiyDB.Execute("update zc_online set usrchg=0 where id=?", rsuser["_o"])
	return c.SuccJSON(w, r, syncdict)
}
func getsync(userrow map[string]any) (map[string]any, error) {
	var err error
	storage := map[string]any{}
	csql := c.NewCiySQL("zc_admin")
	csql.Column("id,name")
	storage["adminuser"], _, err = c.CiyDB.Get(csql)
	if err != nil {
		return nil, err
	}
	csql = c.NewCiySQL("zc_cata")
	csql.Order("csort")
	storage["cata"], _, err = c.CiyDB.Get(csql)
	if err != nil {
		return nil, err
	}
	departid := c.Toint(userrow["departid"])
	var departname string
	if departid > 0 {
		csql := c.NewCiySQL("zc_depart")
		csql.Where("id", departid)
		csql.Column("name")
		departname = c.Tostr(c.CiyDB.Get1(csql))
	}
	me := map[string]any{}
	me["id"] = userrow["id"]
	me["mobile"] = userrow["mobile"]
	me["icon"] = userrow["icon"]
	me["name"] = userrow["name"]
	me["sex"] = userrow["sex"]
	me["depart"] = departname
	me["addtimes"] = userrow["addtimes"]
	power := userrow["power"]
	me["power"] = power
	me["needpass"] = (userrow["password"] == c.Sha256(Gdefpass+Gtokensalt))
	syncdict := map[string]any{}
	syncdict["storage"] = storage
	syncdict["me"] = me
	return syncdict, nil
}

func Login_logout(w http.ResponseWriter, r *http.Request) bool {
	post := c.NewCiyPost(w, r)
	rsuser, err := Verifyuser(r, c.CiyDB, post)
	if err == nil {
		csql := c.NewCiySQL("zc_online")
		csql.Where("id", rsuser["_o"])
		c.CiyDB.Delete(csql)
	}
	SaveLog(c.CiyDB, "LOGIN", "退出登录")
	return c.SuccJSON(w, r)
}
