package service

import (
	"context"
	"errors"
	"fmt"
	"strings"
	"sync"
	"time"

	"github.com/mhaya/game/game_cluster/internal/code"
	"github.com/mhaya/game/game_cluster/internal/mdb"
	"github.com/mhaya/game/game_cluster/internal/mdb/models"
	"github.com/mhaya/game/game_cluster/nodes/webadmin/common"
	"github.com/mhaya/game/game_cluster/nodes/webadmin/entity"
	"github.com/mhaya/game/game_cluster/nodes/webadmin/model"
	mhayaLogger "github.com/mhaya/logger"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/bson/primitive"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

type Role struct {
}

func NewRole() *Role {
	return &Role{}
}

// List 角色列表
func (r *Role) List(ctx context.Context, req entity.RoleListReq) (*entity.RoleResp, *code.Result) {
	roles := models.Roles{}
	rolesCollection := mdb.MDB.Collection(roles.TableName())
	// 构建过滤器
	filter := bson.M{}
	if req.Name != "" {
		filter["name"] = req.Name
	}
	if req.Status > 0 {
		filter["status"] = req.Status
	}
	// 数据验证
	page, pageSize := checkPageParam(req.Page, req.Size)

	// 设置分页选项
	findOptions := options.Find().SetSkip(int64((page - 1) * req.Size)).SetLimit(int64(pageSize))
	countDocuments, err := rolesCollection.CountDocuments(ctx, filter)
	if err != nil {
		mhayaLogger.Warnf("List CountDocuments error:%v", err)
		return nil, common.NewResult(code.InternalError)
	}

	// 防御性编程
	tableName := roles.TableName()
	if tableName == "" {
		mhayaLogger.Warnf("List tableName is nil, tableName:%v", tableName)
		return nil, common.NewResult(code.InternalError)
	}

	cursor, err := rolesCollection.Find(ctx, filter, findOptions)
	if err != nil {
		mhayaLogger.Warnf("List Find error:%v", err)
		return nil, common.NewResult(code.InternalError)
	}
	defer func() {
		if err := cursor.Close(ctx); err != nil {
			mhayaLogger.Warnf("Failed to close cursor: %v", err)
		}
	}()

	var details []*entity.RoleDetail
	for cursor.Next(ctx) {
		var role *entity.RoleDetail
		if err := cursor.Decode(&role); err != nil {
			mhayaLogger.Warnf("List Decode error:%v", err)
			return nil, common.NewResult(code.InternalError)
		}
		details = append(details, role)
	}

	if err := cursor.Err(); err != nil {
		mhayaLogger.Warnf("List cursor error:%v", err)
		return nil, common.NewResult(code.InternalError)
	}

	return &entity.RoleResp{
		Details: details,
		Total:   countDocuments,
	}, nil
}

// Add 新增角色
func (r *Role) Add(ctx context.Context, req entity.RoleAddReq) *code.Result {
	// 验证角色名称是否已存在
	exist, err := r.CheckRoleNameExist(req.Name)
	if err != nil {
		mhayaLogger.Warnf("Add CheckRoleNameExist error:%v", ctx.Err())
		return common.NewResult(code.InternalError)
	}

	if exist {
		return common.NewResult(code.RoleNameExistError)
	}

	// 检查上下文是否有效
	if ctx.Err() != nil {
		mhayaLogger.Warnf("Add ctx error:%v", ctx.Err())
		return common.NewResult(code.InternalError)
	}

	// 插入新角色记录
	roles := models.Roles{}
	insertData := bson.M{}
	insertData["name"] = req.Name
	insertData["desc"] = req.Desc
	insertData["status"] = req.Status
	insertData["created_at"] = time.Now().Unix()
	// 确保 Collection 方法不会返回错误
	collection := mdb.MDB.Collection(roles.TableName())
	_, insertErr := collection.InsertOne(ctx, req)
	if insertErr != nil {
		mhayaLogger.Warnf("Add InsertOne error:%v", insertErr)
		return common.NewResult(code.InternalError)
	}

	return nil
}

// Update 修改角色
func (r *Role) Update(ctx context.Context, req entity.RoleUpdateReq) *code.Result {
	// 更新条件
	objID, err := primitive.ObjectIDFromHex(req.Id)
	if err != nil {
		mhayaLogger.Warnf("Update req.Id error:%v", req.Id)
		return common.NewResult(code.ParamError)
	}

	updateCondition := bson.M{"_id": objID}
	// 更新内容
	updateContent := bson.M{
		"$set": bson.M{
			"name":   req.Name,
			"desc":   req.Desc,
			"status": req.Status,
		},
	}
	// 设置更新选项
	roles := models.Roles{}
	collection := mdb.MDB.Collection(roles.TableName())
	updateOptions := options.Update().SetUpsert(true) // 设置 upsert 选项
	// 执行更新操作
	_, err = collection.UpdateOne(context.TODO(), updateCondition, updateContent, updateOptions)
	if err != nil {
		mhayaLogger.Warnf("Update UpdateOne error:%v", err)
		return common.NewResult(code.InternalError)
	}

	return nil
}

// CheckRoleNameExist 检查角色名称是否已存在
func (r *Role) CheckRoleNameExist(name string) (bool, error) {
	// 创建带超时的上下文
	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()
	roles := models.Roles{}
	collection := mdb.MDB.Collection(roles.TableName())

	// 构建过滤器
	filter := bson.M{"name": name}

	// 执行查询
	err := collection.FindOne(ctx, filter).Err()
	if err != nil {
		if errors.Is(err, mongo.ErrNoDocuments) {
			mhayaLogger.Warnf("No document found with role name: %s", name)
			return false, nil
		}

		return false, err
	}

	return true, nil
}

// Del 删除角色
func (r *Role) Del(ctx context.Context, req entity.RoleDelReq) *code.Result {
	// 创建带超时的上下文
	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()
	roles := models.Roles{}
	collection := mdb.MDB.Collection(roles.TableName())
	id, _ := primitive.ObjectIDFromHex(req.Id)
	_, err := collection.DeleteOne(ctx, bson.M{"_id": id})
	if err != nil {
		mhayaLogger.Warnf("Del DeleteOne error:%v", err)
		return common.NewResult(code.InternalError)
	}

	return nil
}

// AddRoleAccess  添加角色权限
func (r *Role) AddRoleAccess(ctx context.Context, req entity.RoleAccessAddReq) *code.Result {
	// 检查上下文是否有效
	if ctx.Err() != nil {
		mhayaLogger.Warnf("AddRoleAccess ctx error:%v", ctx.Err())
		return common.NewResult(code.InternalError)
	}

	// 检查角色是否存在
	roles := models.Roles{}
	collection := mdb.MDB.Collection(roles.TableName())
	roleIDobj, _ := primitive.ObjectIDFromHex(req.RoleId)
	if err := collection.FindOne(ctx, bson.M{"_id": roleIDobj}).Err(); err != nil {
		if errors.Is(err, mongo.ErrNoDocuments) {
			return common.NewResult(code.RoleNotExistError)
		}
	}
	// 检查权限是否存在 ->具体的权限规则表-存放路由、菜单等
	access := models.Access{}
	collection = mdb.MDB.Collection(access.TableName())
	var accessIDS []primitive.ObjectID
	for _, v := range req.AccessId {
		accessIDobj, _ := primitive.ObjectIDFromHex(v)
		accessIDS = append(accessIDS, accessIDobj)
	}
	filter := bson.M{"_id": bson.M{"$in": accessIDS}} // 数组查询
	if err := collection.FindOne(ctx, filter).Err(); err != nil {
		if errors.Is(err, mongo.ErrNoDocuments) {
			return common.NewResult(code.AccessNotExistError)
		}
	}
	// 插入新角色权限记录
	roleAccess := models.RoleAccess{}
	// 确保 Collection 方法不会返回错误
	collection = mdb.MDB.Collection(roleAccess.TableName())
	_, insertErr := collection.UpdateOne(ctx, bson.M{"role_id": req.RoleId}, bson.M{"$addToSet": bson.M{"access_id": bson.M{"$each": req.AccessId}}}, options.Update().SetUpsert(true))
	if insertErr != nil {
		mhayaLogger.Warnf("AddRoleAccess UpdateOne error:%v", insertErr)
		return common.NewResult(code.InternalError)
	}
	return nil
}

// UpdateRoleAccess 修改角色权限
func (r *Role) UpdateRoleAccess(ctx context.Context, req entity.RoleAccessUpdateReq) *code.Result {
	// 验证请求数据的有效性
	err := validateConcurrently(ctx, req)
	if err != nil {
		mhayaLogger.Warnf("UpdateRoleAccess validateConcurrently error:%v", err)
		return common.NewResult(code.InternalError)
	}

	// 更新角色权限
	err = r.updateAccessInDatabase(ctx, req)
	if err != nil {
		mhayaLogger.Warnf("UpdateRoleAccess updateAccessInDatabase error:%v", err)
		return common.NewResult(code.InternalError)
	}

	// 返回成功
	return nil
}

// DelRoleAccess 根据角色ID删除角色权限
func (r *Role) DelRoleAccess(ctx context.Context, req entity.RoleAccessDelReq) *code.Result {
	roleAccess := models.RoleAccess{}
	collection := mdb.MDB.Collection(roleAccess.TableName())
	filter := bson.M{"role_id": req.RoleId}
	_, err := collection.DeleteOne(ctx, filter)
	if err != nil {
		mhayaLogger.Warnf("DelRoleAccess DeleteOne error:%v", err)
		return common.NewResult(code.InternalError)
	}

	return nil
}

// GetRoleAccessList 获取角色权限列表根据角色ID
func (r *Role) GetRoleAccessList(ctx context.Context, req entity.RoleAccessListReq) (*entity.AccessResp, *code.Result) {
	// 查询角色权限列表
	roleAccess := models.RoleAccess{}
	collection := mdb.MDB.Collection(roleAccess.TableName())
	filter := bson.M{"role_id": req.RoleId} // 数组查询
	cursor, err := collection.Find(ctx, filter)
	defer cursor.Close(ctx)
	if err != nil {
		mhayaLogger.Warnf("GetRoleAccessList Find error:%v", err)
		return nil, common.NewResult(code.InternalError)
	}

	var accessIDS []string
	for cursor.Next(ctx) {
		var roleAccess models.RoleAccess
		if err := cursor.Decode(&roleAccess); err != nil {
			mhayaLogger.Warnf("GetRoleAccessList Decode error:%v", err)
			return nil, common.NewResult(code.InternalError)
		}

		accessIDS = append(accessIDS, roleAccess.AccessID...)
	}

	// 判断accessIDS是否为空
	if len(accessIDS) == 0 {
		return nil, nil
	}
	var objIDS []primitive.ObjectID
	for _, v := range accessIDS {
		objID, _ := primitive.ObjectIDFromHex(v)
		objIDS = append(objIDS, objID)
	}
	// 根据accessIDS查询权限列表 并且按照下级关系组合
	access := models.Access{}
	collection = mdb.MDB.Collection(access.TableName())
	accessFilter := bson.M{"_id": bson.M{"$in": objIDS}}
	cursor, err = collection.Find(ctx, accessFilter)
	defer cursor.Close(ctx)
	if err != nil {
		mhayaLogger.Warnf("GetRoleAccessList sub Find error:%v", err)
		return nil, common.NewResult(code.InternalError)
	}
	var accessList []*entity.AccessDetail
	for cursor.Next(ctx) {
		var accesss *models.Access
		if err := cursor.Decode(&accesss); err != nil {
			mhayaLogger.Warnf("GetRoleAccessList sub Decode error:%v", err)
			return nil, common.NewResult(code.InternalError)
		}
		accessList = append(accessList, &entity.AccessDetail{
			ID:          accesss.ID,
			ActionName:  accesss.ActionName,
			ModuleName:  accesss.ModuleName,
			Description: accesss.Description,
			URL:         accesss.URL,
			ParentId:    accesss.ParentId,
			Sort:        accesss.Sort,
			Type:        accesss.Type,
			Status:      accesss.Status,
		})
	}
	// 格式化数据并且按照下级关系组合
	details := formatAccessData(accessList)

	return &entity.AccessResp{
		Details: details,
		Total:   0,
	}, nil
}

// formatAccessData formats and organizes access data into a hierarchical structure
func formatAccessData(accessData []*entity.AccessDetail) []*entity.AccessDetail {
	nodeMap := make(map[interface{}]*entity.AccessDetail)
	var rootNodes []*entity.AccessDetail
	for i := range accessData {
		node := accessData[i]
		nodeMap[node.ID] = node
	}
	for i := range accessData {
		node := accessData[i]
		if node.ParentId == "0" {
			rootNodes = append(rootNodes, node)
		} else {
			if parentNode, exists := nodeMap[node.ParentId]; exists {
				parentNode.AccessItem = append(parentNode.AccessItem, node)
			}
		}
	}
	return rootNodes
}

// AddAccess 添加权限路由
func (r *Role) AddAccess(ctx context.Context, req entity.AccessAddReq) *code.Result {
	// 检查上下文是否有效
	if ctx.Err() != nil {
		mhayaLogger.Warnf("AddAccess ctx error:%v", ctx.Err())
		return common.NewResult(code.InternalError)
	}

	access := models.Access{}
	collection := mdb.MDB.Collection(access.TableName())
	// 判断是否有相同的数据
	filter := bson.M{"path": req.URL}
	if err := collection.FindOne(ctx, filter).Err(); err == nil {
		return common.NewResult(code.AccessExistError)
	}

	// 插入新角色权限记录
	_, err := collection.InsertOne(ctx, req)
	if err != nil {
		mhayaLogger.Warnf("AddAccess InsertOne error:%v", err)
		return common.NewResult(code.InternalError)
	}

	return nil
}

// DelAccess 删除权限路由
func (r *Role) DelAccess(ctx context.Context, req entity.AccessDelReq) *code.Result {
	access := models.Access{}
	collection := mdb.MDB.Collection(access.TableName())
	// 判断是否有角色使用了该权限路由
	roleAccess := models.RoleAccess{}
	collection = mdb.MDB.Collection(roleAccess.TableName())
	filter := bson.M{"access_id": bson.M{"$in": req.Id}} // 数组查询
	if err := collection.FindOne(ctx, filter).Err(); err == nil {
		return common.NewResult(code.AccessHasUsedError)
	}

	objID := primitive.ObjectID{}
	objID, _ = primitive.ObjectIDFromHex(req.Id)
	_, err := mdb.MDB.Collection(access.TableName()).DeleteOne(ctx, bson.M{"_id": objID})
	if err != nil {
		mhayaLogger.Warnf("DelAccess DeleteOne error:%v", err)
		return common.NewResult(code.InternalError)
	}

	return nil
}

// UpdateAccess  修改权限路由
func (r *Role) UpdateAccess(ctx context.Context, req entity.AccessUpdateReq) *code.Result {
	access := models.Access{}
	collection := mdb.MDB.Collection(access.TableName())
	// update
	var updateFields = bson.M{
		"module_name": req.ModuleName,
		"parent_id":   req.ParentId,
		"action_name": req.ActionName,
		"url":         req.URL,
		"type":        req.Type,
		"description": req.Description,
		"sort":        req.Sort,
		"status":      req.Status}
	// 检查是否有需要更新的字段
	if len(updateFields) == 0 {
		mhayaLogger.Warnf("UpdateAccess len(updateFields) == 0")
		return nil
	}

	// 确保 req.Id 是一个有效的 ObjectID
	objID, err := primitive.ObjectIDFromHex(req.Id)
	if err != nil {
		mhayaLogger.Warnf("UpdateAccess invalid ObjectID:%s, error:%v", req.Id, err)
		return common.NewResult(code.ParamError)
	}

	_, err = collection.UpdateByID(ctx, objID, bson.M{"$set": updateFields})
	if err != nil {
		mhayaLogger.Warnf("UpdateAccess UpdateByID error:%v", err)
		return common.NewResult(code.InternalError)
	}

	return nil
}

// ListAccess listAccessa
func (r *Role) ListAccess(ctx context.Context, req entity.AccessListReq) (*entity.AccessResp, *code.Result) {
	access := models.Access{}
	collection := mdb.MDB.Collection(access.TableName())
	filter := bson.M{}
	if req.ActionName != "" {
		filter["action_name"] = req.ActionName
	}
	if req.ModuleName != "" {
		filter["module_name"] = req.ModuleName
	}
	if req.Status != 0 {
		filter["status"] = req.Status
	}
	if req.Type != 0 {
		filter["type"] = req.Type
	}
	if req.ParentId != "" {
		filter["parent_id"] = req.ParentId
	}
	if req.URL != "" {
		filter["url"] = req.URL
	}
	// 数据验证
	page, pageSize := checkPageParam(req.Page, req.Size)

	// 设置分页选项
	findOptions := options.Find().SetSkip(int64((page - 1) * req.Size)).SetLimit(int64(pageSize))
	findOptions.SetSort(bson.M{"add_time": -1})
	countDocuments, err := collection.CountDocuments(ctx, filter)
	if err != nil {
		mhayaLogger.Warnf("ListAccess CountDocuments error:%v", err)
		return nil, common.NewResult(code.InternalError)
	}

	cursor, err := collection.Find(ctx, filter, findOptions)
	defer cursor.Close(ctx)
	if err != nil {
		mhayaLogger.Warnf("ListAccess Find error:%v", err)
		return nil, common.NewResult(code.InternalError)
	}

	var accessList []*entity.AccessDetail
	for cursor.Next(ctx) {
		var accesss *models.Access
		if err := cursor.Decode(&accesss); err != nil {
			mhayaLogger.Warnf("ListAccess Decode error:%v", err)
			return nil, common.NewResult(code.InternalError)
		}

		accessList = append(accessList, &entity.AccessDetail{
			ID:          accesss.ID,
			ActionName:  accesss.ActionName,
			ModuleName:  accesss.ModuleName,
			Description: accesss.Description,
			URL:         accesss.URL,
			ParentId:    accesss.ParentId,
			Sort:        accesss.Sort,
			Type:        accesss.Type,
			Status:      accesss.Status,
		})
	}

	// 格式化数据并且按照下级关系组合
	details := formatAccessData(accessList)

	return &entity.AccessResp{
		Details: details,
		Total:   countDocuments,
	}, nil
}

// updateAccessInDatabase 在数据库中更新角色权限
func (r *Role) updateAccessInDatabase(ctx context.Context, req entity.RoleAccessUpdateReq) error {
	// 例如更新角色权限表中的记录
	roleAccess := models.RoleAccess{}
	collection := mdb.MDB.Collection(roleAccess.TableName())
	filter := bson.M{"role_id": req.RoleId}
	update := bson.M{"$set": bson.M{"access_id": req.AccessId}}
	_, err := collection.UpdateOne(ctx, filter, update)
	if err != nil {
		return err
	}
	return nil // 假设更新成功，实际应根据业务逻辑处理
}

// AdminBindRole 绑定角色
func (r *Role) AdminBindRole(ctx context.Context, req entity.AdminBindRoleReq) *code.Result {
	// 例如更新角色权限表中的记录
	role := models.Roles{}
	collection := mdb.MDB.Collection(role.TableName())
	roleId, _ := primitive.ObjectIDFromHex(req.RoleId)
	filter := bson.M{"_id": roleId, "status": 1}
	// 判断你是否存在
	if err := collection.FindOne(ctx, filter).Err(); err != nil {
		mhayaLogger.Warnf("AdminBindRole Find error:%v", err)
		return common.NewResult(code.RoleNotExistOrDisabledUserError)
	}

	// 判断管理员是否存在
	admin := model.Admin{}
	collection = mdb.MDB.Collection(admin.TableName())
	objID, _ := primitive.ObjectIDFromHex(req.AdminId)
	err := collection.FindOne(ctx, bson.M{"_id": objID}).Decode(&admin)
	if err != nil {
		return common.NewResult(code.AdminNotExistError)
	}

	if admin.RoleId == req.RoleId {
		mhayaLogger.Warnf("管理员角色和请求角色一致，无需修改")
		return nil
	}

	if admin.Username == "admin" {
		mhayaLogger.Warnf("admin-超级账户不能修改角色")
		return common.NewResult(code.AdminMustNotUpdateError)
	}

	filter = bson.M{"_id": objID, "status": 1}
	if err := collection.FindOne(ctx, filter).Err(); err != nil {
		mhayaLogger.Warnf("管理员不存在 或者 已经被禁用")
		return common.NewResult(code.RoleNotExistOrDisabledUserError)
	}

	// 更新管理员数据
	_, err = collection.UpdateByID(ctx, objID, bson.M{"$set": bson.M{"role_id": req.RoleId}})
	if err != nil {
		mhayaLogger.Warnf("AdminBindRole UpdateByID error:%v", err)
		return common.NewResult(code.InternalError)
	}

	return nil // 假设更新成功，实际应根据业务逻辑处理
}

// AdminUnBindRole 取消绑定角色
func (r *Role) AdminUnBindRole(ctx context.Context, req entity.AdminBindRoleReq) *code.Result {
	// 例如更新角色权限表中的记录
	admin := model.Admin{}
	collection := mdb.MDB.Collection(admin.TableName())
	objID, _ := primitive.ObjectIDFromHex(req.AdminId)
	filter := bson.M{"_id": objID}
	err := collection.FindOne(ctx, filter).Decode(&admin)
	if err != nil {
		return common.NewResult(code.AdminNotExistError)
	}

	if admin.RoleId == req.RoleId {
		mhayaLogger.Warnf("管理员角色和请求角色一致，无需修改")
		return nil
	}

	if admin.Username == "admin" {
		mhayaLogger.Warnf("admin-超级账户不能修改角色")
		return common.NewResult(code.AdminMustNotUpdateError)
	}

	// 更新管理员数据
	_, err = collection.UpdateByID(ctx, objID, bson.M{"$set": bson.M{"role_id": ""}})
	if err != nil {
		mhayaLogger.Warnf("AdminUnBindRole UpdateByID error:%v", err)
		return common.NewResult(code.InternalError)
	}

	return nil
}

// GetAdminRole GetAdminBindRole 根据角色id 获取Access
func getAdmin(ctx context.Context, id string) (*model.Admin, error) {
	objID, err := primitive.ObjectIDFromHex(id)
	if err != nil {
		return nil, fmt.Errorf("解析管理员ID失败: %v", err)
	}

	admin := model.Admin{}
	adminCollection := mdb.MDB.Collection(admin.TableName())
	adminFilter := bson.M{"_id": objID}
	err = adminCollection.FindOne(ctx, adminFilter).Decode(&admin)
	if err != nil {
		if errors.Is(err, mongo.ErrNoDocuments) {
			return nil, fmt.Errorf("找不到管理员")
		}
		return nil, fmt.Errorf("查询管理员失败: %v", err)
	}
	return &admin, nil
}

func getRole(ctx context.Context, id string) (*models.Roles, error) {
	objID, err := primitive.ObjectIDFromHex(id)
	if err != nil {
		return nil, fmt.Errorf("解析角色ID失败: %v", err)
	}

	role := models.Roles{}
	roleCollection := mdb.MDB.Collection(role.TableName())
	roleFilter := bson.M{"_id": objID}
	err = roleCollection.FindOne(ctx, roleFilter).Decode(&role)
	if err != nil {
		if errors.Is(err, mongo.ErrNoDocuments) {
			return nil, fmt.Errorf("找不到角色")
		}
		return nil, fmt.Errorf("查询角色失败: %v", err)
	}
	return &role, nil
}

func getRoleAccess(ctx context.Context, roleId string) (*models.RoleAccess, error) {
	roleAccess := models.RoleAccess{}
	roleAccessCollection := mdb.MDB.Collection(roleAccess.TableName())
	roleAccessFilter := bson.M{"role_id": roleId}
	err := roleAccessCollection.FindOne(ctx, roleAccessFilter).Decode(&roleAccess)
	if err != nil {
		if errors.Is(err, mongo.ErrNoDocuments) {
			return nil, fmt.Errorf("找不到角色权限")
		}
		return nil, fmt.Errorf("查询角色权限失败: %v", err)
	}
	return &roleAccess, nil
}

func (r *Role) GetAdminRole(ctx context.Context, req entity.AdminBindRoleReq) (*entity.AdminBindRoleResp, *code.Result) {
	if req.RoleId == "admin" {
		access := models.Access{}
		collection := mdb.MDB.Collection(access.TableName())
		filter := bson.M{}
		cursor, err := collection.Find(ctx, filter)
		defer cursor.Close(ctx)
		if err != nil {
			mhayaLogger.Warnf("GetAdminRole Find error:%v", err)
			return nil, common.NewResult(code.InternalError)
		}

		var accessList []*entity.AccessDetail
		for cursor.Next(ctx) {
			var accesss *models.Access
			err := cursor.Decode(&accesss)
			if err != nil {
				mhayaLogger.Warnf("GetAdminRole Decode error:%v", err)
				return nil, common.NewResult(code.InternalError)
			}
			accessList = append(accessList, &entity.AccessDetail{
				ID:          accesss.ID,
				ActionName:  accesss.ActionName,
				Description: accesss.Description,
				ModuleName:  accesss.ModuleName,
				ParentId:    accesss.ParentId,
				Sort:        accesss.Sort,
				Status:      accesss.Status,
				Type:        accesss.Type,
				URL:         accesss.URL,
				AddTime:     accesss.AddTime,
			})
		}
		return &entity.AdminBindRoleResp{
			AdminId:    "admin",
			AdminName:  "admin",
			RoleId:     "admin",
			RoleName:   "超级管理员",
			AccessList: formatAccessData(accessList),
		}, nil

	}

	role, err := getRole(ctx, req.RoleId)
	if err != nil {
		mhayaLogger.Warnf("GetAdminRole getRole error:%v", err)
		return nil, common.NewResult(code.InternalError)
	}

	roleAccess, err := getRoleAccess(ctx, req.RoleId)
	if err != nil {
		mhayaLogger.Warnf("GetAdminRole getRoleAccess error:%v", err)
		return nil, common.NewResult(code.InternalError)
	}

	var AccessIds []primitive.ObjectID
	var invalidAccessIds []string
	for _, v := range roleAccess.AccessID {
		objId, err := primitive.ObjectIDFromHex(v)
		if err != nil {
			invalidAccessIds = append(invalidAccessIds, v)
			continue
		}
		AccessIds = append(AccessIds, objId)
	}

	if len(AccessIds) == 0 {
		if len(invalidAccessIds) > 0 {
			mhayaLogger.Warnf("GetAdminRole 无效的权限ID:%v", strings.Join(invalidAccessIds, ", "))
			return nil, common.NewResult(code.InternalError)
		}

		return nil, common.NewResult(code.NoAccessError)
	}

	access := models.Access{}
	collection := mdb.MDB.Collection(access.TableName())
	filter := bson.M{}
	filter["_id"] = bson.M{"$in": AccessIds}
	cursor, err := collection.Find(ctx, filter)
	defer cursor.Close(ctx)
	if err != nil {
		mhayaLogger.Warnf("GetAdminRole Find error:%v", err)
		return nil, common.NewResult(code.InternalError)
	}

	var accessList []*entity.AccessDetail
	for cursor.Next(ctx) {
		var accesss *models.Access
		if err := cursor.Decode(&accesss); err != nil {
			mhayaLogger.Warnf("GetAdminRole Decode error:%v", err)
			return nil, common.NewResult(code.InternalError)
		}
		accessList = append(accessList, &entity.AccessDetail{
			ID:          accesss.ID,
			ActionName:  accesss.ActionName,
			ModuleName:  accesss.ModuleName,
			Description: accesss.Description,
			URL:         accesss.URL,
			ParentId:    accesss.ParentId,
			Sort:        accesss.Sort,
			Type:        accesss.Type,
			Status:      accesss.Status,
		})
	}

	return &entity.AdminBindRoleResp{
			AdminId:    req.AdminId,
			AdminName:  "adminUsername",
			RoleName:   role.Name,
			RoleId:     req.RoleId,
			AccessList: formatAccessData(accessList)},
		nil
}

// 使用协程和通道并发执行验证操作
func validateConcurrently(ctx context.Context, req entity.RoleAccessUpdateReq) error {
	// 创建通道
	ch := make(chan error, 3)

	// 并发执行验证操作
	var wg sync.WaitGroup
	wg.Add(3)
	go func() {
		defer wg.Done()
		ch <- validateRoleExistence(ctx, req)
	}()
	go func() {
		defer wg.Done()
		ch <- validateAccessExistence(ctx, req)
	}()
	go func() {
		defer wg.Done()
		ch <- validateRoleAccessExistence(ctx, req)
	}()

	// 收集所有验证结果
	var e []error
	go func() {
		defer wg.Wait()
		for i := 0; i < 3; i++ {
			if err := <-ch; err != nil {
				e = append(e, err)
			}
		}
		if len(e) > 0 {
			ch <- fmt.Errorf("验证失败: %v", e)
		} else {
			ch <- nil
		}
	}()

	// 等待所有并发任务完成
	select {
	case err := <-ch:
		return err
	case <-ctx.Done():
		return ctx.Err()
	}
}

// 验证角色是否存在
func validateRoleExistence(ctx context.Context, req entity.RoleAccessUpdateReq) error {
	roles := models.Roles{}
	collection := mdb.MDB.Collection(roles.TableName())
	objID, err := primitive.ObjectIDFromHex(req.RoleId)
	if err != nil {
		return fmt.Errorf("解析角色ID失败: %v", err)
	}
	if err := collection.FindOne(ctx, bson.M{"_id": objID}).Err(); err != nil {
		if errors.Is(err, mongo.ErrNoDocuments) {
			return fmt.Errorf("角色不存在")
		}
		return err
	}
	return nil
}

// 验证权限是否存在
func validateAccessExistence(ctx context.Context, req entity.RoleAccessUpdateReq) error {
	access := models.Access{}
	collection := mdb.MDB.Collection(access.TableName())
	objIDS := make([]primitive.ObjectID, len(req.AccessId))
	for i, id := range req.AccessId {
		objID, err := primitive.ObjectIDFromHex(id)
		if err != nil {
			return fmt.Errorf("解析权限ID失败: %v", err)
		}
		objIDS[i] = objID
	}

	filter := bson.M{"_id": bson.M{"$in": objIDS}} // 数组查询
	if err := collection.FindOne(ctx, filter).Err(); err != nil {
		if errors.Is(err, mongo.ErrNoDocuments) {
			return fmt.Errorf("权限不存在")
		}
		return err
	}
	return nil
}

// 验证角色权限是否已存在
func validateRoleAccessExistence(ctx context.Context, req entity.RoleAccessUpdateReq) error {
	roleAccess := models.RoleAccess{}
	collection := mdb.MDB.Collection(roleAccess.TableName())
	filter := bson.M{"role_id": req.RoleId}
	if err := collection.FindOne(ctx, filter).Err(); err != nil {
		if errors.Is(err, mongo.ErrNoDocuments) {
			return fmt.Errorf("角色权限不存在 不能更新")
		}
		return err
	}
	return nil
}
