package front

import (
	"fmt"
	. "jy/mongodbutil"
	. "jy/router"
	. "jy/util"
	"net/http"
	qu "qfw/util"
	"strconv"

	"github.com/gin-contrib/sessions"
	"github.com/gin-gonic/gin"
)

var UserMenu map[string][]map[string]interface{}

func init() {
	UserMenu = make(map[string][]map[string]interface{})
	front := Router.Group("/")
	{
		front.Static("/front", "./web/templates/front")
		front.Static("/res", "./web/res")
	}
	front.POST("/login", Login)  //登录
	front.GET("/logout", Logout) //注销
}

func Login(c *gin.Context) {
	email := c.PostForm("email")
	pwd := c.PostForm("pwd")
	res, _ := Mgo.FindOne("user", fmt.Sprintf(`{"email":"%s","pwd":"%s"}`, email, Se.EncodeString(pwd)))
	if res != nil && len(*res) > 0 {
		UserMenu[qu.ObjToString((*res)["email"])] = GetUserMenu(qu.ObjToString((*res)["role"]))
		session := sessions.Default(c)
		(*res)["pwd"] = pwd
		(*res)["_id"] = qu.BsonIdToSId((*res)["_id"])
		session.Set("user", res)
		session.Set("username", (*res)["name"])
		session.Set("role", (*res)["role"])
		session.Save()
		c.JSON(200, gin.H{"checked": true})
	} else {
		c.JSON(200, gin.H{"checked": false})
	}
}
func Logout(c *gin.Context) {
	session := sessions.Default(c)
	session.Delete("user")
	c.Redirect(http.StatusMovedPermanently, "/front/login.html")
}

func GetUserMenu(role string) []map[string]interface{} {
	list := []map[string]interface{}{}
	maps := map[string]interface{}{}
	if role == "3" {
		maps = map[string]interface{}{}
	} else {
		maps = map[string]interface{}{
			"role." + role: true,
		}
	}
	data, _ := Mgo.Find("menu", maps, nil, nil, false, -1, -1)
	for _, value := range *data {
		_id := value["_id"]
		if role == "3" {
			maps = map[string]interface{}{
				"menuid": qu.BsonIdToSId(_id),
			}
		} else {
			maps = map[string]interface{}{
				"role." + role: true,
				"menuid":       qu.BsonIdToSId(_id),
			}
		}
		secdatas, _ := Mgo.Find("menusecond", maps, nil, nil, false, -1, -1)
		secmenumap := map[string]interface{}{}
		for index, secdata := range *secdatas {
			secmenumap[strconv.Itoa(index+1)] = secdata
		}
		if len(secmenumap) != 0 {
			value["secondmenu"] = secmenumap
		}
		list = append(list, value)
	}
	return list
}
