// distribution 分布式抽取管理
package distribution

import (
	. "jy/admin"
	ecs "jy/cluster"
	db "jy/mongodbutil"
	"log"
	qu "qfw/util"

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

func init() {
	Admin.GET("/distribution", func(c *gin.Context) {
		c.HTML(200, "distribution.html", nil)
	})

	//获取ecs列表
	Admin.POST("/distribution/ecslist", func(c *gin.Context) {
		data, _ := db.Mgo.Find("ecs", `{}`, `{"_id":-1}`, nil, false, -1, -1)
		c.JSON(200, gin.H{"data": data})
	})

	//申请ecs实例、id划段
	Admin.POST("/distribution/runInstances", func(c *gin.Context) {
		s_table, _ := c.GetPostForm("s_table")
		instanceid, _ := c.GetPostForm("instanceid")
		if s_table != "" { //id划段
			sdate, _ := c.GetPostForm("s_date")
			edate, _ := c.GetPostForm("e_date")
			log.Println(s_table, sdate, edate)
			ecs.IdsRange(s_table, sdate, edate)
		} else if instanceid != "" { //实例自动释放时间
			hours, _ := c.GetPostForm("hours")
			hour := qu.IntAll(hours)
			if hour > 0 {
				log.Println(instanceid, hour)
				ecs.ModifyInstanceAutoReleaseTime(instanceid, hour)
			}
		} else { //申请ecs实例
			TaskName, _ := c.GetPostForm("s_name")
			s_computer, _ := c.GetPostForm("s_computer")
			s_flow, _ := c.GetPostForm("s_flow")
			num, _ := c.GetPostForm("i_num")
			hours, _ := c.GetPostForm("i_hours")
			ecs.RunInstances(TaskName, s_computer, s_flow, qu.IntAll(num), qu.IntAll(hours))
		}
		c.JSON(200, gin.H{"rep": true})
	})

	//更新ecs实例状态
	Admin.POST("/distribution/upstatus", func(c *gin.Context) {
		ecs.DescribeInstances()
		c.JSON(200, gin.H{"rep": true})
	})

	//释放ecs实例
	Admin.POST("/distribution/deleteInstance", func(c *gin.Context) {
		InstanceId, _ := c.GetPostForm("InstanceId")
		ecs.DeleteInstance(InstanceId)
		c.JSON(200, gin.H{"rep": true})
	})

	//部署
	Admin.POST("/distribution/deploy", func(c *gin.Context) {
		list, _ := db.Mgo.Find("ecs", `{"Status":"Running"}`, nil, nil, false, -1, -1)
		for _, v := range *list {
			ip := qu.ObjToString(v["ip_nw"])
			id := qu.ObjToString(v["InstanceId"])
			log.Println("部署", ip, id)
			ecs.RunSsh(ip, ecs.Password, 22)
			db.Mgo.Update("ecs", `{"ip_nw":"`+ip+`"}`,
				map[string]interface{}{
					"$set": map[string]interface{}{
						"extstatus": "deploy",
					},
				}, true, false)
		}
		c.JSON(200, gin.H{"rep": true})
	})

	//分发任务
	Admin.POST("/distribution/rangetask", func(c *gin.Context) {
		num := ecs.RunEcsTask()
		log.Println("任务分发完成", num)
		c.JSON(200, gin.H{"rep": true})
	})
}
