package sysuser

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

	sysRoleModel "nms_nbi/features/sys_role/model"
	sysRoleService "nms_nbi/features/sys_role/service"
	sysUserModel "nms_nbi/features/sys_user/model"
	"nms_nbi/features/sys_user/service"
	"nms_nbi/lib/core/utils/ctx"
	"nms_nbi/lib/core/utils/parse"
	"nms_nbi/lib/core/vo/result"
	"nms_nbi/lib/midware"
	"nms_nbi/lib/services"
	"nms_nbi/restagent/config"
	srcConfig "nms_nbi/src/framework/config"
)

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

	rs := [...]services.RouterItem{
		{
			Method:     "GET",
			Pattern:    "/users",
			Handler:    apis.List,
			Middleware: midware.Authorize(nil),
		},
		{
			Method:     "GET",
			Pattern:    "/user/{userId}",
			Handler:    apis.Info,
			Middleware: midware.Authorize(nil),
		},
		{
			Method:     "POST",
			Pattern:    "/user",
			Handler:    apis.Add,
			Middleware: midware.Authorize(nil),
		},
		{
			Method:     "PUT",
			Pattern:    "/user",
			Handler:    apis.Edit,
			Middleware: midware.Authorize(nil),
		},
		{
			Method:     "DELETE",
			Pattern:    "/user/{userIds}",
			Handler:    apis.Remove,
			Middleware: midware.Authorize(nil),
		},
		// 添加更多的 Router 对象...
	}

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

// // 实例化控制层 SysUserApi 结构体
// var NewSysUser = &SysUserApi{
// 	sysUserService:     service.NewSysUserImpl,
// 	sysRoleService:     service.NewSysRoleImpl,
// 	sysPostService:     service.NewSysPostImpl,
// 	sysDictDataService: service.NewSysDictDataImpl,
// }

// 用户信息
//
// PATH /system/user
type SysUserApi struct {
	// 用户服务
	sysUserService *service.ServiceSysUser
	// 角色服务
	sysRoleService *sysRoleService.ServiceSysRole
}

// 用户信息列表
//
// GET /list
func (s *SysUserApi) List(w http.ResponseWriter, r *http.Request) {
	querys := ctx.QueryMap(r)
	data := s.sysUserService.SelectUserPage(querys)
	ctx.JSON(w, 200, result.Ok(data))
}

// 用户信息详情
//
// GET /:userId
func (s *SysUserApi) Info(w http.ResponseWriter, r *http.Request) {
	userId := ctx.Param(r, "userId")
	if userId == "" {
		ctx.JSON(w, 400, result.CodeMsg(400, "parameter error"))
		return
	}
	// 查询系统角色列表
	roles := s.sysRoleService.SelectRoleList(sysRoleModel.SysRole{})

	// 不是系统指定管理员需要排除其角色
	if !srcConfig.IsAdmin(userId) {
		rolesFilter := make([]sysRoleModel.SysRole, 0)
		for _, r := range roles {
			if r.RoleID != "1" {
				rolesFilter = append(rolesFilter, r)
			}
		}
		roles = rolesFilter
	}

	// 新增用户时，用户ID为0
	if userId == "0" {
		ctx.JSON(w, 200, result.OkData(map[string]any{
			"user":    map[string]any{},
			"roleIds": []string{},
			"roles":   roles,
		}))
		return
	}

	// 检查用户是否存在
	user := s.sysUserService.SelectUserById(userId)
	if user.Id != userId {
		ctx.JSON(w, 200, result.ErrMsg("No permission to access user data!"))
		return
	}

	// 角色ID组
	roleIds := make([]string, 0)
	for _, r := range user.Roles {
		roleIds = append(roleIds, r.RoleID)
	}

	ctx.JSON(w, 200, result.OkData(map[string]any{
		"user":    user,
		"roleIds": roleIds,
		"roles":   roles,
	}))
}

// 用户信息新增
//
// POST /
func (s *SysUserApi) Add(w http.ResponseWriter, r *http.Request) {
	var body sysUserModel.SysUser
	err := ctx.ShouldBindJSON(r, &body)
	if err != nil || body.Id != "" {
		ctx.JSON(w, 400, result.CodeMsg(400, "parameter error"))
		return
	}

	// 检查用户登录账号是否唯一
	uniqueUserName := s.sysUserService.CheckUniqueUserName(body.AccountId, "")
	if !uniqueUserName {
		msg := fmt.Sprintf("[%s] Login account already exists", body.AccountId)
		ctx.JSON(w, 200, result.ErrMsg(msg))
		return
	}

	insertId := s.sysUserService.InsertUser(body)
	if insertId != "" {
		ctx.JSON(w, 200, result.Ok(nil))
		return
	}
	ctx.JSON(w, 200, result.Err(nil))
}

