<?php

namespace Modules\Mall\Http\Controllers\Admin;

use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Modules\Mall\Models\Delivery;
use Modules\Mall\Models\DeliveryRule;
use Modules\Mall\Models\Region;

class DeliveryRuleController extends AdminController
{

    protected $title = '模板规则';

    public function index(Content $content): Content
    {
        $delivery = Delivery::find(request()->delivery);

        return $content
            ->header($delivery->name)
            ->description('模板规则')
            ->body($this->grid($delivery));
    }

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

        $grid->model()->where('delivery_id', $delivery->id);

        if ($delivery->type === Delivery::TYPE_BY_COUNT) {
            $firstTitle      = '首件(个)';
            $additionalTitle = '续件';
        } else {
            $firstTitle      = '首重(Kg)';
            $additionalTitle = '续重';
        }

        $grid->column('regions', '配送区域')
             ->display(function () {
                 return Region::find($this->regions);
             })
             ->pluck('name')
             ->label();
        $grid->column('first', $firstTitle);
        $grid->column('first_fee', '运费(元)');
        $grid->column('additional', $additionalTitle);
        $grid->column('additional_fee', '续费(元)');

        return $grid;
    }

    public function edit($id, Content $content): Content
    {
        return $content
            ->title($this->title())
            ->description($this->description['edit'] ?? trans('admin.edit'))
            ->body($this->form()->edit(request()->rule));
    }

    public function update($id)
    {
        return $this->form()->update(request()->rule);
    }

    public function form(): Form
    {
        $delivery = Delivery::find(request()->delivery);

        if ($delivery->type === Delivery::TYPE_BY_COUNT) {
            $firstTitle      = '首件(个)';
            $additionalTitle = '续件';
        } else {
            $firstTitle      = '首重(Kg)';
            $additionalTitle = '续重';
        }

        $form = new Form(new DeliveryRule());

        $form->multipleSelect('regions', '配送区域')
             ->options(function ($regions) {
                 if ($regions) {
                     return Region::find($regions)->pluck('name', 'id');
                 }
             })
             ->ajax(route('admin.mall.regions.ajax'));
        $form->text('first', $firstTitle)
             ->required();
        $form->currency('first_fee')
             ->symbol('￥')
             ->required();
        $form->text('additional', $additionalTitle)
             ->required();
        $form->currency('additional_fee')
             ->required()
             ->symbol('￥');

        $form->hidden('delivery_id')->value($delivery->id);

        return $form;
    }

}