<?php
namespace App\Admin\Controllers;
use App\Department;
use App\Company;
use App\Facades\CommonFacade;
use App\Http\Controllers\Controller;
use Encore\Admin\Controllers\HasResourceActions;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Show;
class DepartmentController extends Controller
{
    use HasResourceActions;
    
    public function index(Content $content)
    {
        return $content
            ->header('部门')
            ->description('列表')
            ->body($this->grid());
    }
    
    public function show($id, Content $content)
    {
        return $content
            ->header('部门')
            ->description('详情')
            ->body($this->detail($id));
    }
    
    public function edit($id, Content $content)
    {
        return $content
            ->header('编辑')
            ->description('门店')
            ->body($this->form()->edit($id));
    }
    
    public function create(Content $content)
    {
        return $content
            ->header('创建')
            ->description('部门')
            ->body($this->form());
    }
    
    protected function grid()
    {
        $grid = new Grid(new Department);
        $grid->model()->where('company_id', CommonFacade::getCompanyId());
        $grid->name('名称');
        $grid->parent()->name('上级部门');
        $grid->created_at('创建时间');
        $grid->updated_at('更新时间');
        return $grid;
    }
    
    protected function detail($id)
    {
        $show = new Show(Department::findOrFail($id));
        $show->id('Id');
        $show->name('名称');
        $show->parent('上级', function ($parent){
            $parent->setResource('admin/company/depart');
            $parent->name('名称');
        });
        $show->created_at('创建时间');
        $show->updated_at('更新时间');
        return $show;
    }
    
    protected function form()
    {
        $form = new Form(new Department);
        $departments = Department::where('company_id', CommonFacade::getCompanyId())->get();
        $options = [];
        foreach ($departments as $item) {
            $options[$item->id] =$item->name;
        }
        $form->text('name', '部门名称')->rules('required');
        $form->select('parent_id', '上级部门')->options($options);
        $form->saved(function (Form $form)  {
            $form->model()->company_id = CommonFacade::getCompanyId();
            $form->model()->save();
        });
        return $form;
    }
}