<?php
namespace App\JsonRpc;
use App\Model\Role;
use App\Model\Menu;
use App\Model\RoleUser;
use App\Model\Website;
use App\Model\WebsiteRoleUser;
use App\Tools\Result;
use Hyperf\RpcServer\Annotation\RpcService;

#[RpcService(name: "AuthorityService", protocol: "jsonrpc-http", server: "jsonrpc-http")]
class AuthorityService implements AuthorityServiceInterface
{

    /**
     * @param array $data
     * @return array
     */
    public function getMenuList(array $data): array
    {
        $result = Menu::get();
        if (empty($result)) {
            return Result::error("没有菜单",0,[]);
        }
        return Result::success($result);
    }

    /**
     * @param array $data
     * @return array
     */
    public function getMenuInfo(array $data): array
    {
        $result = Menu::where(['id'=>$data['id']])->first();
        if (empty($result)) {
            return Result::error("没有菜单",0,[]);
        }
        return Result::success($result);
    }

    /**
     * @param array $data
     * @return array
     */
    public function updateMenu(array $data): array
    {
        $where = [
            'id'=>$data['id']
        ];
        unset($data['id']);
        $result = Menu::where($where)->update($data);
        if($result){
            return Result::success($data);
        }else{
            return Result::error($data);
        }
    }

    /**
     * @param array $data
     * @return array
     */
    public function delMenu(array $data): array
    {
        $result = Menu::where(['id'=>$data['id']])->delete();
        if($result){
            return Result::success($data);
        }else{
            return Result::error($data);
        }
    }

    /**
     * @param array $data
     * @return array
     */
    public function addMenu(array $data): array
    {
        $result = Menu::insertGetId($data);
        if($result){
            return Result::success($data);
        }else{
            return Result::error($data);
        }
    }

    /**
     * @param array $data
     * @return array
     */
    public function getRecursionMenu(array $data): array
    {
        //根据角色查询权限信息
        $roleWhere = [
            'role_user.user_id'=>$data['user_id']
        ];
        $roleInfo = RoleUser::where($roleWhere)
            ->leftJoin('role', 'role.id', '=', 'role_user.role_id')
            ->first();
        if(empty($roleInfo)){
            return Result::error("没有权限",0);
        }
        $roleArr = json_decode($roleInfo['rule']);
        $result = Menu::whereIn('id',$roleArr)->get();
        if (empty($result)) {
            return Result::error("没有菜单",0,[]);
        }
        return Result::success($result);
    }

    /**
     * 获取所有的权限
     * @param array $data
     * @return array
     */
    public function getAllMenuList(array $data): array
    {
        $result = Menu::get();
        if($result){
            return Result::success($result);
        }else{
            return Result::error("没有权限",0,[]);
        }
    }
}