package controllers

import (
	"encoding/json"
	"eta/eta_mini_crm_ht/models"
	"eta/eta_mini_crm_ht/models/request"
	"eta/eta_mini_crm_ht/models/response"
	"eta/eta_mini_crm_ht/services"
	"eta/eta_mini_crm_ht/utils"
	"github.com/rdlucklib/rdluck_tools/paging"
	"time"

	"github.com/beego/beego/v2/client/orm"
)

type SysRoleController struct {
	BaseAuthController
}

// List
// @Title 系统角色列表
// @Description 系统角色列表
// @Param	request	body UserLoginReq true "type json string"
// @Success 200 {object} response.SysRoleListResp
// @router /list [get]
func (this *SysRoleController) List() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()

	pageSize, _ := this.GetInt("PageSize")
	currentIndex, _ := this.GetInt("CurrentIndex")

	var startSize int
	if pageSize <= 0 {
		pageSize = utils.PageSize20
	}
	if currentIndex <= 0 {
		currentIndex = 1
	}
	startSize = utils.StartIndex(currentIndex, pageSize)

	total, err := models.GetSysRoleListCount()
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}
	list, err := models.GetSysRoleList(startSize, pageSize)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}
	page := paging.GetPaging(currentIndex, pageSize, total)
	resp := new(response.SysRoleListResp)
	resp.List = list
	resp.Paging = page
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// AllList
// @Title 系统所有角色列表
// @Description 系统所有角色列表
// @Success 200 {object} response.SysRoleListResp
// @router /allList [get]
func (this *SysRoleController) AllList() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()

	list, err := models.GetSysRoleListNoPage()
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}
	resp := new(response.SysRoleListResp)
	resp.List = list
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// @Title 删除角色
// @Description 删除角色接口
// @Param	request	body system.SysRoleDeleteReq true "type json string"
// @Success 200 删除成功
// @router /delete [post]
func (this *SysRoleController) Delete() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	var req request.SysRoleDeleteReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	if req.SysRoleId <= 0 {
		br.Msg = "参数错误"
		br.ErrMsg = "参数错误,GroupId 小于等于0 "
		return
	}

	role, err := models.GetSysRoleById(req.SysRoleId)
	if err != nil {
		if err.Error() == utils.ErrNoRow() {
			br.Msg = "角色不存在, 请刷新页面"
			return
		}
		br.Msg = "删除失败"
		br.ErrMsg = "获取角色信息失败, Err: " + err.Error()
		return
	}
	if role.SysRoleName == "admin" {
		br.Msg = "admin角色不可删除"
		return
	}
	count, err := models.GetSysUserCountByRoleId(req.SysRoleId)
	if err != nil {
		br.Msg = "删除失败"
		br.ErrMsg = "获取用户数量失败，Err: " + err.Error()
		return
	}
	if count > 0 {
		br.Msg = "角色绑定用户，不可删除"
		return
	}
	err = models.DeleteSysRoleById(req.SysRoleId)
	if err != nil {
		br.Msg = "删除失败"
		br.Msg = "删除角色失败，系统错误，Err: " + err.Error()
		return
	}

	br.Msg = "删除成功"
	br.Ret = 200
	br.Success = true
}

// @Title 新增角色
// @Description 新增角色接口
// @Param	request	body request.SysRoleAddReq true "type json string"
// @Success 200 新增成功
// @router /add [post]
func (this *SysRoleController) Add() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	var req request.SysRoleAddReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}

	if req.SysRoleName == "" {
		br.Msg = "角色名称不能为空"
		return
	}
	count, err := models.GetSysRoleCountByRoleName(req.SysRoleName)
	if err != nil {
		br.Msg = "新增角色失败"
		br.ErrMsg = "新增角色失败，系统异常，Err:" + err.Error()
		return
	}
	if count > 0 {
		br.Msg = "角色已存在，请重新输入"
		return
	}
	sysRole := &models.SysRole{}
	sysRole.SysRoleName = req.SysRoleName
	sysRole.CreateTime = time.Now()
	sysRole.ModifyTime = time.Now()
	err = sysRole.Add()
	if err != nil {
		br.Msg = "新增角色失败"
		br.ErrMsg = "新增角色失败，系统异常，Err:" + err.Error()
		return
	}

	br.Ret = 200
	br.Msg = "新增角色成功"
	br.Success = true
}

