<?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\Support\Arr;
use Illuminate\Support\MessageBag;
use Illuminate\Support\Str;
use Modules\Mall\Http\Controllers\Admin\Action\Goods\Down;
use Modules\Mall\Http\Controllers\Admin\Action\Goods\SkuAction;
use Modules\Mall\Http\Controllers\Admin\Action\Goods\Up;
use Modules\Mall\Models\Brand;
use Modules\Mall\Models\Category;
use Modules\Mall\Models\Delivery;
use Modules\Mall\Models\Goods;
use Modules\Mall\Models\Shop;
use Modules\Mall\Models\Tag;

class GoodsController extends AdminController
{

    use WithUploads,
        WithShop;

    protected $title = '商品管理';

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

        $grid->quickSearch('id')->placeholder('商品编号快速搜索');

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

            $filter->column(1 / 3, function (Grid\Filter $filter) {
                $filter->like('name', '商品名称');
                $filter->equal('channel', '类型')->select(Goods::Channels);
            });
            $filter->column(1 / 3, function (Grid\Filter $filter) {
                $filter->equal('shop_id', '所属店铺')->select(function ($shopId) {
                    if ($shopId) {
                        return Shop::where('id', $shopId)->pluck('name', 'id');
                    }
                })->ajax(route('admin.mall.shops.ajax'));
            });
            $filter->column(1 / 3, function (Grid\Filter $filter) {
                $filter->equal('category_id', '分类')->select(Category::shown()->pluck('name', 'id'));
            });
        });

        $grid->actions(function (Grid\Displayers\Actions $actions) {
            $actions->disableView();
            $actions->disableDelete();

            if ($actions->row->status == Goods::STATUS_UP) {
                $actions->add(new Down());
            }
            if ($actions->row->status == Goods::STATUS_DOWN) {
                $actions->add(new Up());
            }
            if ($actions->row->type == Goods::TYPE_MULTIPLE) {
                $actions->add(new SkuAction());
            }
        });
        $grid->model()
            ->with(['category', 'shop', 'delivery'])
            ->withCount(['specs', 'skus'])
            ->orderByDesc('updated_at');

        $grid->column('id', '#ID#');
        $grid->column('brand.name', '品牌名称');
        $grid->column('category.name', '商品分类');
//        $grid->column('tags', '标签')
//             ->pluck('name')
//             ->label();
        $grid->column('shop.name', '所属店铺');
        $grid->column('name', '商品名称');
        $grid->column('type', '规格类型')->using(Goods::TYPE_MAP);
        $grid->column('sales', '销量');
        $grid->column('original_price', '原价');
        $grid->column('channel', '类型')->using(Goods::Channels)->label();

        $grid->column('规格属性')
            ->display(function () {
                if ($this->type === Goods::TYPE_MULTIPLE) {
                    return $this->specs_count;
                }
            })
            ->link(function () {
                return route('admin.mall.goods.specs.index', $this);
            }, '_self');
        $grid->column('价格条目')
            ->display(function () {
                return $this->skus_count;
            })
            ->link(function () {
                return route('admin.mall.goods.skus.index', $this);
            }, '_self');
        $grid->column('delivery.name', '运费模板');
        $grid->column('status', '状态')->switch([
            'on'  => ['value' => 1, 'text' => '上架', 'color' => 'primary'],
            'off' => ['value' => 3, 'text' => '下架', 'color' => 'default'],
        ]);
        //        $grid->column('status', '状态')->display(function () {
        //            return $this->status_text;
        //        });
        $grid->column('created_at', '创建时间');

        return $grid;
    }

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

        $form->text('name', '商品名称')->required();
        $form->textarea('description', '商品简介')->required();

        $this->shop($form)->required();

        $form->select('category_id', '商品分类')
            ->options(function ($categoryId) {
                $category = Category::find($categoryId);
                if ($category) {
                    return [$category->id => $category->name];
                }
            })
            ->ajax(route('admin.mall.categories.ajax'))
            ->required();
        $form->select('brand_id', '所属品牌')
            ->options(function ($brandId) {
                $brand = Brand::find($brandId);
                if ($brand) {
                    return [$brand->id => $brand->name];
                }
            })
            ->ajax(route('admin.mall.brands.ajax'))
            ->required();
//        $form->multipleSelect('tags', '商品标签')
//             ->options(function ($tagIds) {
//                 if ($tagIds) {
//                     return Tag::find($tagIds)->pluck('name', 'id');
//                 }
//             })
//             ->ajax(route('admin.mall.tags.ajax'));
        $this->cover($form);
        $this->pictures($form);
        $states = [
            'on'  => ['value' => 1, 'text' => '是', 'color' => 'success'],
            'off' => ['value' => 0, 'text' => '否', 'color' => 'danger'],
        ];
        $form->switch('is_post_sale', '是否允许售后')->states($states)->default(1);
        $form->radioButton('deduct_stock_type', '库存扣减')
            ->default(1)
            ->options(Goods::DEDUCT_STOCK_MAP)
            ->required();
        $form->radioButton('pay_type', '支付方式')
            ->default(1)
            ->options(Goods::PAY_TYPE_MAP)
            ->required();
        $form->select('delivery_id', '运费模板')
            ->options(function ($deliveryId) {
                $delivery = Delivery::find($deliveryId);
                if ($delivery) {
                    return [$delivery->id => $delivery->name];
                }
            })
            ->ajax(route('admin.mall.deliveries.ajax'))
            ->required();
        $form->currency('original_price', '展示原价')
            ->default(0)
            ->help('仅作展示使用');
        $form->radioButton('channel', '商品类型')
            ->options(Goods::Channels)
            ->required();
        $form->radioButton('type', '规格类型')
            ->options(Goods::TYPE_MAP)
            ->default(Goods::CHANNEL_NORMAL)
            ->required()
            ->when(Goods::TYPE_SINGLE, function (Form $form) {
                $form->hasMany('skus', '单规格', function (Form\NestedForm $form) {
                    $form->currency('price', '销售价格')
                        ->default(0)
                        ->required();
                    $form->hidden('score', '积分')
                        ->default(0)
                        ->required();
                    $form->hidden('assets', '资产')
                        ->default(0)
                        ->required();
                    $form->number('stock', '商品库存')
                        ->default(0)
                        ->required();
                    $form->text('weight', '商品重量')
                        ->default(0)
                        ->setWidth(2)
                        ->required();
                });
            })
            ->when(Goods::TYPE_MULTIPLE, function ($form) {

            })
            ->default(function () use ($form) {
                return $form->isCreating() ? Goods::TYPE_SINGLE : '';
            });
        $form->ueditor('content', '商品详情')->required();

        $form->switch('status', '状态')
            ->states([
                'on'  => ['value' => 1, 'text' => '上架', 'color' => 'success'],
                'off' => ['value' => 3, 'text' => '下架', 'color' => 'danger'],
            ])
            ->default(1);

        $form->ignore(['single']);

        $form->saving(function (Form $form) {
            if ($form->type === Goods::TYPE_SINGLE) {
                $form->skus = [Arr::first($form->skus)];
            }

            if ($form->channel == Goods::CHANNEL_FREE && $form->isCreating()) {
                $hasOne = Goods::where('channel', Goods::CHANNEL_FREE)->exists();
                if ($hasOne) {
                    $error = new MessageBag([
                        'title'   => '错误',
                        'message' => '免费产品只有一个',
                    ]);

                    return back()->withInput()->with(compact('error'));
                }
            }

            $form->content = Str::of(request()->get('content'))->replace('style=""', '');
        });


        return $form;
    }

}
