<?php

namespace Modules\Mall\Http\Controllers\Admin;

use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Illuminate\Http\Request;
use Modules\Mall\Models\Delivery;

class DeliveryController extends AdminController
{

    use WithShop;

    protected $title = '运费模板';

    public function grid(): Grid
    {
        $grid = new Grid(new Delivery());

        $grid->model()
             ->with(['shop'])
             ->withCount('rules');

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

            $filter->column(1 / 3, function (Grid\Filter $filter) {
                $filter->like('shop.name', '所属店铺');
            });

            $filter->column(1 / 3, function (Grid\Filter $filter) {
                $filter->like('name', '模板名称');
            });

            $filter->column(1 / 3, function (Grid\Filter $filter) {
                $filter->equal('name', '计费方式')->select(Delivery::TYPE_MAP);
            });
        });

        $grid->column('shop.name', '所属店铺');
        $grid->column('name', '模板名称');
        $grid->column('type', '计费方式')->using(Delivery::TYPE_MAP);

        $grid->column('rules_count', '模板规则')->link(function () {
            return route('admin.mall.deliveries.rules.index', $this);
        }, '_self');
        $grid->column('created_at', '创建时间');

        return $grid;
    }

    public function form(): Form
    {
        $form = new Form(new Delivery());

        $this->shop($form)->required();
        $form->text('name', '模板名称')->required();
        $form->radioButton('type', '计费方式')
             ->options(Delivery::TYPE_MAP)
             ->default(Delivery::TYPE_BY_COUNT)
             ->required();

        return $form;
    }

    /**
     * Notes   : 选择运费模板
     * @Date   : 2021/5/11 11:36 上午
     * @Author : < Jason.C >
     * @param  \Illuminate\Http\Request  $request
     * @return mixed
     */
    public function ajax(Request $request)
    {
        $key = $request->get('q');

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

}