package admin

import (
	"html/template"
	. "jy/mongodbutil"
	. "jy/router"
	qu "qfw/util"
	"strconv"

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

var Admin = Router.Group("/admin")

func init() {
	gin.SetMode("")
	Admin.Use(AuthMiddleWare())
	Router.SetFuncMap(template.FuncMap{
		"session": func(key string) string {
			return ""
		},
		"add": func(a, b int) int {
			return a + b
		},
	})
	Router.LoadHTMLGlob("web/templates/admin/*")
	//获取字段列表
	Admin.POST("/getfields", func(c *gin.Context) {
		list, b := Mgo.Find("fields", `{}`, `{"_id":-1}`, nil, false, -1, -1)
		if b && list != nil {
			for _, v := range *list {
				v["_id"] = v["s_field"]
				v["s_name"] = v["s_name"]
			}
		}
		data := []map[string]interface{}{map[string]interface{}{"_id": "", "s_name": ""}}
		data = append(data, *list...)
		c.JSON(200, gin.H{"data": data})
	})
	//获取城市列表
	Admin.POST("/getcitys", func(c *gin.Context) {
		list, b := Mgo.Find("citys", `{}`, `{"_id":-1}`, nil, false, -1, -1)
		if b && list != nil {
			for _, v := range *list {
				v["s_field"] = ""
			}
		}
		data := []map[string]interface{}{map[string]interface{}{"_id": "", "s_name": ""}}
		data = append(data, *list...)
		c.JSON(200, gin.H{"data": data})
	})
	//获取省份列表
	Admin.POST("/getprovinces", func(c *gin.Context) {
		list, b := Mgo.Find("province", `{}`, `{"_id":-1}`, nil, false, -1, -1)
		if b && list != nil {
			for _, v := range *list {
				v["s_field"] = ""
			}
		}
		data := []map[string]interface{}{map[string]interface{}{"_id": "", "s_name": ""}}
		data = append(data, *list...)
		c.JSON(200, gin.H{"data": data})
	})
	//获取抽取版本列表
	Admin.POST("/getversions", func(c *gin.Context) {
		list, b := Mgo.Find("version", `{"delete":false}`, `{"_id":-1}`, `{"version":1}`, false, -1, -1)
		if b && list != nil {
			for _, v := range *list {
				v["_id"] = qu.BsonIdToSId(v["_id"])
				v["s_name"] = v["version"]
			}
		}
		c.JSON(200, gin.H{"data": list})
	})
	//获取清理版本列表
	Admin.POST("/getclearversions", func(c *gin.Context) {
		list, b := Mgo.Find("clearversion", `{"delete":false}`, `{"_id":-1}`, `{"clearversion":1}`, false, -1, -1)
		if b && list != nil {
			for _, v := range *list {
				v["_id"] = qu.BsonIdToSId(v["_id"])
				v["s_name"] = v["clearversion"]
			}
		}
		c.JSON(200, gin.H{"data": list})
	})
}

func GetPostForm(c *gin.Context) map[string]interface{} {
	val := map[string]interface{}{}
	r := c.Request
	r.ParseForm()
	for k, _ := range r.Form {
		if len(k) < 2 {
			continue
		}
		if k != "_id" {
			v := r.FormValue(k)
			switch k[:2] {
			case "s_": //string型
				val[k] = v
			case "l_": //int64位
				val[k], _ = strconv.ParseInt(v, 10, 64)
			case "i_": //int型
				val[k], _ = strconv.Atoi(v)
			default:
				if v == "true" || v == "false" {
					b, _ := strconv.ParseBool(v)
					val[k] = b
				} else {
					val[k] = v
				}
			}
		}
	}
	return val
}
