package front

import (
	qu "qfw/util"
	"strconv"
	"time"

	. "../util"

	"github.com/go-xweb/xweb"
	"gopkg.in/mgo.v2/bson"
)

var UserMenu map[string][]map[string]interface{} //存储菜单
func init() {
	UserMenu = make(map[string][]map[string]interface{})
}

type Front struct {
	*xweb.Action
	login     xweb.Mapper `xweb:"/"`                //登录页面
	index     xweb.Mapper `xweb:"/front/index"`     //index页面
	logout    xweb.Mapper `xweb:"/front/logout"`    //注销
	updatePwd xweb.Mapper `xweb:"/front/updatepwd"` //更新密码
	//user
	user     xweb.Mapper `xweb:"/front/user"`      //查所有用户
	userDel  xweb.Mapper `xweb:"/front/user/del"`  //删除用户
	userSave xweb.Mapper `xweb:"/front/user/save"` //保存用户
	//menu
	menu           xweb.Mapper `xweb:"/front/menu"`            //查一级菜单
	menuSave       xweb.Mapper `xweb:"/front/menu/save"`       //保存一级菜单
	menuDel        xweb.Mapper `xweb:"/front/menu/del"`        //删除一级菜单
	menuSecond     xweb.Mapper `xweb:"/front/menuSecond"`      //查二级菜单
	menuSecondSave xweb.Mapper `xweb:"/front/menuSecond/save"` //保存二级菜单
	menuSecondDel  xweb.Mapper `xweb:"/front/menuSecond/del"`  //删除二级菜单
	personalMenu   xweb.Mapper `xweb:"/front/personalMenu"`
	//role
	roleManager    xweb.Mapper `xweb:"/front/role"`             //角色权限管理
	roleEdit       xweb.Mapper `xweb:"/front/role/edit/(.*)"`   //角色权限查看
	roleFirst      xweb.Mapper `xweb:"/front/role/first"`       //一级权限的查看
	roleSecond     xweb.Mapper `xweb:"/front/role/second"`      //二级权限的查看
	roleSave       xweb.Mapper `xweb:"/front/role/edit/save"`   //权限编辑保存
	roleDel        xweb.Mapper `xweb:"/front/role/edit/del"`    //权限编辑删除
	roleSecondEdit xweb.Mapper `xweb:"/front/role/second/edit"` //二级权限编辑

	logicManager	xweb.Mapper `xweb:"/front/logic"`			//逻辑管理
	logicPre		xweb.Mapper	`xweb:"/front/logic/pre"`		//预处理逻辑
	logicMatch		xweb.Mapper	`xweb:"/front/logic/match"`		//匹配逻辑
	logicClean		xweb.Mapper	`xweb:"/front/logic/clean"`		//清洗
	logicPreSav		xweb.Mapper	`xweb:"/front/logic/pre/save"`	//预处理逻辑保存

}

func (f *Front) Login() {
	defer qu.Catch()
	if f.Method() == "POST" {
		email := f.GetString("email")
		password := f.GetString("pwd")
		//f.SetSession("password", password)
		passwordEn := qu.SE.EncodeString(password)
		query := bson.M{
			"s_email": email,
			"s_pwd":   passwordEn,
		}
		user, _ := Mgo.FindOne("user", query)
		checked := false
		if user != nil && len(*user) > 0 {
			checked = true
			f.SetSession("user", map[string]interface{}{
				"name":  (*user)["s_name"],
				"role":  (*user)["s_role"],
				"pwd":   password,
				"email": email,
				"id":    qu.BsonIdToSId((*user)["_id"]),
			})
			UserMenu[email] = GetUserMenu(qu.ObjToString((*user)["s_role"]))
		}
		f.ServeJson(map[string]interface{}{
			"checked": checked,
		})
	} else {
		f.Render("login.html")
	}
}

func (f *Front) Index() {
	defer qu.Catch()
	f.Render("index.html")
}

func (f *Front) Logout() {
	f.DelSession("user")
	f.Redirect("/")
}

func (f *Front) UpdatePwd() {
	defer qu.Catch()
	id := f.GetString("id")
	password := f.GetString("pwd")
	set := bson.M{
		"$set": bson.M{
			"s_pwd": qu.SE.EncodeString(password),
		},
	}
	if Mgo.UpdateById("user", id, set) {
		sessionuser := f.GetSession("user").(map[string]interface{})
		sessionuser["pwd"] = password
		f.SetSession("user", sessionuser)
	}

}

func (f *Front) User() {
	defer qu.Catch()
	if f.Method() == "POST" {
		query := bson.M{
			"s_role": bson.M{
				"$ne": "0",
			},
		}
		data, _ := Mgo.Find("user", query, `{"_id":1}`, nil, false, -1, -1)
		for _, d := range *data {
			d["s_pwd"] = qu.SE.DecodeString(qu.ObjToString(d["s_pwd"]))
		}
		f.ServeJson(map[string]interface{}{
			"data": data,
		})
	} else {
		f.Render("com/user.html")
	}
}

func (f *Front) UserDel() {
	defer qu.Catch()
	_id := f.GetString("_id")
	query := bson.M{
		"_id": qu.StringTOBsonId(_id),
	}
	b := Mgo.Del("user", query)
	f.ServeJson(map[string]interface{}{
		"rep": b,
	})
}

func (f *Front) UserSave() {
	_id := f.GetString("_id")
	role := f.GetString("role")
	name := f.GetString("name")
	email := f.GetString("email")
	pwd := f.GetString("pwd")
	set := bson.M{
		"$set": bson.M{
			"s_role":       role,
			"s_name":       name,
			"s_email":      email,
			"s_pwd":        qu.SE.EncodeString(pwd),
			"i_comeintime": time.Now().Unix(),
		},
	}
	query := bson.M{
		"_id": qu.StringTOBsonId(_id),
	}
	if _id == "" {
		query = bson.M{
			"_id": bson.NewObjectId(),
		}
	}

	b := Mgo.Update("user", query, set, true, false)
	//b := Mgo.UpdateById("user", _id, set)
	f.ServeJson(map[string]interface{}{
		"rep": b,
	})
}

func (f *Front) PersonalMenu() {
	user := f.GetSession("user").(map[string]interface{})
	list := UserMenu[qu.ObjToString(user["email"])]
	f.ServeJson(map[string]interface{}{
		"data": list,
	})
}

func GetUserMenu(role string) []map[string]interface{} {
	list := []map[string]interface{}{}
	maps := map[string]interface{}{
		"delete": false,
	}
	if role != "0" {
		maps["role."+role] = true
	}
	data, _ := Mgo.Find("menu_first", maps, nil, nil, false, -1, -1)
	for _, d := range *data {
		_id := d["_id"]
		maps = map[string]interface{}{
			"delete": false,
			"s_pid":  qu.BsonIdToSId(_id),
		}
		if role != "0" {
			maps["role."+role] = true
		}
		secdatas, _ := Mgo.Find("menu_second", 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 {
			d["secondmenu"] = secmenumap
		}
		list = append(list, d)
	}
	return list
}
