package sysrole

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

	"be.ems/features/sys_role/model"
	"be.ems/features/sys_role/service"
	userService "be.ems/features/sys_user/service"
	"be.ems/lib/core/utils/ctx"
	"be.ems/lib/core/utils/parse"
	"be.ems/lib/core/vo/result"
	"be.ems/lib/midware"
	"be.ems/lib/services"
	"be.ems/restagent/config"
)

// 角色接口添加到路由
func Routers() []services.RouterItem {
	// 实例化控制层 SysRoleApi 结构体
	var apis = &SysRoleApi{
		sysRoleService: service.NewServiceSysRole,
		sysUserService: userService.NewServiceSysUser,
	}

	rs := [...]services.RouterItem{
		{
			Method:     "GET",
			Pattern:    "/roles",
			Handler:    apis.List,
			Middleware: midware.Authorize(nil),
		},
		{
			Method:     "GET",
			Pattern:    "/role/{roleId}",
			Handler:    apis.Info,
			Middleware: midware.Authorize(nil),
		},
		{
			Method:     "POST",
			Pattern:    "/role",
			Handler:    apis.Add,
			Middleware: midware.Authorize(nil),
		},
		{
			Method:     "PUT",
			Pattern:    "/role",
			Handler:    apis.Edit,
			Middleware: midware.Authorize(nil),
		},
		{
			Method:     "DELETE",
			Pattern:    "/role/{roleIds}",
			Handler:    apis.Remove,
			Middleware: midware.Authorize(nil),
		},
		{
			Method:     "PUT",
			Pattern:    "/role/changeStatus",
			Handler:    apis.Status,
			Middleware: midware.Authorize(nil),
		},
		{
			Method:     "GET",
			Pattern:    "/role/authUser/allocatedList",
			Handler:    apis.AuthUserAllocatedList,
			Middleware: midware.Authorize(nil),
		},
		{
			Method:     "PUT",
			Pattern:    "/role/authUser/checked",
			Handler:    apis.AuthUserChecked,
			Middleware: midware.Authorize(nil),
		},
		// 添加更多的 Router 对象...
	}

	// 生成两组前缀路由
	rsPrefix := []services.RouterItem{}
	for _, v := range rs {
		path := "/roleManage/{apiVersion}" + v.Pattern
		// 固定前缀
		v.Pattern = config.DefaultUriPrefix + path
		rsPrefix = append(rsPrefix, v)
		// 可配置
		v.Pattern = config.UriPrefix + path
		rsPrefix = append(rsPrefix, v)
	}
	return rsPrefix
}

// // 实例化控制层 SysRoleApi 结构体
// var NewSysRole = &SysRoleApi{
// 	sysRoleService: sysrole.NewServiceSysRole,
// 	sysUserService: sysuser.NewServiceSysUser,
// }

// 角色信息
//
// PATH /roleManage
type SysRoleApi struct {
	// 角色服务
	sysRoleService *service.ServiceSysRole
	// 用户服务
	sysUserService *userService.ServiceSysUser
}

// 角色列表
//
// GET /list
func (s *SysRoleApi) List(w http.ResponseWriter, r *http.Request) {
	querys := ctx.QueryMap(r)
	data := s.sysRoleService.SelectRolePage(querys)
	ctx.JSON(w, 200, result.Ok(data))
}

// 角色信息详情
//
// GET /:roleId
func (s *SysRoleApi) Info(w http.ResponseWriter, r *http.Request) {
	roleId := ctx.Param(r, "roleId")
	if roleId == "" {
		ctx.JSON(w, 400, result.CodeMsg(400, "parameter error"))
		return
	}
	data := s.sysRoleService.SelectRoleById(roleId)
	if data.RoleID == roleId {
		ctx.JSON(w, 200, result.OkData(data))
		return
	}
	ctx.JSON(w, 200, result.Err(nil))
}

