// version
package admin

import (
	"encoding/json"
	"fmt"
	"github.com/gin-contrib/sessions"
	"github.com/gin-gonic/gin"
	"gopkg.in/mgo.v2/bson"
	. "jy/mongodbutil"
	"net/http"
	"net/url"
	"qfw/util"
	"strings"
	"sync"
	"time"
)

func init() {
	Admin.GET("/site_management", func(c *gin.Context) {
		vid, _ := c.GetQuery("vid")
		c.HTML(
			http.StatusOK, "site_management.html",
			gin.H{"vid": vid},
		)
	})
	//初始化版本站点列表
	Admin.POST("/site_management/dataForVid", func(c *gin.Context) {
		vid, _ := c.GetQuery("vid")
		if vid == "" {
			data, _ := Mgo.Find("site_management", nil, `{"_id":-1}`, nil, false, -1, -1)
			c.JSON(200, gin.H{"data": data})
		} else {
			data, _ := Mgo.Find("site_management", bson.M{"vid": vid}, `{"_id":-1}`, nil, false, -1, -1)
			c.JSON(200, gin.H{"data": data})
		}
	}) //版本站点列表
	Admin.POST("/site_management/byId", func(c *gin.Context) {
		_id := c.PostForm("_id")
		if !bson.IsObjectIdHex(_id) {
			c.JSON(400, gin.H{"rep": false})
			return
		}
		data, _ := Mgo.FindById("site_management", _id, bson.M{})
		c.JSON(200, gin.H{"rep": true, "data": data})
	})

	//站点信息保存
	Admin.POST("/site_management/save", func(c *gin.Context) {
		_id, _ := c.GetPostForm("_id")
		data := GetPostForm(c)
		if data["site_name"] == nil || data["site_href"] == nil {
			c.JSON(400, gin.H{"rep": false})
			return
		}
		u, _ := url.Parse(data["site_href"].(string))
		if u != nil && u.Scheme == "" {
			data["site_href"] = "http://" + strings.TrimSpace(data["site_href"].(string))
		}
		if scripts, ok := data["site_script"].(string); ok {
			luacodes := strings.Split(scripts, ",")
			data["site_script"] = luacodes
		}
		if data["isuse"] == nil {
			data["isuse"] = "true"
		}
		if data["vid"] != nil && bson.IsObjectIdHex(data["vid"].(string)) {
			if aa, b := Mgo.Find("version", bson.M{"_id": bson.ObjectIdHex(data["vid"].(string))}, nil, bson.M{"version": 1}, true, -1, -1); b {
				data["version"] = (*aa)[0]["version"]
			}
		}
		if _id != "" {
			Mgo.UpdateById("site_management", _id, map[string]interface{}{"$set": data})
			c.JSON(200, gin.H{"rep": true})
		} else {
			Mgo.Save("site_management", data)
			c.JSON(200, gin.H{"rep": true, "vid": data["vid"]})
		}
	})
	//站点信息删除
	Admin.POST("/site_management/delete", func(c *gin.Context) {
		_id, _ := c.GetPostForm("_id")
		if _id == "" || !bson.IsObjectIdHex(_id) {
			c.JSON(400, gin.H{"rep": false})
		} else {
			vstmp,_:=Mgo.FindById("site_management",_id,bson.M{"vid":1})
			Mgo.Del("site_management", bson.M{"_id": bson.ObjectIdHex(_id)})
			vinfotmp,_:=Mgo.FindOne("site_versioninfo",bson.M{"pid": _id,"vid":util.ObjToString((*vstmp)["vid"])})
			if len(*vinfotmp) > 0 {
				go Mgo.Del("site_rule_code", bson.M{"pid": (*vinfotmp)["_id"].(bson.ObjectId).Hex(),"vid":util.ObjToString((*vstmp)["vid"])})
				go Mgo.Del("site_rule_logic", bson.M{"pid": (*vinfotmp)["_id"].(bson.ObjectId).Hex(),"vid":util.ObjToString((*vstmp)["vid"])})
				go Mgo.Del("site_rule_logicback", bson.M{"pid": (*vinfotmp)["_id"].(bson.ObjectId).Hex(),"vid":util.ObjToString((*vstmp)["vid"])})
				go Mgo.Del("site_rule_logicore", bson.M{"pid": (*vinfotmp)["_id"].(bson.ObjectId).Hex(),"vid":util.ObjToString((*vstmp)["vid"])})
				go Mgo.Del("site_rule_logickv", bson.M{"pid": (*vinfotmp)["_id"].(bson.ObjectId).Hex(),"vid":util.ObjToString((*vstmp)["vid"])})
				go Mgo.Del("site_rule_logicpre", bson.M{"pid": (*vinfotmp)["_id"].(bson.ObjectId).Hex(),"vid":util.ObjToString((*vstmp)["vid"])})
			}
			go Mgo.Del("site_versioninfo", bson.M{"pid": _id,"vid":util.ObjToString((*vstmp)["vid"])})
			go Mgo.Del("site_cleanup", bson.M{"pid": _id,"vid":util.ObjToString((*vstmp)["vid"])})
			go Mgo.Del("site_rule_back", bson.M{"pid": _id,"vid":util.ObjToString((*vstmp)["vid"])})
			go Mgo.Del("site_tag", bson.M{"pid": _id,"vid":util.ObjToString((*vstmp)["vid"])})
			go Mgo.Del("site_tagdetailinfo", bson.M{"pid": _id,"vid":util.ObjToString((*vstmp)["vid"])})
			c.JSON(200, gin.H{"rep": true})
		}
	})
	//开关按钮
	Admin.POST("/site_management/use", func(c *gin.Context) {
		_id, _ := c.GetPostForm("_id")
		isuse, _ := c.GetPostForm("isuse")
		b := Mgo.UpdateById("site_management", _id, `{"$set":{"isuse":`+isuse+`}}`)
		c.JSON(200, gin.H{"rep": b})
	})
	//抽取合并开关按钮
	Admin.POST("/site_management/usemerge", func(c *gin.Context) {
		_id, _ := c.GetPostForm("_id")
		ismerge, _ := c.GetPostForm("ismerge")
		b := Mgo.UpdateById("site_management", _id, `{"$set":{"ismerge":`+ismerge+`}}`)
		c.JSON(200, gin.H{"rep": b})
	})
	//属性
	Admin.GET("/site_management/info", func(c *gin.Context) {
		vid := c.Query("vid")
		pid := c.Query("pid")
		c.HTML(
			http.StatusOK, "site_versioninfo.html",
			gin.H{"vid": vid, "pid": pid},
		)
	})
	//属性配置
	Admin.POST("/site_management/infodata", func(c *gin.Context) {
		vid := c.PostForm("vid")
		pid := c.PostForm("pid")
		list, _ := Mgo.Find("site_versioninfo", `{"vid":"`+vid+`","pid":"`+pid+`","delete":false}`, `{"_id":-1}`, nil, false, -1, -1)
		c.JSON(200, gin.H{"data": list, "vid": vid, "pid": pid})
	})
	//属性保存
	Admin.POST("/site_management/infosave", func(c *gin.Context) {
		_id, _ := c.GetPostForm("_id")
		data := GetPostForm(c)
		if _id != "" {
			Mgo.UpdateById("site_versioninfo", _id, map[string]interface{}{"$set": data})
			c.JSON(200, gin.H{"rep": true})
		} else {
			s_field, _ := c.GetPostForm("s_field")
			vid, _ := c.GetPostForm("vid")
			pid, _ := c.GetPostForm("pid")
			tmp, _ := Mgo.FindOne("site_versioninfo", `{"s_field":"`+s_field+`","vid":"`+vid+`","pid":"`+pid+`","delete":false}`)
			if len(*tmp) > 0 {
				c.JSON(200, gin.H{"rep": false})
			} else {
				data["l_createtime"] = time.Now().Unix()
				data["s_username"] = sessions.Default(c).Get("username")
				data["l_lasttime"] = time.Now().Unix()
				data["delete"] = false
				pid := Mgo.Save("site_versioninfo", data)
				fromvid, _ := data["s_pversionid"].(string)
				if fromvid != "" {
					copyFieldRules(vid, pid, s_field, fromvid, sessions.Default(c).Get("username").(string), true)
				}
				c.JSON(200, gin.H{"rep": true})
			}
		}
	})
	//属性use按钮
	Admin.POST("/site_management/infouse", func(c *gin.Context) {
		_id, _ := c.GetPostForm("_id")
		isuse, _ := c.GetPostForm("isuse")
		b := Mgo.UpdateById("site_versioninfo", _id, `{"$set":{"isuse":`+isuse+`}}`)
		c.JSON(200, gin.H{"rep": b})
	})
	//属性删除按钮
	Admin.POST("/site_management/infodel", func(c *gin.Context) {
		_id, _ := c.GetPostForm("_id")
		b := Mgo.UpdateById("site_versioninfo", _id, `{"$set":{"delete":true}}`)
		v, _ := Mgo.FindById("site_versioninfo", _id, `{"vid":1}`)
		go DelLogic(util.ObjToString((*v)["vid"]), _id, true)
		//b := Mgo.Del("site_versioninfo", `{"_id":"`+_id+`"}`)
		c.JSON(200, gin.H{"rep": b})
	})

	//逻辑页面
	Admin.GET("/site_management/rulelogic", func(c *gin.Context) {
		vid := c.Query("vid")
		pid := c.Query("pid")
		verinfo, _ := Mgo.FindById("site_versioninfo", pid, bson.M{"pid": 1})
		c.HTML(200, "site_rule_logiclist.html", gin.H{"vid": vid, "pid": pid, "pzid": (*verinfo)["pid"]})
	})
	//逻辑页面数据展示
	Admin.POST("/site_management/rulelogic/data", func(c *gin.Context) {
		vid, _ := c.GetPostForm("vid")
		pid, _ := c.GetPostForm("pid")
		data, _ := Mgo.Find("site_rule_logic", `{"vid":"`+vid+`","pid":"`+pid+`","delete":false}`, `{"_id":-1}`, nil, false, -1, -1)
		c.JSON(200, gin.H{"data": data, "vid": vid, "pid": pid})
	})
	//逻辑页面数据保存
	Admin.POST("/site_management/rulelogic/save", func(c *gin.Context) {
		data := GetPostForm(c)
		_id, _ := c.GetPostForm("_id")
		b := false
		if _id == "" {
			data["l_createtime"] = time.Now().Unix()
			data["s_username"] = sessions.Default(c).Get("username")
			data["delete"] = false
			b = Mgo.Save("site_rule_logic", data) != ""
		} else {
			data["l_lasttime"] = time.Now().Unix()
			b = Mgo.Update("site_rule_logic", `{"_id":"`+_id+`"}`, map[string]interface{}{
				"$set": data,
			}, true, false)
		}
		c.JSON(200, gin.H{"rep": b})
	})
	//逻辑页面删除按钮
	Admin.POST("/site_management/rulelogic/del", func(c *gin.Context) {
		_id, _ := c.GetPostForm("_id")
		//b := Mgo.Del("rule_logic", `{"_id":"`+_id+`"}`)
		b := Mgo.UpdateById("site_rule_logic", _id, `{"$set":{"delete":true}}`)
		go DelLogicPre(_id, true)
		go DelLogicCore(_id, true)
		go DelLogicBack(_id, true)
		c.JSON(200, gin.H{"rep": b})
	})
	//逻辑页面启用按钮
	Admin.POST("/site_management/rulelogic/use", func(c *gin.Context) {
		_id, _ := c.GetPostForm("_id")
		isuse, _ := c.GetPostForm("isuse")
		b := Mgo.UpdateById("site_rule_logic", _id, `{"$set":{"isuse":`+isuse+`}}`)
		c.JSON(200, gin.H{"rep": b})
	})
	//前置规则
	Admin.GET("/site_management/logicpre", func(c *gin.Context) {
		vid := c.Query("vid")
		pid := c.Query("pid")
		sid := c.Query("sid")
		verinfo, _ := Mgo.FindById("site_versioninfo", pid, bson.M{"pid": 1})
		c.HTML(200, "site_rule_logicprelist.html", gin.H{"vid": vid, "pid": pid, "sid": sid, "pzid": (*verinfo)["pid"]})
	})
	Admin.POST("/site_management/logicpre/data", func(c *gin.Context) {
		vid, _ := c.GetPostForm("vid")
		pid, _ := c.GetPostForm("pid")
		sid, _ := c.GetPostForm("sid")
		data, _ := Mgo.Find("site_rule_logicpre", `{"sid":"`+sid+`","delete":false}`, `{"_id":-1}`, nil, false, -1, -1)
		c.JSON(200, gin.H{"data": data, "vid": vid, "pid": pid, "sid": sid})
	})

	Admin.POST("/site_management/logicpre/save", func(c *gin.Context) {
		data := GetPostForm(c)
		_id, _ := c.GetPostForm("_id")
		b := false
		if _id == "" {
			data["l_createtime"] = time.Now().Unix()
			data["s_username"] = sessions.Default(c).Get("username")
			data["delete"] = false
			s_type := data["s_type"]
			code := ""
			if s_type == "0" { //抽取前置正则E_FE
				code = getSyncIndex(E_FE)
			} else { //抽取前置脚本
				code = getSyncIndex(E_FL)
			}
			data["s_code"] = code
			b = Mgo.Save("site_rule_logicpre", data) != ""
		} else {
			data["l_lasttime"] = time.Now().Unix()
			b = Mgo.Update("site_rule_logicpre", `{"_id":"`+_id+`"}`, map[string]interface{}{
				"$set": data,
			}, true, false)
		}
		c.JSON(200, gin.H{"rep": b})
	})

	Admin.POST("/site_management/logicpre/del", func(c *gin.Context) {
		_id, _ := c.GetPostForm("_id")
		//b := Mgo.Del("rule_logicpre", `{"_id":"`+_id+`"}`)
		b := Mgo.UpdateById("site_rule_logicpre", _id, `{"$set":{"delete":true}}`)
		c.JSON(200, gin.H{"rep": b})
	})
	Admin.GET("/site_management/logicore", func(c *gin.Context) {
		vid := c.Query("vid")
		pid := c.Query("pid")
		sid := c.Query("sid")
		verinfo, _ := Mgo.FindById("site_versioninfo", pid, bson.M{"pid": 1})
		//查询属性字段
		tmp, _ := Mgo.FindById("site_versioninfo", pid, `{"s_field":1}`)
		c.HTML(200, "site_rule_logicore.html", gin.H{"vid": vid, "pid": pid, "sid": sid, "field": (*tmp)["s_field"], "pzid": (*verinfo)["pid"]})
	})
	Admin.GET("/site_management/logickv", func(c *gin.Context) {
		vid := c.Query("vid")
		pid := c.Query("pid")
		sid := c.Query("sid")
		verinfo, _ := Mgo.FindById("site_versioninfo", pid, bson.M{"pid": 1})
		//查询属性字段
		tmp, _ := Mgo.FindById("site_versioninfo", pid, `{"s_field":1}`)
		c.HTML(200, "site_rule_logickv.html", gin.H{"vid": vid, "pid": pid, "sid": sid, "field": (*tmp)["s_field"], "pzid": (*verinfo)["pid"]})
	})
	//抽取规则
	Admin.POST("/site_management/logicore/data", func(c *gin.Context) {
		vid, _ := c.GetPostForm("vid")
		pid, _ := c.GetPostForm("pid")
		sid, _ := c.GetPostForm("sid")
		data, _ := Mgo.Find("site_rule_logicore", `{"sid":"`+sid+`","delete":false}`, `{"_id":-1}`, nil, false, -1, -1)
		c.JSON(200, gin.H{"data": data, "vid": vid, "pid": pid, "sid": sid})
	})
	//抽取规则
	Admin.POST("/site_management/logickv/data", func(c *gin.Context) {
		vid, _ := c.GetPostForm("vid")
		pid, _ := c.GetPostForm("pid")
		sid, _ := c.GetPostForm("sid")
		data, _ := Mgo.Find("site_rule_logickv", `{"sid":"`+sid+`","delete":false}`, `{"_id":-1}`, nil, false, -1, -1)
		c.JSON(200, gin.H{"data": data, "vid": vid, "pid": pid, "sid": sid})
	})
	Admin.POST("/site_management/logicore/save", func(c *gin.Context) {
		data := GetPostForm(c)
		_id, _ := c.GetPostForm("_id")
		b := false
		if _id == "" {
			data["l_createtime"] = time.Now().Unix()
			data["s_username"] = sessions.Default(c).Get("username")
			data["delete"] = false
			s_type := data["s_type"]
			code := ""
			if s_type == "0" { //抽取逻辑正则
				code = getSyncIndex(E_CE)
			} else { //抽取逻辑脚本
				code = getSyncIndex(E_CL)
			}
			data["s_code"] = code
			b = Mgo.Save("site_rule_logicore", data) != ""
		} else {
			data["l_lasttime"] = time.Now().Unix()
			b = Mgo.Update("site_rule_logicore", `{"_id":"`+_id+`"}`, map[string]interface{}{
				"$set": data,
			}, true, false)
		}
		c.JSON(200, gin.H{"rep": b})
	})
	Admin.POST("/site_management/logickv/save", func(c *gin.Context) {
		data := GetPostForm(c)
		_id, _ := c.GetPostForm("_id")
		b := false
		if _id == "" {
			data["l_createtime"] = time.Now().Unix()
			data["s_username"] = sessions.Default(c).Get("username")
			data["delete"] = false
			s_type := data["s_type"]
			code := ""
			if s_type == "0" { //抽取逻辑正则
				code = getSyncIndex(E_CE)
			} else { //抽取逻辑脚本
				code = getSyncIndex(E_CL)
			}
			data["s_code"] = code
			b = Mgo.Save("site_rule_logickv", data) != ""
		} else {
			data["l_lasttime"] = time.Now().Unix()
			b = Mgo.Update("site_rule_logickv", `{"_id":"`+_id+`"}`, map[string]interface{}{
				"$set": data,
			}, true, false)
		}
		c.JSON(200, gin.H{"rep": b})
	})
	Admin.POST("/site_management/logicore/del", func(c *gin.Context) {
		_id, _ := c.GetPostForm("_id")
		//b := Mgo.Del("rule_logicore", `{"_id":"`+_id+`"}`)
		b := Mgo.UpdateById("site_rule_logicore", _id, `{"$set":{"delete":true}}`)
		c.JSON(200, gin.H{"rep": b})
	})
	Admin.POST("/site_management/logickv/del", func(c *gin.Context) {
		_id, _ := c.GetPostForm("_id")
		//b := Mgo.Del("rule_logicore", `{"_id":"`+_id+`"}`)
		b := Mgo.UpdateById("site_rule_logickv", _id, `{"$set":{"delete":true}}`)
		c.JSON(200, gin.H{"rep": b})
	})
	Admin.POST("/site_management/logicore/use", func(c *gin.Context) {
		_id, _ := c.GetPostForm("_id")
		isuse, _ := c.GetPostForm("isuse")
		b := Mgo.UpdateById("site_rule_logicore", _id, `{"$set":{"isuse":`+isuse+`}}`)
		c.JSON(200, gin.H{"rep": b})
	})
	Admin.POST("/site_management/logickv/use", func(c *gin.Context) {
		_id, _ := c.GetPostForm("_id")
		isuse, _ := c.GetPostForm("isuse")
		b := Mgo.UpdateById("site_rule_logickv", _id, `{"$set":{"isuse":`+isuse+`}}`)
		c.JSON(200, gin.H{"rep": b})
	})

	//后置规则
	Admin.GET("/site_management/logicback", func(c *gin.Context) {
		vid := c.Query("vid")
		pid := c.Query("pid")
		sid := c.Query("sid")
		verinfo, _ := Mgo.FindById("site_versioninfo", pid, bson.M{"pid": 1})
		//查询属性字段
		tmp, _ := Mgo.FindById("site_versioninfo", pid, `{"s_field":1}`)
		c.HTML(200, "site_rule_logicbacklist.html", gin.H{"vid": vid, "pid": pid, "sid": sid, "field": (*tmp)["s_field"], "pzid": (*verinfo)["pid"]})
	})
	Admin.POST("/site_management/logicback/data", func(c *gin.Context) {
		vid, _ := c.GetPostForm("vid")
		pid, _ := c.GetPostForm("pid")
		sid, _ := c.GetPostForm("sid")
		data, _ := Mgo.Find("site_rule_logicback", `{"sid":"`+sid+`","delete":false}`, `{"_id":-1}`, nil, false, -1, -1)
		c.JSON(200, gin.H{"data": data, "vid": vid, "pid": pid, "sid": sid})
	})
	Admin.POST("/site_management/logicback/save", func(c *gin.Context) {
		data := GetPostForm(c)
		_id, _ := c.GetPostForm("_id")
		b := false
		if _id == "" {
			data["l_createtime"] = time.Now().Unix()
			data["s_username"] = sessions.Default(c).Get("username")
			data["delete"] = false
			s_type := data["s_type"]
			code := ""
			if s_type == "0" { //抽取后置正则E_FE
				code = getSyncIndex(E_BE)
			} else { //抽取后置脚本
				code = getSyncIndex(E_BL)
			}
			data["s_code"] = code
			b = Mgo.Save("site_rule_logicback", data) != ""
		} else {
			data["l_lasttime"] = time.Now().Unix()
			b = Mgo.Update("site_rule_logicback", `{"_id":"`+_id+`"}`, map[string]interface{}{
				"$set": data,
			}, true, false)
		}
		c.JSON(200, gin.H{"rep": b})
	})
	Admin.POST("/site_management/logicback/del", func(c *gin.Context) {
		_id, _ := c.GetPostForm("_id")
		b := Mgo.UpdateById("site_rule_logicback", _id, `{"$set":{"delete":true}}`)
		c.JSON(200, gin.H{"rep": b})
	})
	//站点后置规则
	Admin.GET("/site_management/ruleback", func(c *gin.Context) {
		version := c.Query("version")
		vid := c.Query("vid")
		pid := c.Query("pid")
		c.HTML(200, "site_rule_backlist.html", gin.H{"version": version, "vid": vid, "pid": pid})
	})
	Admin.POST("/site_management/ruleback/data", func(c *gin.Context) {
		version, _ := c.GetPostForm("version")
		vid := c.PostForm("vid")
		pid := c.PostForm("pid")
		data, _ := Mgo.Find("site_rule_back", `{"s_version":"`+version+`","pid":"`+pid+`","delete":false,"vid":"`+vid+`"}`, `{"_id":-1}`, nil, false, -1, -1)
		c.JSON(200, gin.H{"data": data, "version": version})
	})
	Admin.POST("/site_management/ruleback/save", func(c *gin.Context) {
		data := GetPostForm(c)
		_id, _ := c.GetPostForm("_id")
		b := false
		if _id == "" {
			data["l_createtime"] = time.Now().Unix()
			data["s_username"] = sessions.Default(c).Get("username")
			data["delete"] = false
			s_type := data["s_type"]
			code := ""
			if s_type == "0" { //前置正则
				code = getSyncIndex(B_E)
			} else { //前置lua脚本
				code = getSyncIndex(B_L)
			}
			data["s_code"] = code
			b = Mgo.Save("site_rule_back", data) != ""
		} else {
			data["l_lasttime"] = time.Now().Unix()
			b = Mgo.Update("site_rule_back", `{"_id":"`+_id+`"}`, map[string]interface{}{
				"$set": data,
			}, true, false)
		}
		c.JSON(200, gin.H{"rep": b})
	})
	Admin.POST("/site_management/ruleback/searchbyid", func(c *gin.Context) {
		_id, _ := c.GetPostForm("_id")
		data, _ := Mgo.FindById("/site_rule_back", _id, nil)
		c.JSON(200, gin.H{"rep": data})
	})
	Admin.POST("/site_management/ruleback/del", func(c *gin.Context) {
		_id, _ := c.GetPostForm("_id")
		//b := Mgo.Del("rule_back", `{"_id":"`+_id+`"}`)
		b := Mgo.UpdateById("site_rule_back", _id, `{"$set":{"delete":true}}`)
		c.JSON(200, gin.H{"rep": b})
	})
	//tag
	Admin.GET("/site_management/tag", func(c *gin.Context) {
		version := c.Query("version")
		pid := c.Query("pid")
		vid := c.Query("vid")
		c.HTML(200, "site_taglist.html", gin.H{"version": version, "vid": vid, "pid": pid})
	})
	Admin.POST("/site_management/tag/data", TagDataSite)
	Admin.POST("/site_management/tag/save", TagSaveSite)
	Admin.POST("/site_management/tag/del", TagDelSite)

	//onetag
	Admin.GET("/site_management/onetag", func(c *gin.Context) {
		version := c.Query("version")
		tagname := c.Query("tagname")
		tp := c.Query("tp")
		parentid := c.Query("parentid")
		tag, _ := Mgo.FindById("site_tag", parentid, bson.M{"pid": 1, "vid": 1})
		c.HTML(200, "site_onetag.html", gin.H{"version": version, "vid": (*tag)["vid"], "pid": (*tag)["pid"], "tagname": tagname, "tp": tp, "parentid": parentid})
	})
	Admin.POST("/site_management/onetag/data", OneTagDataSite)
	Admin.POST("/site_management/onetag/create", OneTagCreateSite)
	Admin.POST("/site_management/onetag/del", OneTagDelSite)
	Admin.POST("/site_management/onetag/editsave", OneTagEditSaveSite)
	Admin.POST("/site_management/onetag/searchone", OneTagSearchSite)

	//清理函数
	Admin.GET("/site_management/clear", func(c *gin.Context) {
		version := c.Query("version")
		vid := c.Query("vid")
		pid := c.Query("pid")
		field, _ := Mgo.Find("fields", nil, `{"_id":-1}`, nil, false, -1, -1)
		c.HTML(200, "site_clear.html", gin.H{"version": version, "field": field, "vid": vid, "pid": pid})
	})
	Admin.POST("/site_management/clear/data", func(c *gin.Context) {
		version, _ := c.GetPostForm("version")
		vid := c.PostForm("vid")
		pid := c.PostForm("pid")
		data, _ := Mgo.Find("site_cleanup", `{"s_version":"`+version+`","vid":"`+vid+`","pid":"`+pid+`","delete":false}`, `{"_id":-1}`, nil, false, -1, -1)
		for _, d := range *data {
			timeStr := time.Unix(d["l_intime"].(int64), 0).Format(Date_Short_Layout)
			d["l_intime"] = timeStr
		}
		c.JSON(200, gin.H{"data": data})
	}) //加载数据
	Admin.POST("/site_management/clear/save", func(c *gin.Context) {
		clearTmpArr := make([]string, 0)
		clear := make([]string, 0)
		clearInfo := make([]string, 0)
		save := make(map[string]interface{})
		clearJsonStr, _ := c.GetPostForm("clearJsonStr")
		err := json.Unmarshal([]byte(clearJsonStr), &clearTmpArr)
		if err == nil && len(clearTmpArr) > 0 {
			for _, v := range clearTmpArr {
				clearTmpSplitArr := strings.Split(v, "+")
				clearInfo = append(clearInfo, clearTmpSplitArr[0])
				clear = append(clear, clearTmpSplitArr[1])
			}
		} else {
			c.JSON(200, gin.H{"rep": false})
			return
		}
		_id, _ := c.GetPostForm("_id")
		if _id == "" { //保存
			version, _ := c.GetPostForm("version")
			username, _ := c.GetPostForm("username")
			fieldname, _ := c.GetPostForm("fieldname")
			pid := c.PostForm("pid")
			vid := c.PostForm("vid")
			fieldArr := strings.Split(fieldname, "+")
			data, _ := Mgo.FindOne("site_cleanup", `{"s_version":"`+version+`","pid":"`+pid+`","s_field":"`+fieldArr[1]+`","delete":false}`)
			if len(*data) > 0 { //创建判重
				c.JSON(200, gin.H{"rep": false})
				return
			}
			save = map[string]interface{}{
				"s_version": version,
				"s_creater": username,
				"l_intime":  time.Now().Unix(),
				"s_field":   fieldArr[1],
				"s_name":    fieldArr[0],
				"clear":     clear,
				"clearInfo": clearInfo,
				"delete":    false,
				"pid":       pid,
				"vid":       vid,
			}
			b := Mgo.Save("site_cleanup", save)
			if b != "" {
				c.JSON(200, gin.H{"rep": true})
			} else {
				c.JSON(200, gin.H{"rep": false})
			}
		} else { //更新
			save = map[string]interface{}{
				"clear":     clear,
				"clearInfo": clearInfo,
				"l_intime":  time.Now().Unix(),
			}
			f := Mgo.Update("site_cleanup", `{"_id":"`+_id+`"}`, map[string]interface{}{"$set": save}, true, false)
			if f {
				c.JSON(200, gin.H{"rep": true})
			} else {
				c.JSON(200, gin.H{"rep": false})
			}
		}
	}) //保存数据
	Admin.POST("/site_management/clear/del", func(c *gin.Context) {
		_id, _ := c.GetPostForm("_id")
		b := Mgo.Update("site_cleanup", `{"_id":"`+_id+`"}`, map[string]interface{}{
			"$set": map[string]interface{}{"delete": true},
		}, false, false)
		if b {
			c.JSON(200, gin.H{"rep": true})
		} else {
			c.JSON(200, gin.H{"rep": false})
		}
	}) //删除数据

	//校验
	//正则规则验证
	Admin.POST("/site_management/check/prerule", func(c *gin.Context) {
		rule, _ := c.GetPostForm("s_rule")
		con, _ := c.GetPostForm("s_testcon")
		str := checkPreReg(con, rule)
		c.JSON(200, gin.H{"rep": str})
	})
	Admin.POST("/site_management/check/extrule", func(c *gin.Context) {
		rule, _ := c.GetPostForm("s_rule")
		con, _ := c.GetPostForm("s_testcon")
		field, _ := c.GetPostForm("s_field")
		tmp := checkCoreReg(field, con, rule)
		c.JSON(200, gin.H{"rep": tmp})
	})
	Admin.POST("/site_management/check/backrule", func(c *gin.Context) {
		rule, _ := c.GetPostForm("s_rule")
		con, _ := c.GetPostForm("s_testcon")
		str := checkBackReg(con, rule)
		c.JSON(200, gin.H{"rep": str})
	})

	//lua脚本验证
	//通用前置验证
	Admin.GET("/site_management/check/lua/pre", func(c *gin.Context) {
		version := c.Query("version")
		s_code := c.Query("s_code")
		rule, _ := Mgo.FindOne("site_rule_pre", `{"s_code":"`+s_code+`"}`)
		(*rule)["_id"] = util.BsonIdToSId((*rule)["_id"])
		c.HTML(200, "site_check_luapre.html", gin.H{"version": version, "code": s_code, "rule": &rule, "infos": getCheckInfos()})
	})
	Admin.POST("/site_management/check/lua/prerule", func(c *gin.Context) {
		luascript, _ := c.GetPostForm("s_luascript")
		infoid, _ := c.GetPostForm("infoid")
		code, _ := c.GetPostForm("s_code")
		name, _ := c.GetPostForm("s_name")
		extinfo := checkPreScript(code, name, infoid, luascript)
		c.JSON(200, gin.H{"rep": extinfo})
	})
	//通用后置验证
	Admin.GET("/site_management/check/lua/back", func(c *gin.Context) {
		version := c.Query("version")
		s_code := c.Query("s_code")
		rule, _ := Mgo.FindOne("site_rule_back", `{"s_code":"`+s_code+`"}`)
		(*rule)["_id"] = util.BsonIdToSId((*rule)["_id"])
		c.HTML(200, "site_check_luaback.html", gin.H{"version": version, "code": s_code, "rule": &rule, "infos": getCheckInfos()})
	})
	Admin.POST("/site_management/check/lua/backrule", func(c *gin.Context) {
		luascript, _ := c.GetPostForm("s_luascript")
		infoid, _ := c.GetPostForm("infoid")
		version, _ := c.GetPostForm("s_version")
		code, _ := c.GetPostForm("s_code")
		name, _ := c.GetPostForm("s_name")
		extinfo := checkBackScript("site_rule_back", code, name, version, infoid, luascript, true)
		c.JSON(200, gin.H{"rep": extinfo})
	})
	//抽取前置验证
	Admin.GET("/site_management/check/lua/corepre", func(c *gin.Context) {
		vid := c.Query("vid")
		pid := c.Query("pid")
		sid := c.Query("sid")
		s_code := c.Query("s_code")
		rule, _ := Mgo.FindOne("site_rule_logicpre", `{"s_code":"`+s_code+`"}`)
		(*rule)["_id"] = util.BsonIdToSId((*rule)["_id"])
		c.HTML(200,
			"site_check_luacorepre.html",
			gin.H{"code": s_code, "rule": &rule, "infos": getCheckInfos(),
				"pid": pid, "vid": vid, "sid": sid},
		)
	})
	Admin.POST("/site_management/check/lua/coreprerule", func(c *gin.Context) {
		luascript, _ := c.GetPostForm("s_luascript")
		infoid, _ := c.GetPostForm("infoid")
		code, _ := c.GetPostForm("s_code")
		name, _ := c.GetPostForm("s_name")
		extinfo := checkPreScript(code, name, infoid, luascript)
		c.JSON(200, gin.H{"rep": extinfo})
	})
	//抽取验证
	Admin.GET("/site_management/check/lua/core", func(c *gin.Context) {
		vid := c.Query("vid")
		pid := c.Query("pid")
		sid := c.Query("sid")
		s_code := c.Query("s_code")
		rule, _ := Mgo.FindOne("site_rule_logicore", `{"s_code":"`+s_code+`"}`)
		(*rule)["_id"] = util.BsonIdToSId((*rule)["_id"])
		c.HTML(200,
			"site_check_luacore.html",
			gin.H{"code": s_code, "rule": &rule, "infos": getCheckInfos(),
				"pid": pid, "vid": vid, "sid": sid},
		)
	})
	Admin.POST("/site_management/check/lua/corerule", func(c *gin.Context) {
		luascript, _ := c.GetPostForm("s_luascript")
		infoid, _ := c.GetPostForm("infoid")
		code, _ := c.GetPostForm("s_code")
		name, _ := c.GetPostForm("s_name")
		extinfo := checkCoreScript(code, name, infoid, luascript)
		c.JSON(200, gin.H{"rep": extinfo})
	})
	//抽取后置验证
	Admin.GET("/site_management/check/lua/coreback", func(c *gin.Context) {
		vid := c.Query("vid")
		pid := c.Query("pid")
		sid := c.Query("sid")
		s_code := c.Query("s_code")
		rule, _ := Mgo.FindOne("site_rule_logicback", `{"s_code":"`+s_code+`"}`)
		(*rule)["_id"] = util.BsonIdToSId((*rule)["_id"])
		c.HTML(200,
			"site_check_luacoreback.html",
			gin.H{"code": s_code, "rule": &rule, "infos": getCheckInfos(),
				"pid": pid, "vid": vid, "sid": sid},
		)
	})

	Admin.POST("/site_management/check/lua/corebackrule", func(c *gin.Context) {
		luascript, _ := c.GetPostForm("s_luascript")
		infoid, _ := c.GetPostForm("infoid")
		code, _ := c.GetPostForm("s_code")
		name, _ := c.GetPostForm("s_name")
		vid, _ := c.GetPostForm("vid")
		version, _ := Mgo.FindById("version", vid, `{"version":1}`)
		extinfo := checkBackScript("rule_back", code, name, util.ObjToString((*version)["version"]), infoid, luascript, true)
		c.JSON(200, gin.H{"rep": extinfo})
	})
	//清理逻辑脚本验证
	Admin.GET("/site_management/check/lua/clearlogic", func(c *gin.Context) {
		vid := c.Query("vid")
		pid := c.Query("pid")
		s_code := c.Query("s_code")
		rule, _ := Mgo.FindOne("site_clearulelogic", `{"s_code":"`+s_code+`"}`)
		(*rule)["_id"] = util.BsonIdToSId((*rule)["_id"])
		c.HTML(200,
			"site_check_luaclearlogic.html",
			gin.H{"code": s_code, "rule": &rule, "infos": getCheckInfos(),
				"pid": pid, "vid": vid},
		)
	})
	Admin.POST("/site_management/check/lua/checkclearlua", func(c *gin.Context) {
		luascript, _ := c.GetPostForm("s_luascript")
		code, _ := c.GetPostForm("s_code")
		name, _ := c.GetPostForm("s_name")
		rid, _ := c.GetPostForm("rid")
		resultcoll, _ := c.GetPostForm("resultcoll")
		if rid == "" || resultcoll == "" {
			c.JSON(200, gin.H{"rep": nil})
		} else {
			extinfo := checkClearScript(code, name, resultcoll, rid, luascript)
			c.JSON(200, gin.H{"rep": extinfo})
		}

	})
}

