package internal

import (
	"context"
	"github.com/gogf/gf/v2/util/guid"
	"yx-dataset-server/app/errors"
	"yx-dataset-server/app/model"
	"yx-dataset-server/app/schema"
)

// NewRole 创建Role
func NewRole(
	mRole model.IRole,
	mRoleMenu model.IRoleMenu,
	mTrans model.ITrans,
	mMenu model.IMenu,
	mUser model.IUser,
) *Role {
	return &Role{
		RoleModel:     mRole,
		roleMenuModel: mRoleMenu,
		transModel:    mTrans,
		menuModel:     mMenu,
		userModel:     mUser,
	}
}

// Role 创建Role对象
type Role struct {
	RoleModel     model.IRole
	roleMenuModel model.IRoleMenu
	transModel    model.ITrans
	menuModel     model.IMenu
	userModel     model.IUser
}

// Query 查询数据
// 权限规则：
//   - root / 系统管理员：可查询全部角色
//   - 企业管理员：仅可查询企业员工角色（code=99）
//   - 其他：返回空列表
func (a *Role) Query(ctx context.Context, params schema.RoleQueryParam, opts ...schema.RoleQueryOptions) (*schema.RoleQueryResult, error) {
	code, err := GetUserRoleCode(ctx, a.userModel, a.RoleModel)
	if err != nil {
		return nil, err
	}
	switch code {
	case RoleCodeSystemAdmin:
		// 全部角色
	case RoleCodeEnterpriseAdmin:
		params.Code = RoleCodeEmployee
	default:
		return &schema.RoleQueryResult{
			Data:       make(schema.Roles, 0),
			PageResult: &schema.PaginationResult{Total: 0},
		}, nil
	}
	return a.RoleModel.Query(ctx, params, opts...)
}

// Get 查询指定数据
func (a *Role) Get(ctx context.Context, recordID string, opts ...schema.RoleQueryOptions) (*schema.Role, error) {
	item, err := a.RoleModel.Get(ctx, recordID, opts...)
	if err != nil {
		return nil, err
	} else if item == nil {
		return nil, errors.ErrNotFound
	}
	roleMenu, err := a.roleMenuModel.Query(ctx, schema.RoleMenuQueryParam{RoleId: item.RecordID})
	if err != nil {
		return nil, err
	}
	menu, err := a.menuModel.Query(ctx, schema.MenuQueryParam{RecordIDs: roleMenu.Data.ToMenuIds()})
	if err != nil {
		return nil, err
	}
	item.Menus = menu.Data
	return item, nil
}

func (a *Role) checkCode(ctx context.Context, code string) error {
	result, err := a.RoleModel.Query(ctx, schema.RoleQueryParam{
		Code: code,
	}, schema.RoleQueryOptions{
		PageParam: &schema.PaginationParam{PageSize: -1},
	})
	if err != nil {
		return err
	} else if result.PageResult.Total > 0 {
		return errors.New400Response("编号已经存在")
	}
	return nil
}

func (a *Role) getUpdate(ctx context.Context, recordID string) (*schema.Role, error) {
	return a.Get(ctx, recordID)
}

// Create 创建数据
func (a *Role) Create(ctx context.Context, item schema.Role) error {
	item.RecordID = guid.S()
	err := ExecTrans(ctx, a.transModel, func(ctx context.Context) error {
		if len(item.Menus) > 0 {
			for _, menu := range item.Menus {
				err := a.roleMenuModel.Create(ctx, schema.RoleMenu{
					RecordId: guid.S(),
					RoleId:   item.RecordID,
					MenuId:   menu.RecordID,
				})
				if err != nil {
					return err
				}
			}
		}
		return a.RoleModel.Create(ctx, item)
	})
	return err
}

// Update 更新数据
func (a *Role) Update(ctx context.Context, recordID string, item schema.Role) error {
	oldItem, err := a.RoleModel.Get(ctx, recordID)
	if err != nil {
		return err
	} else if oldItem == nil {
		return errors.ErrNotFound
	}

	err = ExecTrans(ctx, a.transModel, func(ctx context.Context) error {
		err = a.roleMenuModel.DeleteByRoleId(ctx, recordID)
		if len(item.Menus) > 0 {
			for _, menu := range item.Menus {
				err := a.roleMenuModel.Create(ctx, schema.RoleMenu{
					RecordId: guid.S(),
					RoleId:   oldItem.RecordID,
					MenuId:   menu.RecordID,
				})
				if err != nil {
					return err
				}
			}
		}
		return a.RoleModel.Update(ctx, recordID, item)
	})

	return err
}

// Delete 删除数据
func (a *Role) Delete(ctx context.Context, recordID string) error {
	oldItem, err := a.RoleModel.Get(ctx, recordID)
	if err != nil {
		return err
	} else if oldItem == nil {
		return errors.ErrNotFound
	}
	err = ExecTrans(ctx, a.transModel, func(ctx context.Context) error {
		err = a.roleMenuModel.DeleteByRoleId(ctx, recordID)
		if err != nil {
			return err
		}
		return a.RoleModel.Delete(ctx, recordID)
	})
	return err
}