// 用户信息修改
//
// POST /
func (s *SysUserApi) Edit(w http.ResponseWriter, r *http.Request) {
	var body sysUserModel.SysUser
	err := ctx.ShouldBindJSON(r, &body)
	if err != nil || body.Id == "" {
		ctx.JSON(w, 400, result.CodeMsg(400, "parameter error"))
		return
	}

	// 检查是否管理员用户
	// if srcConfig.IsAdmin(body.Id) {
	// 	ctx.JSON(w, 200, result.ErrMsg("不允许操作管理员用户"))
	// 	return
	// }

	user := s.sysUserService.SelectUserById(body.Id)
	if user.Id != body.Id {
		ctx.JSON(w, 200, result.ErrMsg("No permission to access user data!"))
		return
	}

	// 检查用户登录账号是否唯一
	uniqueUserName := s.sysUserService.CheckUniqueUserName(body.AccountId, body.Id)
	if !uniqueUserName {
		msg := fmt.Sprintf("[%s] Login account already exists", body.AccountId)
		ctx.JSON(w, 200, result.ErrMsg(msg))
		return
	}

	body.AccountId = "" // 忽略修改登录用户名称
	// body.Password = "" // 忽略修改密码
	rows := s.sysUserService.UpdateUserAndRolePost(body)
	if rows > 0 {
		ctx.JSON(w, 200, result.Ok(nil))
		return
	}
	ctx.JSON(w, 200, result.Err(nil))
}

// 用户信息删除
//
// DELETE /:userIds
func (s *SysUserApi) Remove(w http.ResponseWriter, r *http.Request) {
	userIds := ctx.Param(r, "userIds")
	if userIds == "" {
		ctx.JSON(w, 400, result.CodeMsg(400, "parameter error"))
		return
	}
	// 处理字符转id数组后去重
	ids := strings.Split(userIds, ",")
	uniqueIDs := parse.RemoveDuplicates(ids)
	if len(uniqueIDs) <= 0 {
		ctx.JSON(w, 200, result.Err(nil))
		return
	}
	rows, err := s.sysUserService.DeleteUserByIds(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 /resetPwd
func (s *SysUserApi) ResetPwd(w http.ResponseWriter, r *http.Request) {
	var body struct {
		UserID   string `json:"userId" binding:"required"`
		Password string `json:"password" binding:"required"`
	}
	if err := ctx.ShouldBindJSON(r, &body); err != nil {
		ctx.JSON(w, 400, result.CodeMsg(400, "parameter error"))
		return
	}

	// 检查是否管理员用户
	if srcConfig.IsAdmin(body.UserID) {
		ctx.JSON(w, 200, result.ErrMsg("No permission to access user data!"))
		return
	}

	user := s.sysUserService.SelectUserById(body.UserID)
	if user.Id != body.UserID {
		ctx.JSON(w, 200, result.ErrMsg("No permission to access user data!"))
		return
	}

	SysUserApi := sysUserModel.SysUser{
		Id:       body.UserID,
		Password: body.Password,
	}
	rows := s.sysUserService.UpdateUser(SysUserApi)
	if rows > 0 {
		ctx.JSON(w, 200, result.Ok(nil))
		return
	}
	ctx.JSON(w, 200, result.Err(nil))
}

// 用户状态修改
//
// PUT /changeStatus
func (s *SysUserApi) Status(w http.ResponseWriter, r *http.Request) {
	var body struct {
		UserID string `json:"userId" binding:"required"`
		Status string `json:"status" binding:"required"`
	}
	if err := ctx.ShouldBindJSON(r, &body); err != nil {
		ctx.JSON(w, 400, result.CodeMsg(400, "parameter error"))
		return
	}

	// 检查是否存在
	user := s.sysUserService.SelectUserById(body.UserID)
	if user.Id != body.UserID {
		ctx.JSON(w, 200, result.ErrMsg("No permission to access user data!"))
		return
	}

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

	SysUserApi := sysUserModel.SysUser{
		Id:     body.UserID,
		Status: body.Status,
	}
	rows := s.sysUserService.UpdateUser(SysUserApi)
	if rows > 0 {
		ctx.JSON(w, 200, result.Ok(nil))
		return
	}
	ctx.JSON(w, 200, result.Err(nil))
}
