<?php
namespace App\Domains\Permission\Http\Controllers;

use App\Core\Controller;
use Illuminate\Http\Request;
use App\Domains\Permission\Services\PermissionService;

class PermissionController extends Controller
{
    protected $request;
    protected $permissionService;

    /**
     * 构造函数，自动注入.
     */
    public function __construct(Request $request, PermissionService $permissionService)
    {
        $this->request = $request;
        $this->permissionService = $permissionService;
        $this->account = app('dipper')->initAccount();
    }

    /**
     * 列表.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $conditions = [];

        if (!$this->account->can('permissions.create')) {
            $conditions['role_ids'] = $this->account->roles->pluck('id')->toArray();
        }

        $permissions = $this->permissionService->index($conditions)->toTree();

        return res($permissions, '权限列表', 201);
    }


    /**
     * 创建.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $attributes = $this->request->all();

        $permission = $this->permissionService->store($attributes);

        return res($permission, '创建成功');
    }

    /**
     * 编辑.
     *
     * @return \Illuminate\Http\Response
     */
    public function update($id)
    {
        $attributes = $this->request->all();
        $attributes['id'] = $id;

        $permission = $this->permissionService->store($attributes);

        return res($permission, '修改成功');
    }

    /**
     * 删除.
     *
     * @return \Illuminate\Http\Response
     */
    public function destroy()
    {
        $ids = $this->request->ids();
        $this->permissionService->destroy($ids);
        return res(true, '删除成功');
    }
}
