package system

import (
	"spaceofcheng/services/controllers"
	"spaceofcheng/services/models/model"
	"spaceofcheng/services/service/system"
)

// RoleController 用户
type RoleController struct {
	dao *system.RoleServ
	controllers.BaseController
}

// Constructor 初始化 Controller
// @Title Constructor
// @Description 初始化 Controller, 系统自动调用
func (c *RoleController) Constructor() {
	c.dao = system.NewRoleServ(c.Context)
}

// GetRoleList 获取角色列表
func (c *RoleController) GetRoleList() {
	cases := c.Context.Get("cases").([]model.SysUserCase)
	caseIDs := c.GetCaseIDs(cases)
	page, _ := c.GetInt("page")
	pageSize, _ := c.GetInt("pagesize")
	name := c.GetString("name")
	caseid := c.GetString("caseid")

	list, err := c.dao.GetRoleList(caseIDs, name, caseid, page, pageSize)
	if err != nil {
		c.ResponseError(err)
	}
	c.ResponseJSON(list)
}

// GetRoleByID 根据ID获取角色信息
func (c *RoleController) GetRoleByID() {
	roleid := c.GetString(":roleid")
	info, err := c.dao.GetRoleByID(roleid)
	if err != nil {
		c.ResponseError(err)
	}
	c.ResponseJSON(info)
}

// GetRoleMenuByRole 获取角色菜单
func (c *RoleController) GetRoleMenuByRole() {
	roleid := c.GetString(":roleid")
	menus, err := c.dao.GetRoleMeneByID(roleid)
	if err != nil {
		c.ResponseError(err)
	}
	c.ResponseJSON(menus)
}

// SaveCaseRole 保存角色
func (c *RoleController) SaveCaseRole() {
	role := model.SysRole{}
	if err := c.ParseForm(&role); err != nil {
		c.ResponseError(err)
	}
	newRole, err := c.dao.SaveRole(role)
	if err != nil {
		c.ResponseError(err)
	}
	c.ResponseJSON(newRole)
}

// SaveRoleMenus 保存角色对应菜单
func (c *RoleController) SaveRoleMenus() {
	roleid := c.GetString(":roleid")
	menuids := c.GetString("menuids")
	err := c.dao.SaveRoleMenu(roleid, menuids)
	if err != nil {
		c.ResponseError(err)
	}
	c.ResponseJSON("保存成功！")
}

// DelCaseRole 删除角色
func (c *RoleController) DelCaseRole() {
	roleid := c.GetString(":roleid")
	err := c.dao.DelRole(roleid)
	if err != nil {
		c.ResponseError(err)
	}
	c.ResponseJSON("删除成功！")
}
