// user
package admin

import (
	. "jy/mongodbutil"
	. "jy/util"
	"net/http"
	"time"

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

func init() {
	Admin.GET("/index", func(c *gin.Context) {
		c.HTML(http.StatusOK, "index.html", gin.H{})
	})
	Admin.GET("/user", func(c *gin.Context) {
		c.HTML(http.StatusOK, "user.html", gin.H{})
	})
	Admin.POST("/user/data", User)
	Admin.POST("/user/save", UserSave)
	Admin.POST("/user/searchbyid", UserSearchById)
	Admin.POST("/user/del", UserDel)
	Admin.POST("/user/uppwd", UserUppwd)
}

func User(c *gin.Context) {
	data, _ := Mgo.Find("user", `{}`, nil, nil, false, -1, -1)
	c.JSON(200, gin.H{"data": data})
}

func UserSave(c *gin.Context) {
	email, _ := c.GetPostForm("email")
	pwd, _ := c.GetPostForm("pwd")
	name, _ := c.GetPostForm("name")
	role, _ := c.GetPostForm("role")
	data := map[string]interface{}{
		"email": email,
		"pwd":   Se.EncodeString(pwd),
		"name":  name,
		"role":  role,
		"mtime": time.Now().Unix(),
	}
	b := Mgo.Update("user", `{"email":"`+email+`"}`, data, true, false)
	c.JSON(200, gin.H{"rep": b})
}

func UserSearchById(c *gin.Context) {
	_id, _ := c.GetPostForm("_id")
	data, _ := Mgo.FindById("user", _id, nil)
	(*data)["pwd"] = Se.DecodeString((*data)["pwd"].(string))
	c.JSON(200, gin.H{"rep": data})
}

func UserDel(c *gin.Context) {
	_id, _ := c.GetPostForm("_id")
	b := Mgo.Del("user", `{"_id":"`+_id+`"}`)
	c.JSON(200, gin.H{"rep": b})
}

func UserUppwd(c *gin.Context) {
	_id, _ := c.GetPostForm("_id")
	pwd, _ := c.GetPostForm("pwd")
	b := Mgo.UpdateById("user", _id, `{"$set":{"pwd":"`+Se.EncodeString(pwd)+`"}}`)
	c.JSON(200, gin.H{"rep": b})
}
