<?php

namespace Modules\Mall\Http\Controllers\Admin;

use App\Admin\Traits\WithUploads;
use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Illuminate\Http\Request;
use Modules\Mall\Models\Category;

class CategoryController extends AdminController
{

    use WithShop,
        WithUploads;

    protected $title = "分类管理";

    protected function grid(): Grid
    {
        $grid = new Grid(new Category());

        $parentId = request()->get('parent_id');
        $grid->model()
             ->with(['shop'])
             ->withCount('goods')
             ->when($parentId, function ($query) use ($parentId) {
                 $query->where('parent_id', $parentId);
             });

        $grid->filter(function (Grid\Filter $filter) {
            $filter->scope('trashed', '回收站')->onlyTrashed();

            $filter->column(1 / 3, function (Grid\Filter $filter) {
                $filter->like('name', '分类名称');
            });
            $filter->column(1 / 3, function (Grid\Filter $filter) {
                $filter->like('slug', '分类简称');
            });
            $filter->column(1 / 3, function (Grid\Filter $filter) {
                $filter->equal('status', '状态')->select([
                    0 => '禁用',
                    1 => '正常',
                ]);
            });
        });

        $grid->column('shop.name', '所属店铺');
        $grid->column('parent.name', '上级分类')
             ->link(function () {
                 return route('admin.mall.categories.index', ['parent_id' => $this->parent_id]);
             }, '_self');;
        $grid->column('name', '分类名称')
             ->link(function () {
                 return route('admin.mall.categories.index', ['parent_id' => $this->id]);
             }, '_self');
        $grid->column('slug', '分类简称');
        $grid->column('goods_count', '分类商品');
        $grid->column('order', '排序');
        $grid->column('status', '状态')->bool();

        return $grid;
    }

    /**
     * Notes   : 编辑表单
     * @Date   : 2021/4/25 1:41 下午
     * @Author : < Jason.C >
     * @return \Encore\Admin\Form
     */
    protected function form(): Form
    {
        $form = new Form(new Category);

        $this->shop($form)->required();
        $form->select('parent_id', '上级分类')
             ->options(Category::selectOptions(function ($model) {
                 return $model->where('status', 1);
             }, '一级分类'))
             ->required();
        $form->text('name', '分类名称')
             ->required()
             ->rules('required');
        $form->text('slug', '分类简称');
        $form->textarea('description', '分类简介');
        $this->cover($form, 'cover', '分类图片');
        $form->number('order', '排序')->default(0);
        $form->switch('status', '显示')->default(1);

        return $form;
    }

    public function ajax(Request $request)
    {
        $key = $request->q;

        return Category::where('name', 'like', "%$key%")->paginate(null, ['id', 'name as text']);
    }

}
