package rigger

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

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

func statsfunc_setwhere(post *c.CiyPost) (map[string]any, *c.CiySQL) {
	query := post.Getobj("query")
	csql := c.NewCiySQL("zc_stats")
	csql.Where_daterange("addtimes", c.Getstr(query, "addtimes"))
	csql.Where_numrange("func_succ", c.Getstr(query, "func_succ_1"), c.Getstr(query, "func_succ_2"), 1)
	csql.Where_numrange("func_fail", c.Getstr(query, "func_fail_1"), c.Getstr(query, "func_fail_2"), 1)
	csql.Where_numrange("func_rollback", c.Getstr(query, "func_rollback_1"), c.Getstr(query, "func_rollback_2"), 1)
	csql.Where_numrange("func_runms", c.Getstr(query, "func_runms_1"), c.Getstr(query, "func_runms_2"), 1)
	order := c.Getstr(query, "order", "id desc")
	csql.Order(order)
	query["order"] = order
	return query, csql
}
func Statsfunc_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 := statsfunc_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)
		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": "func_succ",
			"type": "num",
			"name": "成功数",
			"prop": ` style="width:4em;"`,
		})
		input = append(input, map[string]any{
			"form": "func_fail",
			"type": "num",
			"name": "失败数",
			"prop": ` style="width:4em;"`,
		})
		input = append(input, map[string]any{
			"form": "func_rollback",
			"type": "num",
			"name": "回滚数",
			"prop": ` style="width:4em;"`,
		})
		input = append(input, map[string]any{
			"form": "func_runms",
			"type": "num",
			"name": "平均用时",
			"prop": ` style="width:4em;"`,
		})
		once["input"] = input
		ret["once"] = once
	}
	return c.SuccJSON(w, r, ret)
}
func Statsfunc_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, "p550d") {
		return c.ErrJSON(w, "您未被授权操作")
	}
	ids := post.Get("ids")
	if ids == "" {
		return c.ErrJSON(w, "请选择至少一条")
	}
	csql := c.NewCiySQL("zc_stats")
	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_stats")
			admin.SaveLogDB(c.CiyDB, "zc_stats", 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 Statsfunc_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, "p550e") {
		return c.ErrJSON(w, "您未被授权操作")
	}
	_, csql := statsfunc_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": "c", "width": "100", "field": "addtimes", "name": "记录时间"})
	fields = append(fields, map[string]string{"style": "r", "width": "100", "field": "func_succ", "name": "成功数"})
	fields = append(fields, map[string]string{"style": "r", "width": "100", "field": "func_fail", "name": "失败数"})
	fields = append(fields, map[string]string{"style": "r", "width": "100", "field": "func_commit", "name": "提交数"})
	fields = append(fields, map[string]string{"style": "r", "width": "100", "field": "func_rollback", "name": "回滚数"})
	fields = append(fields, map[string]string{"style": "r", "width": "100", "field": "func_runms", "name": "平均用时"})
	fields = append(fields, map[string]string{"style": "r", "width": "100", "field": "disk_sysfree", "name": "磁盘系统剩余空间"})
	fields = append(fields, map[string]string{"style": "r", "width": "100", "field": "disk_datafree", "name": "磁盘数据剩余空间"})
	fields = append(fields, map[string]string{"style": "r", "width": "100", "field": "disk_ioms", "name": "磁盘IO响应"})
	fields = append(fields, map[string]string{"style": "r", "width": "100", "field": "cpu_free", "name": "CPU空闲占比"})
	fields = append(fields, map[string]string{"style": "r", "width": "100", "field": "cpu_db", "name": "CPU数据库占比"})
	fields = append(fields, map[string]string{"style": "r", "width": "100", "field": "cpu_web", "name": "CPU应用占比"})
	fields = append(fields, map[string]string{"style": "r", "width": "100", "field": "cpu_oth", "name": "CPU其他占比"})
	fields = append(fields, map[string]string{"style": "r", "width": "100", "field": "mem_free", "name": "空闲内存"})
	fields = append(fields, map[string]string{"style": "r", "width": "100", "field": "mem_db", "name": "数据库内存占比"})
	fields = append(fields, map[string]string{"style": "r", "width": "100", "field": "mem_web", "name": "应用内存占比"})
	fields = append(fields, map[string]string{"style": "r", "width": "100", "field": "mem_oth", "name": "其他内存占比"})
	fields = append(fields, map[string]string{"style": "r", "width": "100", "field": "net_tcp", "name": "网络连接数"})
	fields = append(fields, map[string]string{"style": "r", "width": "100", "field": "net_ioms", "name": "网络响应"})
	fields = append(fields, map[string]string{"style": "r", "width": "100", "field": "db_query", "name": "数据库查询数"})
	fields = append(fields, map[string]string{"style": "r", "width": "100", "field": "db_commit", "name": "数据库提交数"})
	fields = append(fields, map[string]string{"style": "r", "width": "100", "field": "db_rollback", "name": "数据库回滚数"})
	fields = append(fields, map[string]string{"style": "r", "width": "100", "field": "db_keyhit", "name": "索引命中率"})
	fields = append(fields, map[string]string{"style": "r", "width": "100", "field": "db_dbhit", "name": "缓存命中率"})
	fields = append(fields, map[string]string{"style": "r", "width": "100", "field": "db_tmptable", "name": "临时表占比"})
	fields = append(fields, map[string]string{"style": "r", "width": "100", "field": "db_lock", "name": "当前锁数量"})
	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 == "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)
}
