<?php

namespace App\Community\Controllers;

use App\Models\Office;
use App\Models\Organization;
use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Show;

class OfficeController extends AdminController
{
    /**
     * Title for current resource.
     *
     * @var string
     */
    protected $title = '科室';

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        $grid = new Grid(new Office());
        $grid->model()->orderByDesc('id');
        $is_admin = Admin::user()->isRole('administrator');
        if(!$is_admin){
            $grid->model()->where(['org_id'=>Admin::user()->org_id]);
        } else {
            $grid->column('organizations.name','机构名称');
        }

        $grid->disableCreateButton(false);
        $grid->column('id', __('Id'));
        $grid->column('name', __('名称'));
        $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(Office::findOrFail($id));

        $show->field('id', __('Id'));
        $show->field('name', __('Name'));
        $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 Office());
        $org_id = Admin::user()->org_id;
        if($org_id){
            $form->hidden('org_id', __('名称'))->value(Admin::user()->org_id);
        } else {
            $orglist = Organization::pluck('name','id');
            $form->select('org_id', __('名称'))->options($orglist);
        }
        $form->text('name', __('名称'));
        $form->setWidth(6);
        return $form;
    }
}
