<?php

namespace Modules\Mall\Http\Controllers\Admin;

use Encore\Admin\Form;
use Encore\Admin\Form\NestedForm;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Illuminate\Routing\Controller;
use Modules\Mall\Models\Goods;
use Modules\Mall\Models\GoodsSpec;

class SpecController extends Controller
{

    public function index(Content $content, Goods $good): Content
    {
        return $content
            ->header($good->name)
            ->description('属性列表')
            ->body($this->grid($good));
    }

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

        $grid->model()
             ->where('goods_id', $good->id)
             ->withCount('values');

        $grid->column('name', '属性名称');
        $grid->column('values_count', '属性值数量')
             ->link(function () use ($good) {
                 return route('admin.mall.goods.specs.values.index', [$good, $this]);
             }, '_self');

        return $grid;
    }

    public function create(Content $content, Goods $good): Content
    {
        return $content
            ->header($good->name)
            ->description('属性列表')
            ->body($this->form($good));
    }

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

        $form->text('name', '属性名称');
        $form->hidden('goods_id')->value($good->id);

        $form->hasMany('values', '属性值列表', function (NestedForm $form) {
            $form->text('value', '属性值');
        });

        return $form;
    }

    public function store(Goods $good)
    {
        return $this->form($good)->store();
    }

    public function edit(Content $content, Goods $good, GoodsSpec $spec): Content
    {
        return $content
            ->header($good->name)
            ->description('属性列表')
            ->body($this->form($good)->edit($spec->id));
    }

    public function update(Goods $good, GoodsSpec $spec)
    {
        return $this->form($good)->update($spec->id);
    }

}