// @Title 新增角色
// @Description 新增角色接口
// @Param	request	body request.SysRoleAddReq true "type json string"
// @Success 200 新增成功
// @router /edit [post]
func (this *SysRoleController) Edit() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()

	var req request.SysRoleEditReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	if req.SysRoleId <= 0 {
		br.Msg = "参数错误"
		br.ErrMsg = "参数错误,GroupId 小于等于0 "
		return
	}
	if req.SysRoleName == "" {
		br.Msg = "分组名称不能为空"
		return
	}

	sysRole, err := models.GetSysRoleById(req.SysRoleId)
	if err != nil {
		if err.Error() == utils.ErrNoRow() {
			br.Msg = "角色不存在，请刷新页面"
			return
		}
		br.Msg = "操作失败"
		br.ErrMsg = "获取角色失败, Err:" + err.Error()
		return
	}
	if sysRole.SysRoleName == "admin" {
		br.Msg = "admin角色不可编辑"
		return
	}
	oldSysRole, err := models.GetSysRoleByRoleName(req.SysRoleName)
	if err != nil && err != orm.ErrNoRows {
		br.Msg = "操作失败"
		br.ErrMsg = "获取角色失败, Err:" + err.Error()
		return
	}
	if oldSysRole != nil && oldSysRole.SysRoleId != req.SysRoleId {
		br.Msg = "名称已存在，请重新输入"
		return
	}
	err = models.UpdateSysUserRoleByRoleId(req.SysRoleId, req.SysRoleName)
	if err != nil {
		br.Msg = "编辑失败"
		br.ErrMsg = "编辑角色失败，Err:" + err.Error()
		return
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "编辑成功"
}

// ButtonList
// @Title 角色-按钮权限列表
// @Description 角色-按钮权限列表
// @Param   RoleId   query   int  true       "角色Id"
// @Success 200 {object} system.SysRoleListResp
// @router /menu/buttons [get]
func (this *SysRoleController) ButtonList() {
	br := new(models.BaseResponse).Init()
	defer func() {
		if br.ErrMsg == "" {
			br.IsSendEmail = false
		}
		this.Data["json"] = br
		this.ServeJSON()
	}()
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		br.Ret = 408
		return
	}

	roleId := sysUser.SysRoleId
	list, e := models.GetMenuButtonsByRoleId(roleId)
	if e != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取角色按钮权限失败, Err: " + e.Error()
		return
	}

	buttonList := make([]*response.SysMenuButtonResp, 0)
	for _, v := range list {
		// 把菜单过滤
		if v.MenuType == 1 {
			continue
		}
		tmp := new(response.SysMenuButtonResp)
		tmp.SysMenuId = v.SysMenuId
		tmp.ParentId = v.ParentId
		tmp.Name = v.Name
		tmp.MenuType = v.MenuType
		tmp.ButtonCode = v.ButtonCode
		buttonList = append(buttonList, tmp)
	}

	br.Data = buttonList
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
}

// @Title 获取用户权限菜单
// @Description 获取用户权限菜单接口
// @Success 200 {object} system.MenuListResp
// @router /menu/list [get]
func (this *SysRoleController) SysMenuList() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		return
	}
	roleId := sysUser.SysRoleId
	if roleId <= 0 {
		br.Msg = "参数错误"
		return
	}
	list, err := models.GetMenuListByRoleIds(roleId)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}
	// items := make([]*models.SysMenuItem, 0)
	// for _, v := range list {
	// 	t := &models.SysMenuItem{
	// 		SysMenuId:  v.SysMenuId,
	// 		ParentId:   v.ParentId,
	// 		Name:       v.Name,
	// 		Level:      v.Level,
	// 		Sort:       v.Sort,
	// 		Path:       v.Path,
	// 		IconPath:   v.IconPath,
	// 		ButtonCode: v.ButtonCode,
	// 		Children:   make([]*models.SysMenuItem, 0),
	// 	}
	// 	items = append(items, t)
	// }
	// 递归返回树形结构
	list = services.GetMenuTreeRecursive(list, 0)

	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = list
}

