<?php

namespace App\Admin\Controllers;

use App\Admin\Repositories\BaseProduct;
use Dcat\Admin\Admin;
use Dcat\Admin\Form;
use Dcat\Admin\Form\NestedForm;
use Dcat\Admin\Grid;
use Dcat\Admin\Layout\Content;
use Dcat\Admin\Show;
use Dcat\Admin\Http\Controllers\AdminController;
use App\Admin\Repositories\BaseProductCategory;
use App\Admin\Repositories\BaseProductImage;
use Illuminate\Http\Request;
use App\Libraries\CommonHelper;
class BaseProductController extends AdminController
{

    public function title()
    {
        return admin_trans( 'admin.products_list');
    }

    public function index(Content $content)
    {
        return $content
            ->header($this->title())
            ->description('')
            ->breadcrumb(['text'=>'list','url'=>''])
            ->body($this->grid());
    }

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Grid::make(BaseProduct::with(['baseProductCategory','images']), function (Grid $grid) {
            //默认分页条数
            $grid->paginate(config('admin.per_page'));

            $grid->column('id')->display(function () {
                return $this->_index+1;
            });
            $grid->column('title');
            $grid->column('sku');
            $grid->column('base_product_category.name',admin_trans_label('category_name'));
            $grid->column('images')->display(function ($images) {
                $images = $images->toArray();
                $dataImages = array_column($images, 'image_url');
                // 限制最多显示2个缩略图
                $dataImages = array_slice($dataImages, 0, 1);
                return CommonHelper::displayImage($dataImages,100);
            });
            $grid->column('order')->sortable();
            $grid->column('enabled')->switch();
            $grid->column('created_at')->sortable();
            $grid->column('updated_at')->sortable();
            // 筛选
            $grid->filter(function (Grid\Filter $filter) {
                $filter->panel();
                $filter->expand();
                $filter->equal('sku')->width(2);
                $filter->like('title')->width(2);
                $filter->equal('category_id',admin_trans_label('category_name'))->select(BaseProductCategory::selectOptions())->width(3);
                $filter->equal('enabled')->select(admin_trans_array(config('dictionary.enabled')))->width(2);
            });
            //排序
            $grid->model()->orderBy('created_at','desc');
            $grid->disableViewButton();
        });
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     *
     * @return Show
     */
    protected function detail($id)
    {
        return Show::make($id, BaseProduct::with(['baseProductCategory','images']), function (Show $show) {
            $show->field('title');
            $show->field('sku');
            $show->field('base_product_category.name',admin_trans_label('category_name'));
            $show->field('issuance_date');
            $show->field('parameters',admin_trans_label('attribute_name'))->as(function ($items) {
                if (is_array($items)) {
                    // 创建表格的表头
                    $table = '<table class="table table-bordered table-condensed">';
                    // 遍历数组并将数据填充到表格中
                    foreach ($items as $item) {
                        $table .= '<tr>';
                        $table .= '<td style="vertical-align: middle !important;width: 20%">' . $item['key'] . '</td>';    // 商品名称
                        $table .= '<td style="vertical-align: middle !important;">' . $item['value'] . '</td>'; // 数量
                        $table .= '</tr>';
                    }
                    $table .= '</table>';
                    return $table;
                }
                return ''; // 当没有数组数据时
            })->unescape();
            $show->field('images')->as(function ($images) {
                // 开始生成 HTML
                $dataImages = array_column($images, 'image_url');
                return CommonHelper::displayImage($dataImages,150);
            })->unescape();
            $show->field('content')->unescape();
            $show->field('seo_title');
            $show->field('seo_keywords');
            $show->field('seo_description');
            $show->field('order');
            $show->field('enabled')->using(admin_trans_array(config('dictionary.enabled')));
            $show->field('created_at');
            $show->field('updated_at');
        });
    }


    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Form::make(BaseProduct::with('images'), function (Form $form) {
            $form->select('category_id', admin_trans_label('category_name'))
                ->options(BaseProductCategory::selectOptions())
                ->required();
            $form->text('title')->required();
            $form->text('sku')->required();
            $form->date('issuance_date');
            $form->table('parameters',admin_trans_label('attribute_name'), function (Form\NestedForm $table) {
                $table->text('key')->required();
                $table->text('value')->required();
            });
            // 多图上传
            $form->multipleImage('images', admin_trans_label('images'))
                ->retainable()//禁止删OSS图
                ->sortable() // 可拖动排序
                ->removable() // 可移除图片
                ->autoUpload() // 自动上传
                ->uniqueName()
                ->limit(config('admin.upload.oss_image.limit'))
                ->accept(config('admin.upload.oss_image.accept'))
                ->maxSize(config('admin.upload.oss_image.max_size'))
                ->dir(config("admin.upload.directory.image").'/product/'.date("Ymd"))
                ->customFormat(function ($images) {
                    // 数据格式化为数组['1.jpg','2.jpg'] 编辑时用到
                    return array_column($images, 'image_url');
                })
                ->saving(function ($images) use ($form) {
                    $id = $form->getKey();
                    $reslut =  BaseProductImage::formatData($id,$images);
                    return $reslut;
                });
            $form->editor('content');
            $form->text('seo_title');
            $form->text('seo_keywords');
            $form->text('seo_description');
            $form->number('order')
                ->default(0)
                ->rules('numeric');
            $form->switch('enabled')->default(1);

            //插入参数联动JS
            $this->addParametersJs();
            //新建时插入JS
            $form->creating(function (Form $form) {
                CommonHelper::seoReplace('title',false);
            });
            //保存前回调
            $form->saving(function ($form) {
                //检查sku是否重复
                $baseProduct = new BaseProduct();
                if ($form->isCreating()) {
                    $count = $baseProduct->model()->where('sku', $form->sku)->count();
                } else {
                    $count = $baseProduct->model()->where('sku', $form->sku)->where('id', '!=', $form->getKey())->count();
                }
                if ($count > 0) {
                    return $form->response()->error('sku already exists');
                }
            });
        });
    }

    /*
     * 以json型式返回产品参数
     */
    public static function parameter(Request $request)
    {
        $id = $request->query('q');
        $content = BaseProductCategory::getParameter($id);
        return $content;
    }

    /**
     * 分类与参数联动JS
     * @return void
     */
    private function addParametersJs()
    {
        $prefix = config('admin.route.prefix');
        //插入JS
        Admin::script(
            <<<JS
var fill_param = function (key,val) {
    lastForm = $(".has-many-table-parameters-form:last");
    lastForm.find('input').eq(0).val(key);
    lastForm.find('input').eq(1).val(val);
}

$('select[name="category_id"]').on('change', function() {
    var category_id = $(this).val();
    // 清空现有的表格行
    $('.has-many-table-parameters-form').remove();
    if (category_id > 0) {
        $.ajax({
            url: '/{$prefix}/base-product/parameter',
            data: { q: category_id},
            dataType: 'json',
            type: 'GET',              // GET
            success: function(data) { // success
                if (Array.isArray(data) && data.length === 0) {
                    return null;
                }
                // 动态添加新数据到表格
                $.each(data, function(index, item) {
                    $(".has-many-table-parameters").find(".add").click();
                    fill_param(item.key,item.value);
                });
            },
            error: function(error) {  // 错误时执行的代码
                console.log('error:', error);
            }
        });
    }

});
JS
        );
    }
}
