<?php

namespace App\Distributor\Controllers;

use App\Distributor\Repositories\DistVideo;
use App\distributor\Repositories\DistVideoCategory;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Show;
use Dcat\Admin\Http\Controllers\AdminController;
use Dcat\Admin\Layout\Content;
use Dcat\Admin\Admin;

class DistVideoCategoryController extends AdminController
{
    /**
     * page index
     */
    public function index(Content $content)
    {
        return $content
            ->header(admin_trans('admin.video_category'))
            ->description(admin_trans('admin.all'))
            ->breadcrumb(['text'=>'Video Category','url'=>''])
            ->body($this->grid());
    }

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {

        return Grid::make(new DistVideoCategory(), function (Grid $grid) {

            $grid->model()->where('dist_id', getDistributorId());//这里限不了，改为仓库限制
            $grid->column('id')->sortable();
            $grid->column('name')->tree(true,true);
            $grid->column('parent_id');
            $grid->column('order')->orderable();
            $grid->column('enabled')->switch();
            $grid->column('created_at');
            $grid->column('updated_at')->sortable();
            //$grid->quickSearch('name');
            //按钮
            $grid->disableViewButton();
            $grid->showQuickEditButton();
            $grid->enableDialogCreate();
            $grid->disableEditButton();
        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Form::make(new DistVideoCategory(), function (Form $form) {
            $form->display('id');
            $form->text('name')->required();
            $form->select('parent_id', admin_trans_field('parent'))
                ->options([0 =>admin_trans_label('root')]) // 只显示 0 => root
                ->saving(function ($v) {
                    return (int) $v;
                });
            $form->switch('enabled')->default(1);
            $form->hidden('dist_id'); // 隐藏dist_id字段,用于保存
            $form->saving(function (Form $form) {
                $form->dist_id =getDistributorId();//保存时直接写死dist_id

                if (!$form->isCreating()) {
                    // 验证主键 ID 的 dist_id 是否与 session 的 dist_id 一致
                    $current = DistVideoCategory::findById($form->getKey());
                    if ($current && $current->dist_id !== $form->dist_id) {
                        throw new \Exception('Unable to modify the product because the distributor ID does not match.');
                    }
                }
            });

        });
    }
}
