<?php

namespace App\Admin\Controllers;

use App\Models\Product;
use App\Models\ProductCategory;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Show;
use Dcat\Admin\Http\Controllers\AdminController;

class ProductCategoryController extends AdminController
{

    public function destroy($id)
    {
        $childIds = ProductCategory::where('pid',$id)->get()->pluck('id');
        $childIds[]= $id;

        $hasEpisode = Product::whereIn('cate_id',$childIds)->count();
        if($hasEpisode){
            $form = new Form();
            $response = $form->response();
            return $response->error('当前分类或子分类存在产品，前先删除产品后再删除分类');
        }

        return $this->form()->destroy($id);
    }

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Grid::make(new ProductCategory(), function (Grid $grid) {
            $grid->model()->orderByDesc('sort');
            $grid->column('id')->sortable();
            $grid->column('name');
            $grid->column('cover_img')->image('',100);
            $grid->column('level')->using(config('global.cat_level'));
            $grid->column('is_opened')->switch();
            $grid->column('sort')->editable();
            $grid->column('created_at');
            $grid->disableViewButton();
        });
    }


    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Form::make(new ProductCategory(), function (Form $form) {
            $form->display('id');
            $form->radio('level')
                ->when(2, function (Form $form){
                    $options = ProductCategory::select(['id','name'])
                        ->where('level',1)
                        ->get()
                        ->pluck('name', 'id');
                    $form->select('pid')->options($options);
                })
                ->options(config('global.cat_level'))
                ->default(1);
            $form->text('name')->required();
            $form->image('cover_img','封面图（宽高比 1.4:1）')->saveFullUrl()
                ->uniqueName()->autoUpload()
                ->autoSave(false)
                ->removable(false)
                ->width(4)->required();
            $form->radio('is_opened')
                ->options(config('global.bool_status'))
                ->default(1);
            $form->number('sort');

            $form->disableViewButton();
            $form->disableDeleteButton();
            $form->disableListButton();
            $form->disableEditingCheck();
            $form->disableViewCheck();
            $form->disableCreatingCheck();
        });
    }
}
