<?php
// +----------------------------------------------------------------------
// | onezan-admin 快速开发的管理平台
// +----------------------------------------------------------------------
// | 官方网址：https://www.onezan.cn
// +----------------------------------------------------------------------
// | onezan团队 版权所有 开源版本可自由商用
// +----------------------------------------------------------------------
// | Author: 543885307@qq.com
// +----------------------------------------------------------------------
namespace app\service\admin\admin;

use app\repository\admin\AdminUserRepository;
use app\service\domain\admin\CoreAdminPermissionService;
use app\service\RequestHelper;
use app\service\admin\BaseAdminService;
use app\service\domain\admin\CoreAdminUserService;
use think\Request;


/**
 * User Service
 * @package app\service\admin\admin
 */
class UserService extends BaseAdminService
{

    /**
     * 管理员用户分页列表
     * @param Request $request 请求对象
     * @return array
     */
    public function list(Request $request): array
    {
        $page = $this->adminUserRepository()->paginate([
            'keyword' => $request->get('keyword'),
        ], RequestHelper::parseLimit($request, 'limit', 10, 100));

        $items = $page['data'] ?? [];
        $userIds = array_column($items, 'id');
        $rolesByUser = $this->adminUserRepository()->rolesByUserIds($userIds);

        foreach ($items as &$item) {
            unset($item['password']);
            $uid = (int)($item['id'] ?? 0);
            $item['roles'] = $rolesByUser[$uid] ?? [];
        }
        unset($item);

        $page['data'] = $items;
        return ['code' => 0, 'data' => $page];
    }


    /**
     * 新增或更新管理员用户
     * @param Request $request 请求对象
     * @return array
     */
    public function save(Request $request): array
    {
        return $this->core()->save([
            'id' => $request->post('id'),
            'username' => $request->post('username', ''),
            'password' => $request->post('password', ''),
            'nickname' => $request->post('nickname', ''),
            'status' => $request->post('status', 1),
        ]);
    }


    /**
     * 删除管理员用户
     * @param Request $request 请求对象
     * @return array
     */
    public function delete(Request $request): array
    {
        $id = $request->post('id');
        if (!is_numeric($id)) {
            return ['code' => 1, 'msg' => ''];
        }

        return $this->core()->delete((int)$id);
    }


    /**
     * 获取可分配给用户的角色选项
     * @param Request $request 请求对象
     * @return array
     */
    public function roleOptions(Request $request): array
    {
        $uid = (int)($request->uid ?? 0);
        $user = $this->adminUserRepository()->findById($uid);
        if (!$user || (int)($user->status ?? 0) !== 1) {
            return ['code' => 403, 'msg' => '', '_http_status' => 403];
        }

        return ['code' => 0, 'data' => $this->permissionService()->getAssignableRolesForUser($user)->toArray()];
    }


    /**
     * 设置用户角色
     * @param Request $request 请求对象
     * @return array
     */
    public function setRoles(Request $request): array
    {
        $userId = $request->post('user_id');
        if (!is_numeric($userId)) {
            return ['code' => 1, 'msg' => ''];
        }

        $actor = $this->adminUserRepository()->findById((int)($request->uid ?? 0));
        if (!$actor || (int)($actor->status ?? 0) !== 1) {
            return ['code' => 403, 'msg' => '', '_http_status' => 403];
        }

        return $this->core()->setRoles($actor, (int)$userId, (array)$request->post('role_ids/a'));
    }

    /**
     * 获取管理员用户核心服务实例
     * @return CoreAdminUserService
     */
    private function core(): CoreAdminUserService
    {
        return $this->app->make(CoreAdminUserService::class);
    }

    /**
     * 获取管理员权限服务实例
     * @return CoreAdminPermissionService
     */
    private function permissionService(): CoreAdminPermissionService
    {
        return $this->app->make(CoreAdminPermissionService::class);
    }

    /**
     * 获取管理员用户仓储实例
     * @return AdminUserRepository
     */
    private function adminUserRepository(): AdminUserRepository
    {
        return $this->app->make(AdminUserRepository::class);
    }
}