//标签库列表
func TagDataSite(c *gin.Context) {
	version, _ := c.GetPostForm("version")
	pid := c.PostForm("pid")
	vid := c.PostForm("vid")
	data, _ := Mgo.Find("site_tag", `{"s_version":"`+version+`","pid":"`+pid+`","vid":"`+vid+`","delete":false}`, `{"_id":-1}`, nil, false, -1, -1)
	for _, d := range *data {
		timeStr := time.Unix(d["l_intime"].(int64), 0).Format(Date_Short_Layout)
		d["l_intime"] = timeStr
	}
	c.JSON(200, gin.H{"data": data})
}

//添加标签
func TagSaveSite(c *gin.Context) {
	tagname, _ := c.GetPostForm("tagname")
	version, _ := c.GetPostForm("version")
	username, _ := c.GetPostForm("username")
	pid := c.PostForm("pid")
	vid := c.PostForm("vid")
	tp, _ := c.GetPostForm("tp")
	data, _ := Mgo.FindOne("site_tag", `{"s_tagname":"`+tagname+`","pid":"`+pid+`","vid":"`+vid+`","s_version":"`+version+`","delete":false}`)
	if len(*data) > 0 { //判重，防止添加name相同的标签
		c.JSON(200, gin.H{"rep": false})
		return
	}
	save := map[string]interface{}{
		"s_tagname": tagname,
		"s_version": version,
		"s_creater": username,
		"s_type":    tp,
		"l_intime":  time.Now().Unix(),
		"delete":    false,
		"vid":       vid,
		"pid":       pid,
	}
	b := Mgo.Save("site_tag", save)
	if b != "" {
		c.JSON(200, gin.H{"rep": true})
	} else {
		c.JSON(200, gin.H{"rep": false})
	}
}

