package rigger

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

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

func Role_u_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
	}
	id := post.Getint("id")
	var err error
	ret := map[string]any{}
	csql := c.NewCiySQL("zc_role")
	csql.Where("id", id)
	ret["data"], err = c.CiyDB.Getone(csql)
	if err != nil {
		return c.ErrJSON(w, "读取role失败:"+err.Error())
	}
	csql = c.NewCiySQL("zc_menu")
	csql.Where("isuse", 1).Order("csort desc,id")
	ret["pcmenu"], _, err = c.CiyDB.Get(csql)
	if err != nil {
		return c.ErrJSON(w, "读取menu失败:"+err.Error())
	}
	csql = c.NewCiySQL("zc_power")
	csql.Order("csort desc,id")
	ret["powers"], _, err = c.CiyDB.Get(csql)
	if err != nil {
		return c.ErrJSON(w, "读取power失败:"+err.Error())
	}
	return c.SuccJSON(w, r, ret)
}
func Role_u_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, "p502u") {
		return c.ErrJSON(w, "您未被授权操作")
	}
	id := post.Getint("id")
	name := post.Get("name")
	if name == "" {
		return c.ErrJSON(w, "请填写角色名称")
	}
	memo := post.Get("memo")
	pman := post.Get("pman")
	pmans := strings.Split(pman, ",")
	powers := []string{}
	for _, pmain := range pmans {
		if pmain == "" {
			continue
		}
		power := post.Get("power_" + pmain)
		if power == "" {
			continue
		}
		powerno := post.Get("power_" + pmain + "_no")
		if powerno == "" {
			powers = append(powers, pmain)
		} else {
			ps := strings.Split(power, ",")
			for _, p := range ps {
				if p == "" {
					continue
				}
				powers = append(powers, p)
			}
		}
	}
	power := "." + strings.Join(powers, ".") + "."
	var err error
	var datarow map[string]any
	if id > 0 {
		csql := c.NewCiySQL("zc_role")
		csql.Where("id", id)
		datarow, err = c.CiyDB.Getone(csql)
		if datarow == nil {
			return c.ErrJSON(w, "数据不存在", err)
		}
	}

	err = c.CiyDB.Tran(func() error {
		updata := map[string]any{}
		updata["name"] = name
		updata["power"] = power
		updata["memo"] = memo
		updata["uptimes"] = c.Tostamp()
		csql := c.NewCiySQL("zc_role")
		if id > 0 {
			csql.Where("id", id)
			_, err = c.CiyDB.Update(csql, updata)
			if datarow["power"] != power {
				c.CiyDB.Execute("update zc_admin set power=? where roleid=?", power, id)
				c.CiyDB.Execute("update zc_online set usrchg=2 where user in (select id from zc_admin where roleid=?)", id)
			}
		} else {
			id, err = c.CiyDB.Insert(csql, updata)
			updata["id"] = id
		}
		if err != nil {
			return fmt.Errorf("更新失败:%v", err)
		}
		admin.SaveLogDB(c.CiyDB, "zc_role", datarow, updata)
		return nil
	})
	if err != nil {
		return c.ErrJSON(w, "事务"+err.Error())
	}
	return c.SuccJSON(w, r)
}