// 角色信息新增
//
// POST /
func (s *SysRoleApi) Add(w http.ResponseWriter, r *http.Request) {
	var body model.SysRole
	err := ctx.ShouldBindJSON(r, &body)
	if err != nil || body.RoleID != "" {
		ctx.JSON(w, 400, result.CodeMsg(400, "parameter error"))
		return
	}

	// 判断角色名称是否唯一
	uniqueRoleName := s.sysRoleService.CheckUniqueRoleName(body.RoleName, "")
	if !uniqueRoleName {
		msg := fmt.Sprintf("[%s] Role name already exists", body.RoleName)
		ctx.JSON(w, 200, result.ErrMsg(msg))
		return
	}

	// 判断角色键值是否唯一
	uniqueRoleKey := s.sysRoleService.CheckUniqueRoleKey(body.RoleKey, "")
	if !uniqueRoleKey {
		msg := fmt.Sprintf("[%s] The role key value already exists", body.RoleName)
		ctx.JSON(w, 200, result.ErrMsg(msg))
		return
	}

	body.CreateBy = ctx.LoginUserToUserName(r)
	insertId := s.sysRoleService.InsertRole(body)
	if insertId != "" {
		ctx.JSON(w, 200, result.Ok(nil))
		return
	}
	ctx.JSON(w, 200, result.Err(nil))
}

// 角色信息修改
//
// PUT /
func (s *SysRoleApi) Edit(w http.ResponseWriter, r *http.Request) {
	var body model.SysRole
	err := ctx.ShouldBindJSON(r, &body)
	if err != nil || body.RoleID == "" {
		ctx.JSON(w, 400, result.CodeMsg(400, "parameter error"))
		return
	}

	// 检查是否管理员角色
	if body.RoleID == "1" {
		ctx.JSON(w, 200, result.ErrMsg("Operation of administrator role is not allowed"))
		return
	}

	// 检查是否存在
	role := s.sysRoleService.SelectRoleById(body.RoleID)
	if role.RoleID != body.RoleID {
		ctx.JSON(w, 200, result.ErrMsg("No permission to access role data!"))
		return
	}

	// 判断角色名称是否唯一
	uniqueRoleName := s.sysRoleService.CheckUniqueRoleName(body.RoleName, body.RoleID)
	if !uniqueRoleName {
		msg := fmt.Sprintf("[%s] Role name already exists", body.RoleName)
		ctx.JSON(w, 200, result.ErrMsg(msg))
		return
	}

	// 判断角色键值是否唯一
	uniqueRoleKey := s.sysRoleService.CheckUniqueRoleKey(body.RoleKey, body.RoleID)
	if !uniqueRoleKey {
		msg := fmt.Sprintf("[%s] The role key value already exists", body.RoleName)
		ctx.JSON(w, 200, result.ErrMsg(msg))
		return
	}

	body.UpdateBy = ctx.LoginUserToUserName(r)
	rows := s.sysRoleService.UpdateRole(body)
	if rows > 0 {
		ctx.JSON(w, 200, result.Ok(nil))
		return
	}
	ctx.JSON(w, 200, result.Err(nil))
}

// 角色信息删除
//
// DELETE /:roleIds
func (s *SysRoleApi) Remove(w http.ResponseWriter, r *http.Request) {
	roleIds := ctx.Param(r, "roleIds")
	if roleIds == "" {
		ctx.JSON(w, 400, result.CodeMsg(400, "parameter error"))
		return
	}
	// 处理字符转id数组后去重
	ids := strings.Split(roleIds, ",")
	uniqueIDs := parse.RemoveDuplicates(ids)
	if len(uniqueIDs) <= 0 {
		ctx.JSON(w, 200, result.Err(nil))
		return
	}
	// 检查是否管理员角色
	for _, id := range uniqueIDs {
		if id == "1" {
			ctx.JSON(w, 200, result.ErrMsg("Operation of administrator role is not allowed"))
			return
		}
	}
	rows, err := s.sysRoleService.DeleteRoleByIds(uniqueIDs)
	if err != nil {
		ctx.JSON(w, 200, result.ErrMsg(err.Error()))
		return
	}
	msg := fmt.Sprintf("Successfully deleted: %d", rows)
	ctx.JSON(w, 200, result.OkMsg(msg))
}

