package rigger

import (
	"math/rand"
	"net/http"

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

func autotskrun_setwhere(post *c.CiyPost) (map[string]any, *c.CiySQL) {
	query := post.Getobj("query")
	csql := c.NewCiySQL("zc_autotsk_run")
	csql.Where("autotaskid", c.Getstr(query, "_autotaskid"))
	csql.Where_daterange("addtimes", c.Getstr(query, "addtimes"))
	csql.Where_numrange("runsec", c.Getstr(query, "runsec_1"), c.Getstr(query, "runsec_2"), 1)
	csql.Where_numrange("logcnt", c.Getstr(query, "logcnt_1"), c.Getstr(query, "logcnt_2"), 1)
	csql.Where("msg like", c.Getstr(query, "msg"))
	order := c.Getstr(query, "order", "id desc")
	csql.Order(order)
	query["order"] = order
	return query, csql
}
func Autotskrun_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 := autotskrun_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)
	}
	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)
		field["msg"]["thwidth"] = "20em"
		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": "addtimes",
			"type": "daterange",
			"name": "执行时间",
		})
		input = append(input, map[string]any{
			"form": "runsec",
			"type": "num",
			"name": "时长",
			"prop": ` style="width:4em;"`,
		})
		input = append(input, map[string]any{
			"form": "logcnt",
			"type": "num",
			"name": "LOG统计",
			"prop": ` style="width:4em;"`,
		})
		input = append(input, map[string]any{
			"form": "msg",
			"type": "input",
			"name": "任务简报",
			"prop": ` style="width:8em;"`,
		})
		once["input"] = input
		csql = c.NewCiySQL("zc_autotask")
		csql.Column("id,name")
		ret["zc_autotask"], _, _ = c.CiyDB.Get(csql)
		ret["once"] = once
	}
	return c.SuccJSON(w, r, ret)
}
func Autotskrun_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, "p602l") {
		return c.ErrJSON(w, "您未被授权操作")
	}
	ids := post.Get("ids")
	if ids == "" {
		return c.ErrJSON(w, "请选择至少一条")
	}
	csql := c.NewCiySQL("zc_autotsk_run")
	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.Delall(c.CiyDB, delid, "zc_autotsk_log", "runtaskid", "Log记录")
			c.Delme(c.CiyDB, delid, "zc_autotsk_run")
			admin.SaveLogDB(c.CiyDB, "zc_autotsk_run", 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 Autotskrun_exportxls(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, "p602l") {
		return c.ErrJSON(w, "您未被授权操作")
	}
	_, csql := autotskrun_setwhere(post)
	rows, _, err := c.CiyDB.Get(csql)
	if err != nil {
		return c.ErrJSON(w, "读取错误", err)
	}
	if len(rows) > 10000 {
		return c.ErrJSON(w, "将导出"+c.Tostr(len(rows))+"条，不建议超过1万条，请筛选缩小范围", err)
	}
	fields := []map[string]string{}
	fields = append(fields, map[string]string{"style": "c", "width": "60", "field": "id", "name": "行码"})
	fields = append(fields, map[string]string{"style": "l", "width": "100", "field": "autotaskid", "name": "所属任务"})
	fields = append(fields, map[string]string{"style": "l", "width": "100", "field": "addtimes", "name": "执行时间"})
	fields = append(fields, map[string]string{"style": "r", "width": "60", "field": "runsec", "name": "时长"})
	fields = append(fields, map[string]string{"style": "r", "width": "60", "field": "logcnt", "name": "LOG统计"})
	fields = append(fields, map[string]string{"style": "l", "width": "500", "field": "msg", "name": "任务简报"})

	csql = c.NewCiySQL("zc_autotask")
	csql.Column("id,name")
	code_autotaskid, _, err2 := c.CiyDB.Get(csql)
	if err2 != nil {
		return c.ErrJSON(w, "读取zc_autotask错误", err2)
	}

	datas := [][]string{}
	for _, row := range rows {
		dat := make([]string, 0)
		for _, f := range fields {
			field := f["field"]
			if val, ok := row[field]; ok {
				var str string
				if field == "id" {
					str = c.EnID(c.Toint(val))
				} else if field == "autotaskid" {
					str = c.Ccode(code_autotaskid, c.Toint(val))
				} else if field == "addtimes" {
					t := c.Toint(val)
					if t <= 0 {
						str = "--"
					} else {
						str = c.Todate(t, "Y-m-d H:i")
					}
				} else {
					str = c.Tostr(val)
				}
				dat = append(dat, str)
			} else {
				dat = append(dat, "")
			}
		}
		datas = append(datas, dat)
	}
	param := map[string]any{}
	param["sheetname"] = "数据报表"
	param["titleheight"] = "25" //列头高度
	param["landscape"] = true   //横向打印
	param["fixtopage"] = true   //打印整个工作表
	param["toptitle"] = "任务执行记录数据报表"
	total := []map[string]any{} //单行统计数据
	// total = append(total, map[string]any{"style": "l", "name": "合计", "merge": 5})
	// total = append(total, map[string]any{"style": "r", "name": "=SUM(R[-" + c.Tostr(len(datas)) + "]C:R[-1]C)"})
	// total = append(total, map[string]any{"style": "r", "name": "=MAX(R[-" + c.Tostr(len(datas)) + "]C:R[-1]C)"})
	// param["rowstop"] = `<Row ss:Height="45"><Cell ss:MergeAcross="7" ss:StyleID="cap"><Data ss:Type="String">众产Ciyon</Data></Cell></Row>`
	// param["rowsfooter"] = `<Row><Cell ss:MergeAcross="2"><Data ss:Type="String" ss:StyleID="r">总计</Data></Cell><Cell ss:Formula="=SUM(R[-2]C:R[-1]C)"><Data ss:Type="Number"></Data></Cell></Row>`
	str := c.General_excel_xml(fields, datas, param, total)
	filename := "/ud/tmp/" + c.Todate(-1, "Ymd_His") + c.Tostr(rand.Intn(8999)+1000) + ".xls"
	err = c.FileSave(c.CiyWebDir+filename, str)
	if err != nil {
		return c.ErrJSON(w, "导出保存文件错误:%v[%v]", err, filename)
	}
	ret := map[string]any{}
	ret["url"] = filename
	return c.SuccJSON(w, r, ret)
}
func Autotskrun_viewlog(w http.ResponseWriter, r *http.Request) bool {
	post := c.NewCiyPost(w, r)
	_, userid := admin.Verifyfast(r, c.CiyDB, post)
	if userid == 0 {
		return false
	}
	runtaskid := post.Getint("runtaskid")
	csql := c.NewCiySQL("zc_autotsk_log")
	csql.Where("runtaskid", runtaskid)
	csql.Column("addtimes,msg")
	csql.Order("id")
	rows, _, err := c.CiyDB.Get(csql)
	if err != nil {
		return c.ErrJSON(w, "读取数据错误", err)
	}
	ret := map[string]any{}
	ret["logs"] = rows
	return c.SuccJSON(w, r, ret)
}