//删除标签
func TagDelSite(c *gin.Context) {
	_id, _ := c.GetPostForm("_id")
	b := Mgo.Update("site_tag", `{"_id":"`+_id+`"}`, map[string]interface{}{
		"$set": map[string]interface{}{"delete": true},
	}, false, false)
	data, _ := Mgo.Find("site_tagdetailinfo", `{"s_parentid":"`+_id+`"}`, `{"_id":-1}`, nil, false, -1, -1)
	if len(*data) > 0 { //删除父标签下所有详细标签
		for _, d := range *data {
			cid := d["_id"].(bson.ObjectId).Hex()
			//Mgo.Del("tagdetailinfo", `{"_id":"`+cid+`"}`)
			Mgo.Update("site_tagdetailinfo", `{"_id":"`+cid+`"}`, map[string]interface{}{
				"$set": map[string]interface{}{"delete": true},
			}, false, false)
		}
	}
	if b {
		c.JSON(200, gin.H{"rep": true})
	} else {
		c.JSON(200, gin.H{"rep": false})
	}
}

//查找某个tag的信息
func OneTagDataSite(c *gin.Context) {
	version, _ := c.GetPostForm("version")
	parentid, _ := c.GetPostForm("parentid")
	pid := c.PostForm("pid")
	vid := c.PostForm("vid")
	data, _ := Mgo.Find("site_tagdetailinfo", `{"s_version":"`+version+`","pid":"`+pid+`","vid":"`+vid+`","s_parentid":"`+parentid+`","delete":false}`, `{"_id":-1}`, nil, false, -1, -1)
	for _, d := range *data {
		timeStr := time.Unix(d["l_intime"].(int64), 0).Format(Date_Short_Layout)
		d["l_intime"] = timeStr
	}
	c.JSON(200, gin.H{"data": data})
}