// 角色状态变更
//
// PUT /changeStatus
func (s *SysRoleApi) Status(w http.ResponseWriter, r *http.Request) {
	var body struct {
		// 角色ID
		RoleID string `json:"roleId" binding:"required"`
		// 状态
		Status string `json:"status" binding:"required"`
	}
	err := ctx.ShouldBindJSON(r, &body)
	if err != nil {
		ctx.JSON(w, 400, result.CodeMsg(400, "parameter error"))
		return
	}

	// 检查是否管理员角色
	if body.RoleID == "1" {
		ctx.JSON(w, 200, result.ErrMsg("Operation of administrator role is not allowed"))
		return
	}

	// 检查是否存在
	role := s.sysRoleService.SelectRoleById(body.RoleID)
	if role.RoleID != body.RoleID {
		ctx.JSON(w, 200, result.ErrMsg("No permission to access role data!"))
		return
	}

	// 与旧值相等不变更
	if role.Status == body.Status {
		ctx.JSON(w, 200, result.ErrMsg("Change status equals old value!"))
		return
	}

	// 更新状态不刷新缓存
	userName := ctx.LoginUserToUserName(r)
	SysRoleApi := model.SysRole{
		RoleID:   body.RoleID,
		Status:   body.Status,
		UpdateBy: userName,
	}
	rows := s.sysRoleService.UpdateRole(SysRoleApi)
	if rows > 0 {
		ctx.JSON(w, 200, result.Ok(nil))
		return
	}
	ctx.JSON(w, 200, result.Err(nil))
}

// 角色分配用户列表
//
// GET /authUser/allocatedList
func (s *SysRoleApi) AuthUserAllocatedList(w http.ResponseWriter, r *http.Request) {
	querys := ctx.QueryMap(r)
	roleId, ok := querys["roleId"]
	if !ok || roleId == "" {
		ctx.JSON(w, 400, result.CodeMsg(400, "parameter error"))
		return
	}

	// 检查是否存在
	role := s.sysRoleService.SelectRoleById(roleId.(string))
	if role.RoleID != roleId {
		ctx.JSON(w, 200, result.ErrMsg("No permission to access role data!"))
		return
	}

	data := s.sysUserService.SelectAllocatedPage(querys)
	ctx.JSON(w, 200, result.Ok(data))
}

// 角色分配选择授权
//
// PUT /authUser/checked
func (s *SysRoleApi) AuthUserChecked(w http.ResponseWriter, r *http.Request) {
	var body struct {
		// 角色ID
		RoleID string `json:"roleId" binding:"required"`
		// 用户ID组
		UserIDs string `json:"userIds" binding:"required"`
		// 选择操作 添加true 取消false
		Checked bool `json:"checked"`
	}
	err := ctx.ShouldBindJSON(r, &body)
	if err != nil {
		ctx.JSON(w, 400, result.CodeMsg(400, "parameter error"))
		return
	}

	// 处理字符转id数组后去重
	ids := strings.Split(body.UserIDs, ",")
	uniqueIDs := parse.RemoveDuplicates(ids)
	if len(uniqueIDs) <= 0 {
		ctx.JSON(w, 200, result.Err(nil))
		return
	}

	// 检查是否存在
	role := s.sysRoleService.SelectRoleById(body.RoleID)
	if role.RoleID != body.RoleID {
		ctx.JSON(w, 200, result.ErrMsg("No permission to access role data!"))
		return
	}

	var rows int64
	if body.Checked {
		rows = s.sysRoleService.InsertAuthUsers(body.RoleID, uniqueIDs)
	} else {
		rows = s.sysRoleService.DeleteAuthUsers(body.RoleID, uniqueIDs)
	}
	if rows > 0 {
		ctx.JSON(w, 200, result.Ok(nil))
		return
	}
	ctx.JSON(w, 200, result.Err(nil))
}
