package rigger

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

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

func Menu_init(w http.ResponseWriter, r *http.Request) bool {
	post := c.NewCiyPost(w, r)
	rsuser, _ := admin.Verifyfast(r, c.CiyDB, post)
	if rsuser == nil {
		return false
	}
	csql := c.NewCiySQL("zc_icon")
	csql.Where("icontarget", 10)
	csql.Column("targetid as id,icon")
	iconrows, _, err := c.CiyDB.Get(csql)
	if err != nil {
		return c.ErrJSON(w, "遇到读取错误", err)
	}
	icons := c.Mapid2data(iconrows)
	csql = c.NewCiySQL("zc_menu")
	csql.Order("csort desc,id")
	rows, _, err := c.CiyDB.Get(csql)
	if err != nil {
		return c.ErrJSON(w, "遇到menu读取错误", err)
	}
	for i, row := range rows {
		if v, ok := icons[c.Toint(row["id"])]; ok {
			rows[i]["icon"] = v["icon"]
		}
	}
	ret := map[string]any{}
	ret["list"] = rows
	if post.Getbool("field") {
		field, fshow := c.CiyDB.GetField(csql)
		c.FieldAdd(&field, &fshow, -1, "_btn", "操作")
		c.FieldAdd(&field, &fshow, 2, "demo", "原型")
		c.FieldAdd(&field, &fshow, 1, "icon", "|图标|")
		field["url"]["thwidth"] = "20em"
		field["csort"]["thwidth"] = "5em"
		ret["fshow"] = 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": "名称",
			"prop": ` style="width:8em;"`,
		})
		input = append(input, map[string]string{
			"form": "url",
			"type": "input",
			"name": "链接",
			"prop": ` style="width:12em;"`,
		})
		once["input"] = input
		ret["once"] = once
	}
	return c.SuccJSON(w, r, ret)
}
func Menu_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, "p980u") {
		return c.ErrJSON(w, "您未被授权操作")
	}
	id := post.Getint("id")
	name := post.Get("name")
	if name == "" {
		return c.ErrJSON(w, "请填写菜单名称")
	}
	upid := post.Getint("upid")
	csort := post.Getint("csort")
	isuse := post.Getint("isuse")
	csql := c.NewCiySQL("zc_menu")
	csql.Where("id", id)
	datarow, err := c.CiyDB.Getone(csql)
	if err != nil {
		return c.ErrJSON(w, "数据不存在", err)
	}
	demo := ""
	url := ""
	urldb := ""
	pow := ""
	csql = c.NewCiySQL("zc_menu")
	csql.Where("upid", id)
	downcnt := c.Toint(c.CiyDB.Get1(csql))
	if downcnt == 0 {
		url = post.Get("url", c.CIYPOST_ALLOW_ALL)
		urldb = url
		demo = post.Get("demo")
		if demo != "" {
			if demo[0] != ':' && demo[0] != 'a' && demo[0] != 'm' && demo[0] != 'c' {
				return c.ErrJSON(w, "原型前缀错误，支持[:acm]")
			}
			urldb += "~" + demo
		}
		pow = post.Get("pow")
	}
	err = c.CiyDB.Tran(func() error {
		updata := map[string]any{}
		updata["name"] = name
		updata["isuse"] = isuse
		updata["upid"] = upid
		updata["csort"] = csort
		updata["url"] = urldb
		updata["pow"] = pow
		csql = c.NewCiySQL("zc_menu")
		csql.Where("id", id)
		_, err = c.CiyDB.Update(csql, updata)
		if err != nil {
			return fmt.Errorf("更新失败:%v", err)
		}
		admin.SaveLogDB(c.CiyDB, "zc_menu", datarow, updata)
		return nil
	})
	if err != nil {
		return c.ErrJSON(w, "事务"+err.Error())
	}
	ret := map[string]any{}
	ret["url"] = url
	ret["demo"] = demo
	ret["pow"] = pow
	return c.SuccJSON(w, r, ret)
}
func Menu_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, "p980d") {
		return c.ErrJSON(w, "您未被授权操作")
	}
	ids := post.Get("ids")
	if ids == "" {
		return c.ErrJSON(w, "请选择至少一条")
	}
	csql := c.NewCiySQL("zc_menu")
	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"])
			if delid >= 10 {
				c.Delcheck(c.CiyDB, delid, "zc_menu", "upid", c.Tostr(row["name"]))
			}
			c.Delme(c.CiyDB, delid, "zc_menu")
			admin.SaveLogDB(c.CiyDB, "zc_menu", 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 Menu_modifyupid(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, "p980u") {
		return c.ErrJSON(w, "您未被授权操作")
	}
	id := post.Getint("id")
	newupid := post.Getint("newupid")

	csql := c.NewCiySQL("zc_menu")
	csql.Where("id", id)
	datarow, err := c.CiyDB.Getone(csql)
	if err != nil {
		return c.ErrJSON(w, "数据不存在", err)
	}

	err = c.CiyDB.Tran(func() error {
		updata := map[string]any{}
		updata["url"] = ""
		updata["pow"] = ""
		csql = c.NewCiySQL("zc_menu")
		csql.Where("id", newupid)
		_, err = c.CiyDB.Update(csql, updata)
		if err != nil {
			return fmt.Errorf("更新new失败:%v", err)
		}

		updata = map[string]any{}
		updata["upid"] = newupid
		csql = c.NewCiySQL("zc_menu")
		csql.Where("id", id)
		_, err = c.CiyDB.Update(csql, updata)
		if err != nil {
			return fmt.Errorf("更新id失败:%v", err)
		}
		admin.SaveLogDB(c.CiyDB, "zc_menu", datarow, updata)
		return nil
	})
	if err != nil {
		return c.ErrJSON(w, "事务"+err.Error())
	}
	return c.SuccJSON(w, r)
}
func Menu_multiadd(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, "p980u") {
		return c.ErrJSON(w, "您未被授权操作")
	}
	upid := post.Getint("upid")
	multi := strings.Split(post.Get("multi"), "\n")
	cnt := 0
	err := c.CiyDB.Tran(func() error {
		for _, m := range multi {
			if m == "" {
				continue
			}
			ms := strings.Split(m, "~")
			name := strings.TrimSpace(ms[0])
			url := ""
			pow := ""
			if len(ms) > 1 {
				url = strings.TrimSpace(ms[1])
			}
			if len(ms) > 2 {
				pow = strings.TrimSpace(ms[2])
			}
			updata := map[string]any{}
			updata["name"] = name
			updata["url"] = url
			updata["pow"] = pow
			updata["isuse"] = 1
			updata["upid"] = upid
			updata["csort"] = 10
			csql := c.NewCiySQL("zc_menu")
			_, err := c.CiyDB.Insert(csql, updata)
			if err != nil {
				return fmt.Errorf("新增失败:%v", err)
			}
			cnt++
			admin.SaveLogDB(c.CiyDB, "zc_menu", nil, updata)
		}
		return nil
	})
	if err != nil {
		return c.ErrJSON(w, "事务"+err.Error())
	}
	if cnt == 0 {
		return c.ErrJSON(w, "没有任何新增")
	}

	updata := map[string]any{}
	updata["url"] = ""
	updata["pow"] = ""
	csql := c.NewCiySQL("zc_menu")
	csql.Where("id", upid)
	_, err = c.CiyDB.Update(csql, updata)
	if err != nil {
		return c.ErrJSON(w, "更新upid失败:"+err.Error())
	}
	return c.SuccJSON(w, r)
}

