package front

import (
	"go.mongodb.org/mongo-driver/bson/primitive"
	"mongodb"
	qu "qfw/util"
	"time"

	. "util"

	"go.mongodb.org/mongo-driver/bson"
)

func (f *Front) Menu() {
	defer qu.Catch()
	if f.Method() == "POST" {
		data, _ := Mgo.Find("menu_first", `{"delete":false}`, `{"_id":1}`, nil, false, -1, -1)
		f.ServeJson(map[string]interface{}{
			"data": data,
		})
	} else {
		f.Render("com/menu_first.html")
	}
}

func (f *Front) MenuSave() {
	defer qu.Catch()
	name := f.GetString("name")
	href := f.GetString("href")
	css := f.GetString("css")
	id := f.GetString("id")
	query := bson.M{
		"_id":    mongodb.StringTOBsonId(id),
		"delete": false,
	}
	if id == "" {
		query = bson.M{
			"_id":    primitive.NewObjectID(),
			"delete": false,
		}
	}
	set := bson.M{
		"$set": bson.M{
			"s_name":       name,
			"s_href":       href,
			"s_css":        css,
			"delete":       false,
			"i_comeintime": time.Now().Unix(),
		},
	}
	b := Mgo.Update("menu_first", query, set, true, false)
	if b {
		f.ServeJson(map[string]interface{}{
			"rep": b,
		})
	}
}

func (f *Front) MenuDel() {
	defer qu.Catch()
	_id := f.GetString("_id")
	query := bson.M{
		"_id": mongodb.StringTOBsonId(_id),
	}
	set := bson.M{
		"$set": bson.M{
			"delete": true,
		},
	}
	b := Mgo.Update("menu_first", query, set, false, false)
	if b { //删除一级菜单下的二级菜单
		Mgo.Update("menu_second", `{"s_pid":"`+_id+`"}`, set, false, true)
	}
	f.ServeJson(map[string]interface{}{
		"rep": b,
	})
}

func (f *Front) MenuSecond() {
	defer qu.Catch()
	id := f.GetString("id")
	if f.Method() == "POST" {
		data, _ := Mgo.Find("menu_second", `{"s_pid":"`+id+`","delete":false}`, `{"_id":1}`, nil, false, -1, -1)
		f.ServeJson(map[string]interface{}{
			"data": data,
		})
	} else {
		f.T["id"] = id
		f.Render("com/menu_second.html", &f.T)
	}
}

func (f *Front) MenuSecondSave() {
	defer qu.Catch()
	name := f.GetString("name")
	href := f.GetString("href")
	css := f.GetString("css")
	id := f.GetString("id")
	pid := f.GetString("pid")
	query := bson.M{
		"_id":    mongodb.StringTOBsonId(id),
		"delete": false,
	}
	if id == "" {
		query = bson.M{
			"_id":    primitive.NewObjectID(),
			"delete": false,
		}
	}
	set := bson.M{
		"$set": bson.M{
			"s_name":       name,
			"s_href":       href,
			"s_css":        css,
			"delete":       false,
			"s_pid":        pid,
			"i_comeintime": time.Now().Unix(),
		},
	}
	b := Mgo.Update("menu_second", query, set, true, false)
	if b {
		f.ServeJson(map[string]interface{}{
			"rep": b,
		})
	}
}

func (f *Front) MenuSecondDel() {
	defer qu.Catch()
	_id := f.GetString("_id")
	query := bson.M{
		"_id": mongodb.StringTOBsonId(_id),
	}
	set := bson.M{
		"$set": bson.M{
			"delete": true,
		},
	}
	b := Mgo.Update("menu_second", query, set, false, false)
	f.ServeJson(map[string]interface{}{
		"rep": b,
	})
}
