package admin

import (
	"encoding/json"
	. "jy/mongodbutil"
	"strings"
	"time"

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

func init() {
	//清理函数
	Admin.GET("/clear", func(c *gin.Context) {
		version := c.Query("version")
		field, _ := Mgo.Find("fields", nil, `{"_id":-1}`, nil, false, -1, -1)
		c.HTML(200, "clear.html", gin.H{"version": version, "field": field})
	})
	Admin.POST("/clear/data", ClearData) //加载数据
	Admin.POST("/clear/save", ClearSave) //保存数据
	Admin.POST("/clear/del", ClearDel)   //删除数据
}

//加载数据
func ClearData(c *gin.Context) {
	version, _ := c.GetPostForm("version")
	data, _ := Mgo.Find("cleanup", `{"s_version":"`+version+`","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 ClearSave(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")
		fieldArr := strings.Split(fieldname, "+")
		data, _ := Mgo.FindOne("cleanup", `{"s_version":"`+version+`","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,
		}
		b := Mgo.Save("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("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})
		}
	}
}

//删除数据
func ClearDel(c *gin.Context) {
	_id, _ := c.GetPostForm("_id")
	b := Mgo.Update("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})
	}
}