func Menu_seticon(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, "p980u") {
		return c.ErrJSON(w, "您未被授权操作")
	}
	id := post.Getint("id")
	svg := post.Get("svg", c.CIYPOST_ALLOW_ALL)
	if svg != "" && !strings.HasPrefix(svg, "<svg ") {
		return c.ErrJSON(w, "svg格式错误")
	}
	csql := c.NewCiySQL("zc_icon")
	csql.Where("icontarget", 10)
	csql.Where("targetid", id)
	datarow, err := c.CiyDB.Getone(csql)
	if err != nil {
		return c.ErrJSON(w, "数据不存在", err)
	}
	if datarow == nil && svg == "" {
		return c.SuccJSON(w, r)
	}
	err = c.CiyDB.Tran(func() error {
		msg := ""
		if svg == "" {
			csql = c.NewCiySQL("zc_icon")
			csql.Where("id", datarow["id"])
			_, err = c.CiyDB.Delete(csql)
			msg = "删除图标"
		} else {
			msg = "更新图标"
			updata := map[string]any{}
			updata["icon"] = svg
			if datarow != nil {
				csql = c.NewCiySQL("zc_icon")
				csql.Where("id", datarow["id"])
				_, err = c.CiyDB.Update(csql, updata)
			} else {
				updata["icontarget"] = 10
				updata["targetid"] = id
				csql = c.NewCiySQL("zc_icon")
				_, err = c.CiyDB.Insert(csql, updata)
			}
		}
		if err != nil {
			return fmt.Errorf("操作失败:%v", err)
		}
		admin.SaveLog(c.CiyDB, "zc_menu", "Upd="+c.Tostr(id)+"_|@|_icon="+msg)
		return nil
	})
	if err != nil {
		return c.ErrJSON(w, "事务"+err.Error())
	}
	return c.SuccJSON(w, r)
}
