<?php

namespace Modules\Project\Http\Controllers\Admin;

use Modules\Project\Entities\Goods;
use Modules\Project\Entities\GoodsList;
use Modules\Project\Entities\GoodsSpec;
use Modules\Project\Entities\Transport;
use Modules\Project\Services\GoodsService;
use SMG\Admin\Controllers\ModelForm;
use SMG\Admin\Facades\Admin;
use SMG\Admin\Form;
use SMG\Admin\Grid;
use SMG\Admin\Layout\Content;
use SMG\Support\Admin\Services\CustomAttributeService;

class GoodsController
{
    use ModelForm;

    protected $casts = [
        'extra' => 'json',
    ];

    /**
     * Index interface.
     *
     * @return Content
     */
    public function index()
    {
        return Admin::content(function (Content $content) {
            $content->body($this->grid());
        });
    }

    public function grid()
    {
        $grid = Admin::grid(Goods::class, function (Grid $grid) {
            $grid->id('ID');

            $grid->title('标题');

            $grid->category('分类')->display(function ($data) {
                return "<span class='label label-warning'>{$data['name']}</span>";
            });

            $grid->brand('品牌')->display(function ($data) {
                return "<span class='label label-warning'>{$data['name']}</span>";
            });

            $grid->market_price('市场价格');

            $grid->selling_price('实际价格');

            $grid->goods_stock('产品库存');

            $grid->sort('排序值');

            $states = [
                'on'  => ['value' => 1, 'text' => '是', 'color' => 'primary'],
                'off' => ['value' => 2, 'text' => '否', 'color' => 'default'],
            ];

            $grid->hot('热门')->switch($states);

            $grid->fine('精品')->switch($states);
        });

        $grid->enableFilter();

        $grid->filter(function ($filter) {
            $filter->disableIdFilter();

            $filter->like('title', '标题');

            Goods::addCategoryFilter($filter, 'category', '分类');
        });

        return $grid;
    }

    /**
     * Edit interface.
     *
     * @param $id
     *
     * @return Content
     */
    public function edit($id)
    {
        return Admin::content(function (Content $content) use ($id) {
            $content->header('编辑');

            $content->description('编辑');

            $form = $this->form()->edit($id);

            $content->body($form);
        });
    }

    /**
     * Create interface.
     *
     * @return Content
     */
    public function create()
    {
        return Admin::content(function (Content $content) {
            $content->header('新增');

            $content->description('新增');

            $content->body($this->form());
        });
    }

    public function form()
    {
        return Admin::form(Goods::class, function (Form $form) {
            $form->display('id', 'ID');

            $form->text('title', '标题')->rules('required');

            CustomAttributeService::setForm($form, 'common');

            $form->image('cover_picture', '封面图')->rules('required')->help('图片尺寸：450*450')->uniqueName();

            $pictures = $form->multipleImage('pictures', '图片')->help('图片尺寸：750*750')->removable();

            if (!request()->route('good')) {
                $pictures->rules('required');
            }

            $options = Goods::getRootSelectTree('category');

            $form->select('category_id', '分类')->options($options)->rules('required');

            $form->currency('market_price', '市场价格')->symbol('￥');

            $form->currency('selling_price', '实际价格')->symbol('￥');

            /*
            if (request()->route('good')) {
                $form->display('goods_stock', '产品库存');

                //$form->number('goods_stock', '产品库存')->min(0);
            }
            */

            $form->number('goods_stock', '产品库存')->min(0);

            $form->number('sort', '排序值')->min(1)->max(255)->default(100)->help('数字越小，排序越前');

            $form->editor('description', '商品描述');

            /*

            $form->select('transport_id', '快递模板')->options($this->transport());

            $form->embeds('transport_value', '', function ($form) {
                $form->text('weight', '商品重量')->default(0)->rules('required')->help('单位千克');
            });

            */

            $states = [
                'on'  => ['value' => 1, 'text' => '是', 'color' => 'primary'],
                'off' => ['value' => 0, 'text' => '否', 'color' => 'default'],
            ];

            $form->switch('hot', '热门商品')->states($states)->default(0);

            $form->switch('fine', '精品商品')->states($states)->default(0);

            $form->display('created_at', '创建时间');

            $form->display('updated_at', '修改时间');

            $form->saved(function (Form $form) {
                $product_spec = json_decode($form->spec_param, true);

                if (is_array($product_spec)) {
                    $form->model()->goodsList()->delete();

                    $data = [];

                    $stock = 0;

                    foreach ($product_spec['products'] as $k => $v) {
                        $tmp = [];

                        $tmp['spec'] = json_encode($v['spec']);

                        $tmp['market_price'] = $v['price'];

                        $tmp['selling_price'] = $v['price'];

                        $tmp['goods_stock'] = $v['stock'];

                        $stock = $stock + $tmp['goods_stock'];

                        $tmp['goods_sale'] = 0;

                        $tmp['uuid'] = GoodsService::getSpecUuid($form->model()->id, $v['spec']);

                        $data[] = new GoodsList($tmp);
                    }

                    $form->model()->goodsList()->saveMany($data);

                    if ($form->model()->goods_stock != $stock) {
                        $form->model()->goods_stock = $stock;

                        $form->model()->save();
                    }
                }
            });
        });
    }

    protected function transport()
    {
        $list = Transport::all();

        $res = [];

        foreach ($list as $v) {
            $res[$v->id] = $v->name;
        }

        return $res;
    }

    public function getGoodsCategory()
    {
        $options = Goods::getRootSelectTree('category');

        $res = [];

        foreach ($options as $k => $v) {
            $res[] = [

                'id' => $k,

                'text' => $v,

            ];
        }

        /*
        $res [] = [
            'id' => '-100',
            'text' => '品牌',
        ];
        */

        return $res;
    }
}