//添加详细标签
func OneTagCreateSite(c *gin.Context) {
	name, _ := c.GetPostForm("name")
	version, _ := c.GetPostForm("version")
	parentid, _ := c.GetPostForm("parentid")
	pid := c.PostForm("pid")
	vid := c.PostForm("vid")
	data, _ := Mgo.FindOne("site_tagdetailinfo", `{"s_name":"`+name+`","pid":"`+pid+`","vid":"`+vid+`","s_parentid":"`+parentid+`","s_version":"`+version+`","delete":false}`)
	if len(*data) > 0 { //判重
		c.JSON(200, gin.H{"rep": false})
		return
	}
	tp, _ := c.GetPostForm("tp")
	field, _ := c.GetPostForm("field")
	content, _ := c.GetPostForm("content")
	username, _ := c.GetPostForm("username")
	pratagname, _ := c.GetPostForm("pratagname")
	var jsondata interface{}
	err := json.Unmarshal([]byte(content), &jsondata)
	if err != nil { //不是json格式
		c.JSON(200, gin.H{"rep": false})
		return
	}
	save := make(map[string]interface{})
	save = map[string]interface{}{
		"s_pratagname": pratagname,
		"s_name":       name,
		"s_field":      field,
		"s_version":    version,
		"s_creater":    username,
		"s_type":       tp,
		"l_intime":     time.Now().Unix(),
		"content":      jsondata,
		"s_parentid":   parentid,
		"delete":       false,
		"vid":          vid,
		"pid":          pid,
	}
	b := Mgo.Save("site_tagdetailinfo", save)
	if b != "" {
		c.JSON(200, gin.H{"rep": true})
	} else {
		c.JSON(200, gin.H{"rep": false})
	}
}

