<?php

namespace App\Community\Controllers;

use App\Models\CdmsPermissions;
use App\Models\CdmsRoles;
use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Show;

class  PermissionController extends AdminController
{
    /**
     * Title for current resource.
     *
     * @var string
     */
    protected $title = '权限列表';

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        $grid = new Grid(new CdmsRoles());

        $user = Admin::user();
        $is_admin = Admin::user()->inRoles(['administrator','devloper']);
        $grid->model()->orderByDesc('id');
        $grid->disableCreateButton(false);
//        $is_manager = Admin::user()->isRole('manager');
        if(!$is_admin){
            $org_id = $user->org_id;
            $grid->model()->where(['org_id'=>$org_id]);
        }
        $grid->column('organization.name', __('所属机构'))->display(function ($org_name){
            return $org_name ?? '总后台';
        });
        $grid->column('name', __('名称'));
        $grid->column('slug', __('标识'));
        $grid->column('created_at', __('创建时间'));
        $grid->column('updated_at', __('更新时间'));

        return $grid;
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     * @return Show
     */
    protected function detail($id)
    {
        $show = new Show(CdmsRoles::findOrFail($id));

        $show->field('id', __('Id'));
        $show->field('name', __('Name'));
        $show->field('slug', __('Slug'));
        $show->field('created_at', __('Created at'));
        $show->field('updated_at', __('Updated at'));

        return $show;
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        $form = new Form(new CdmsRoles());
        $is_manager = Admin::user()->isRole('manager');

        if($is_manager){
            $org_id = Admin::user()->org_id;
            $form->hidden('org_id')->value($org_id);
        }

        $form->text('slug', __('标识'))->rules('required',['required'=>'标识必须']);
        $form->text('name', '名称')
            ->creationRules(['required', "unique:cdms_roles"])
            ->updateRules(['required', "unique:cdms_roles,name,{{id}}"]);
        $form->listbox('permissions', trans('admin.permissions'))->options(CdmsPermissions::all()->pluck('name', 'id'));

        return $form;
    }
}
