package rigger

import (
	"fmt"
	"net/http"

	"ciyon/web/admin"
	c "ciyon/zciyon"
)

func autotask_setwhere(post *c.CiyPost) (map[string]any, *c.CiySQL) {
	query := post.Getobj("query")
	csql := c.NewCiySQL("zc_autotask")
	liid := c.Getint(query, "liid")
	if liid > 0 {
		csql.Where("autotaskstatus", liid)
	}
	csql.Where("types like", c.Getstr(query, "types"))
	order := c.Getstr(query, "order", "id desc")
	csql.Order(order)
	query["order"] = order
	return query, csql
}
func Autotask_init(w http.ResponseWriter, r *http.Request) bool {
	post := c.NewCiyPost(w, r)
	_, userid := admin.Verifyfast(r, c.CiyDB, post)
	if userid == 0 {
		return false
	}
	where, csql := autotask_setwhere(post)
	pageno := post.Getint("pageno", 1)
	pagecount := post.Getint("pagecount", 10)
	csql.Limit(pageno, pagecount)
	rows, mainrowcount, err := c.CiyDB.Get(csql, post.Getint("count"))
	if err != nil {
		return c.ErrJSON(w, "读取错误", err)
	}
	rows = append(rows, map[string]any{
		"id":        "",
		"runcycle":  0,
		"nexttimes": c.Tostamp(),
	})
	ret := map[string]any{}
	ret["where"] = where
	ret["pageno"] = pageno
	ret["pagecount"] = pagecount
	ret["count"] = mainrowcount
	ret["list"] = rows
	if post.Getbool("field") {
		field, fshow := c.CiyDB.GetField(csql)
		c.FieldAdd(&field, &fshow, -1, "_btn", "操作")
		field["runparam"]["thwidth"] = "8em"
		field["nexttimes"]["thwidth"] = "10em"
		field["runcycle"]["thwidth"] = "9em"
		field["autotaskstatus"]["thwidth"] = "6em"
		ret["fshow"] = fshow
		ret["field"] = field
	}
	if post.Getbool("once") {
		once := map[string]any{}
		input := make([]map[string]any, 0)
		input = append(input, map[string]any{
			"form": "name",
			"type": "input",
			"name": "任务名称",
			"prop": ` style="width:8em;"`,
		})
		input = append(input, map[string]any{
			"form": "runfunc",
			"type": "input",
			"name": "入口函数",
			"prop": ` style="width:8em;"`,
		})
		once["input"] = input
		ret["once"] = once
	}
	return c.SuccJSON(w, r, ret)
}
func Autotask_update(w http.ResponseWriter, r *http.Request) bool {
	post := c.NewCiyPost(w, r)
	_, userid := admin.Verifyfast(r, c.CiyDB, post)
	if userid == 0 {
		return false
	}
	if admin.Nopower(c.CiyDB, userid, "p602u") {
		return c.ErrJSON(w, "您未被授权操作")
	}
	id := post.Getint("id")
	name := post.Get("name")
	if name == "" {
		return c.ErrJSON(w, "请填写任务名称")
	}
	runfunc := post.Get("runfunc")
	if runfunc == "" {
		return c.ErrJSON(w, "请填写入口函数")
	}
	runparam := post.Get("runparam")
	nexttimes := post.Getdate("nexttimes")
	runcycle := post.Getint("runcycle")
	if runcycle >= 0 && runcycle < 60 {
		return c.ErrJSON(w, "请填写超过1分钟的执行周期")
	}
	var err error
	var datarow map[string]any
	if id > 0 {
		csql := c.NewCiySQL("zc_autotask")
		csql.Where("id", id)
		datarow, err = c.CiyDB.Getone(csql)
		if datarow == nil {
			return c.ErrJSON(w, "数据不存在", err)
		}
	}
	updata := map[string]any{}
	err = c.CiyDB.Tran(func() error {
		var csql *c.CiySQL
		csql = c.NewCiySQL("zc_autotask")
		csql.Where("name", name)
		csql.Column("id")
		chkid := c.Toint(c.CiyDB.Get1(csql))
		if chkid > 0 && ((id > 0 && chkid != id) || id == 0) {
			return fmt.Errorf("数据已存在")
		}
		updata["name"] = name
		updata["runfunc"] = runfunc
		updata["runparam"] = runparam
		updata["nexttimes"] = nexttimes
		updata["runcycle"] = runcycle
		csql = c.NewCiySQL("zc_autotask")
		if id > 0 {
			csql.Where("id", id)
			_, err = c.CiyDB.Update(csql, updata)
		} else {
			updata["autotaskstatus"] = 90
			if nexttimes == 0 {
				updata["nexttimes"] = c.Tostamp()
			}
			id, err = c.CiyDB.Insert(csql, updata)
		}
		updata["newid"] = id
		if err != nil {
			return fmt.Errorf("更新失败:%v", err)
		}
		admin.SaveLogDB(c.CiyDB, "zc_autotask", datarow, updata)
		return nil
	})
	if err != nil {
		return c.ErrJSON(w, "事务"+err.Error())
	}
	ret := map[string]any{}
	ret["data"] = updata
	return c.SuccJSON(w, r, ret)
}
func Autotask_del(w http.ResponseWriter, r *http.Request) bool {
	post := c.NewCiyPost(w, r)
	_, userid := admin.Verifyfast(r, c.CiyDB, post)
	if userid == 0 {
		return false
	}
	if admin.Nopower(c.CiyDB, userid, "p602d") {
		return c.ErrJSON(w, "您未被授权操作")
	}
	ids := post.Get("ids")
	if ids == "" {
		return c.ErrJSON(w, "请选择至少一条")
	}
	csql := c.NewCiySQL("zc_autotask")
	csql.Where("id in", ids)
	rows, _, err := c.CiyDB.Get(csql)
	if err != nil {
		return c.ErrJSON(w, "读取数据错误", err)
	}
	vids := make([]int, 0)
	err = c.CiyDB.Tran(func() error {
		for _, row := range rows {
			delid := c.Toint(row["id"])
			c.Delme(c.CiyDB, delid, "zc_autotask")
			admin.SaveLogDB(c.CiyDB, "zc_autotask", row, nil)
			vids = append(vids, delid)
		}
		return nil
	})
	if err != nil {
		return c.ErrJSON(w, "事务"+err.Error())
	}
	ret := map[string]any{}
	ret["ids"] = vids
	return c.SuccJSON(w, r, ret)
}