// SysRoleMenuAuthSave
// @Title 角色设置权限-保存
// @Description 角色设置权限-保存
// @Param	request	body RoleMenusSaveReq true "type json string"
// @Success 200 {object} system.SysRoleListResp
// @router /menu/auth_save [post]
func (this *SysRoleController) SysRoleMenuAuthSave() {
	br := new(models.BaseResponse).Init()
	defer func() {
		if br.ErrMsg == "" {
			br.IsSendEmail = false
		}
		this.Data["json"] = br
		this.ServeJSON()
	}()

	var req request.RoleMenusSaveReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	if req.SysRoleId <= 0 {
		br.Msg = "参数有误"
		return
	}
	if len(req.SysMenuIds) == 0 {
		br.Msg = "请选择菜单"
		return
	}
	sysRole, err := models.GetSysRoleById(req.SysRoleId)
	if err == nil {
		if sysRole.SysRoleName == "admin" {
			br.Msg = "不允许修改admin权限"
			return
		}
	}

	halfMap := make(map[int]struct{})
	for _, v := range req.HalfMenuIds {
		halfMap[v] = struct{}{}
	}

	items := make([]*models.SysRoleMenuMapping, 0)
	for _, v := range req.SysMenuIds {
		if _, ok := halfMap[v]; ok {
			continue
		}
		t := new(models.SysRoleMenuMapping)
		t.SysMenuId = v
		t.SysRoleId = req.SysRoleId
		items = append(items, t)
	}
	for _, v := range req.HalfMenuIds {
		t := new(models.SysRoleMenuMapping)
		t.SysMenuId = v
		t.Type = 1
		t.SysRoleId = req.SysRoleId
		items = append(items, t)
	}
	if e := models.CreateMultiSysRoleMenu(req.SysRoleId, items); e != nil {
		br.Msg = "保存失败"
		br.ErrMsg = "保存角色菜单权限失败, Err: " + e.Error()
		return
	}

	br.Ret = 200
	br.Success = true
	br.Msg = "设置成功"
}

// SysRoleMenuAuthList
// @Title 角色设置权限-菜单列表
// @Description 角色设置权限-菜单列表
// @Param   RoleId   query   int  true       "角色Id"
// @Success 200 {object} system.SysRoleListResp
// @router /menu/auth_list [get]
func (this *SysRoleController) SysRoleMenuAuthList() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	resp := new(response.SysMenuListResp)
	resp.ChoiceList = make([]int, 0)
	resp.HalfChoiceList = make([]int, 0)
	resp.List = make([]*models.SysMenuItem, 0)

	// 角色勾选的权限
	roleId, _ := this.GetInt("SysRoleId", 0)
	if roleId > 0 {
		relates, e := models.GetSysRoleMenuByRoleId(roleId)
		if e != nil {
			br.Msg = "获取失败"
			br.ErrMsg = "获取角色关联菜单失败, Err: " + e.Error()
			return
		}
		for _, r := range relates {
			if r.Type == 1 {
				resp.HalfChoiceList = append(resp.HalfChoiceList, r.SysMenuId)
				continue
			}
			resp.ChoiceList = append(resp.ChoiceList, r.SysMenuId)
		}
	}

	order := `sort ASC, create_time DESC, sys_menu_id DESC`
	list, e := models.GetSysMenuItemsByCondition(``, make([]interface{}, 0), []string{}, order)
	if e != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取菜单列表失败, Err: " + e.Error()
		return
	}

	items := make([]*models.SysMenuItem, 0)
	for _, v := range list {
		t := &models.SysMenuItem{
			SysMenuId:  v.SysMenuId,
			ParentId:   v.ParentId,
			Name:       v.Name,
			Level:      v.Level,
			Sort:       v.Sort,
			Path:       v.Path,
			IconPath:   v.IconPath,
			ButtonCode: v.ButtonCode,
			Children:   make([]*models.SysMenuItem, 0),
		}
		items = append(items, t)
	}

	// 递归返回树形结构
	items = services.GetMenuTreeRecursive(items, 0)

	resp.List = items
	br.Data = resp
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
}