//删除某个详细标签
func OneTagDelSite(c *gin.Context) {
	_id, _ := c.GetPostForm("_id")
	b := Mgo.Update("site_tagdetailinfo", `{"_id":"`+_id+`"}`, map[string]interface{}{
		"$set": map[string]interface{}{"delete": true},
	}, false, false)
	if b {
		c.JSON(200, gin.H{"rep": true})
	} else {
		c.JSON(200, gin.H{"rep": false})
	}
}

//修改某个详细标签
func OneTagEditSaveSite(c *gin.Context) {
	_id, _ := c.GetPostForm("_id")
	content, _ := c.GetPostForm("content")
	var jsondata interface{}
	err := json.Unmarshal([]byte(content), &jsondata)
	if err != nil { //不是json格式
		c.JSON(200, gin.H{"rep": false})
		return
	}
	set := make(map[string]interface{})
	set["content"] = jsondata
	if jsondata != nil {
		b := Mgo.Update("site_tagdetailinfo", `{"_id":"`+_id+`"}`, map[string]interface{}{"$set": set}, false, false)
		if b {
			c.JSON(200, gin.H{"rep": true})
		} else {
			c.JSON(200, gin.H{"rep": false})
		}
	} else {
		c.JSON(200, gin.H{"rep": false})
	}
}

//根据id查找某个标签
func OneTagSearchSite(c *gin.Context) {
	_id, _ := c.GetPostForm("_id")
	data, _ := Mgo.FindOne("site_tagdetailinfo", `{"_id":"`+_id+`"}`)
	c.JSON(200, gin.H{"data": data})
}

var sysn sync.RWMutex

func getSyncIndex(code string) string {
	tmp := ""
	sysn.Lock()
	Mgo.Update("site_rule_code", `{"code":"`+code+`"}`, bson.M{"$inc": bson.M{"index": 1}}, true, false)
	data, _ := Mgo.FindOne("site_rule_code", `{"code":"`+code+`"}`)
	sysn.Unlock()
	if len(*data) > 0 {
		tmp = code + "_" + fmt.Sprint((*data)["index"])
	}
	return tmp
}