func Autotask_status(w http.ResponseWriter, r *http.Request) bool {
	post := c.NewCiyPost(w, r)
	_, userid := admin.Verifyfast(r, c.CiyDB, post)
	if userid == 0 {
		return false
	}
	if admin.Nopower(c.CiyDB, userid, "p602u") {
		return c.ErrJSON(w, "您未被授权操作")
	}
	id := post.Getint("id")
	status := post.Getint("status")
	csql := c.NewCiySQL("zc_autotask")
	csql.Where("id", id)
	row, err := c.CiyDB.Getone(csql)
	if err != nil {
		return c.ErrJSON(w, "读取数据错误", err)
	}
	updata := map[string]any{}
	err = c.CiyDB.Tran(func() error {
		updata["autotaskstatus"] = status
		csql = c.NewCiySQL("zc_autotask")
		csql.Where("id", id)
		_, err = c.CiyDB.Update(csql, updata)
		if err != nil {
			return fmt.Errorf("更新失败:%v", err)
		}
		admin.SaveLogDB(c.CiyDB, "zc_autotask", row, updata)
		updata["id"] = id
		return nil
	})
	if err != nil {
		return c.ErrJSON(w, "事务"+err.Error())
	}
	ret := map[string]any{}
	ret["data"] = updata
	return c.SuccJSON(w, r, ret)
}
