package rigger

import (
	"fmt"
	"net/http"
	"strings"

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

func Cata_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
	}
	cbid := post.Getint("cbid")
	ext := post.Get("ext")
	issub := (post.Get("issub") == "yes")
	ismulti := (post.Get("ismulti") == "yes")
	cname := ""
	code := ""
	if cbid == 0 {
		code = post.Get("code")
		csql := c.NewCiySQL("zc_cata")
		csql.Where("codeid", code)
		csql.Where("cbid=0")
		cbrow, _ := c.CiyDB.Getone(csql)
		if cbrow == nil {
			return c.ErrJSON(w, "代码库未找到code="+code)
		}
		cbid = c.Toint(cbrow["id"])
		cname = c.Tostr(cbrow["name"])
	} else {
		csql := c.NewCiySQL("zc_cata")
		csql.Where("id", cbid)
		csql.Where("cbid=0")
		cbrow, _ := c.CiyDB.Getone(csql)
		if cbrow == nil {
			return c.ErrJSON(w, "代码库未找到cbid="+c.Tostr(cbid))
		}
		cname = c.Tostr(cbrow["name"])
		code = c.Tostr(cbrow["codeid"])
	}
	csql := c.NewCiySQL("zc_cata")
	csql.Where("cbid", cbid)
	csql.Order("csort,id")
	rows, _, err := c.CiyDB.Get(csql)
	if err != nil {
		return c.ErrJSON(w, "读取错误", err)
	}
	rows = append(rows, map[string]any{
		"id":    0,
		"name":  "",
		"csort": 10,
		"isuse": 1,
	})
	ret := map[string]any{}
	ret["list"] = rows
	if post.Getbool("field") {
		field := map[string]map[string]any{}
		fshow := ""
		c.FieldAdd(&field, &fshow, -1, "name", cname)
		c.FieldAdd(&field, &fshow, -1, "codeid", "代码|")
		if ext != "" {
			c.FieldAdd(&field, &fshow, -1, "extdata", ext)
		}
		c.FieldAdd(&field, &fshow, -1, "isuse", "启用")
		c.FieldAdd(&field, &fshow, -1, "csort", "排序|")
		c.FieldAdd(&field, &fshow, -1, "clas", "样式")
		c.FieldAdd(&field, &fshow, -1, "_btn", "操作")

		field["clas"]["thwidth"] = "7em"
		field["codeid"]["thwidth"] = "6em"
		field["csort"]["thwidth"] = "5em"
		ret["fshow"] = strings.TrimLeft(fshow, ",")
		ret["field"] = field
	}
	if post.Getbool("once") {
		once := map[string]any{}
		input := make([]map[string]string, 0)
		input = append(input, map[string]string{
			"form": "name",
			"type": "input",
			"name": cname,
			"prop": ` style="width:8em;"`,
		})
		input = append(input, map[string]string{
			"form": "codeid",
			"type": "input",
			"name": "代码",
			"prop": ` style="width:8em;"`,
		})
		if ext != "" {
			input = append(input, map[string]string{
				"form": "extdata",
				"type": "input",
				"name": ext,
				"prop": ` style="width:8em;"`,
			})
		}
		once["input"] = input
		ret["cbid"] = cbid
		ret["issub"] = issub
		ret["ismulti"] = ismulti
		ret["codename"] = code
		ret["once"] = once
	}
	return c.SuccJSON(w, r, ret)
}
func Cata_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, "p601pd") {
		return c.ErrJSON(w, "您未被授权操作")
	}
	id := post.Getint("id")
	cbid := post.Getint("cbid")
	codeid := post.Get("codeid")
	name := post.Get("name")
	if name == "" {
		return c.ErrJSON(w, "请填写名称")
	}
	upid := post.Getint("upid")
	csort := post.Getint("csort")
	extdata := post.Get("extdata")
	isuse := post.Getint("isuse")
	clas := post.Get("clas")
	var err error
	var datarow map[string]any
	if id > 0 {
		csql := c.NewCiySQL("zc_cata")
		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_cata")
		csql.Where("cbid", cbid)
		csql.Where("codeid", codeid)
		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["codeid"] = codeid
		updata["cbid"] = cbid
		updata["upid"] = upid
		updata["isuse"] = isuse
		updata["csort"] = csort
		updata["clas"] = clas
		updata["extdata"] = extdata
		csql = c.NewCiySQL("zc_cata")
		if id > 0 {
			csql.Where("id", id)
			_, err = c.CiyDB.Update(csql, updata)
		} else {
			id, err = c.CiyDB.Insert(csql, updata)
		}
		updata["newid"] = id
		if err != nil {
			return fmt.Errorf("更新失败:%v", err)
		}
		admin.SaveLogDB(c.CiyDB, "zc_cata", datarow, updata)
		return nil
	})
	if err != nil {
		return c.ErrJSON(w, "事务"+err.Error())
	}
	c.CiyDB.Execute("update zc_online set usrchg=2")
	ret := map[string]any{}
	ret["data"] = updata
	return c.SuccJSON(w, r, ret)
}
func Cata_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, "p601pd") {
		return c.ErrJSON(w, "您未被授权操作")
	}
	ids := post.Get("ids")
	if ids == "" {
		return c.ErrJSON(w, "请选择至少一条")
	}
	cbid := post.Getint("cbid")
	var csql *c.CiySQL
	csql = c.NewCiySQL("zc_cata")
	csql.Where("cbid=0")
	csql.Where("id", cbid)
	cbrow, _ := c.CiyDB.Getone(csql)
	if cbrow == nil {
		return c.ErrJSON(w, "代码库未找到cbid="+c.Tostr(cbid))
	}
	exs := strings.Split(c.Tostr(cbrow["extdata"]), "\n")
	csql = c.NewCiySQL("zc_cata")
	csql.Where("id in", ids)
	rows, _, _ := c.CiyDB.Get(csql)
	vids := make([]int, 0)
	err := c.CiyDB.Tran(func() error {
		for _, row := range rows {
			delid := c.Toint(row["id"])
			csql = c.NewCiySQL("zc_cata")
			csql.Where("upid", delid)
			csql.Where("cbid", row["cbid"])
			downcnt := c.Toint(c.CiyDB.Get1(csql))
			if downcnt > 0 {
				return fmt.Errorf("[%v]有%v个子码，请先删除子码", row["name"], downcnt)
			}
			for _, exn := range exs {
				if exn == "" {
					continue
				}
				tabf := strings.Split(exn, ",")
				if len(tabf) == 1 {
					tabf = append(tabf, c.Tostr(cbrow["codeid"]))
				}
				c.Delcheck(c.CiyDB, c.Toint(row["codeid"]), tabf[0], tabf[1], tabf[0]+"数据")
			}
			c.Delme(c.CiyDB, delid, "zc_cata")
			admin.SaveLogDB(c.CiyDB, "zc_cata", row, nil)
			vids = append(vids, delid)
		}
		return nil
	})
	if err != nil {
		return c.ErrJSON(w, "事务"+err.Error())
	}
	c.CiyDB.Execute("update zc_online set usrchg=2")
	ret := map[string]any{}
	ret["ids"] = vids
	return c.SuccJSON(w, r, ret)
}
