<?php

namespace App\Distributor\Controllers;

use App\Admin\Repositories\BaseProductImage;
use App\Distributor\Actions\Extensions\DistProductImport;
use App\Distributor\Repositories\DistAdminUsersSetting;
use App\Distributor\Repositories\DistProduct;
use App\Distributor\Repositories\DistProductCategory;
use App\Distributor\Repositories\DistProductImage;
use App\Libraries\CommonHelper;
use Dcat\Admin\Admin;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Http\Controllers\AdminController;
use Dcat\Admin\Layout\Content;
use Dcat\Admin\Show;
use Illuminate\Http\Request;

class DistProductController extends AdminDistController
{
    protected function title()
    {
        return admin_trans('admin.product');
    }
    /**
     * page index
     */
    public function index(Content $content)
    {
        return $content
            ->header(admin_trans( 'admin.products_list'))
            ->description(admin_trans('admin.all'))
            ->description('')
            //->breadcrumb(['text'=>'Product Management','url'=>''])

            ->body($this->grid());

    }


    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {

        return Grid::make(DistProduct::with(['distProductCategory','images']), function (Grid $grid)  {
            //默认分页条数
            $grid->paginate(config('admin.per_page'));
            $grid->model()->where('dist_id', getDistributorId());
            $grid->column('id')->display(function () {
                return $this->_index+1;
            });
            $grid->column('title');
            $grid->column('sku');

            $grid->column('dist_product_category.name',admin_trans_label('category_name'));
            $grid->column('images')->display(function ($images) {
                $images = $images->toArray();
                $dataImages = array_column($images, 'image_url');
                // 限制最多显示1个缩略图
                $dataImages = array_slice($dataImages, 0, 1);
                return CommonHelper::displayImage($dataImages,100);
            });
            $grid->column('order')->sortable();
            $grid->column('enabled')->switch();
            $grid->column('status')->using(admin_trans_array(config('dictionary.dist_product_status')))->label([
                -1 => 'danger',
                0 => 'gray',
                1 => 'orange1',
                2 => 'success',
            ])->display(function($status) {
                if ($this->status == -1) {
                    return '<span  class="status-popover" data-container="body" data-toggle="popover" data-placement="top" data-content="'.$this->review_reply.'">'.$status.'</span>';
                }
                return $status;
            });
            $grid->column('created_at')->sortable();
            //$grid->column('updated_at')->sortable();
            // 筛选
            $grid->filter(function (Grid\Filter $filter) {
                $filter->panel();
                $filter->expand();
                $filter->like('title')->width(2);
                $filter->equal('sku')->width(2);
                $filter->equal('category_id',admin_trans_label('category'))->select(DistProductCategory::selectOptions())->width(3);
                $filter->equal('enabled', admin_trans_label('enabled'))->select(admin_trans_array( config('dictionary.enabled')))->width(2);
            });
            //排序
            $grid->model()->orderBy('created_at', 'desc')->orderBy('id', 'desc');
            // 传入数组
            $grid->tools([
                new DistProductImport(),
            ]);
            //按钮
            //$grid->disableCreateButton();
            $grid->disableViewButton();
            $this->addGridJS();
        });

    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     *
     * @return Show
     */
    protected function detail($id)
    {
        return Show::make($id, DistProduct::with(['distProductCategory','images']), function (Show $show) {
            // 比较 dist_id 和 getDistributorId()，如果不相同则返回 404
            if ($show->model()->dist_id !== getDistributorId()) {
                abort(404);
            }
            $show->field('title');
            $show->field('sku');
            $show->field('dist_product_category.name',admin_trans_label('category_name'));
            $show->field('keywords');
            $show->field('description');
            $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('slug',admin_trans_label('url_and_handle'))->as(function ($value) {
                return getSiteDomain().config('dictionary.site_url.products').'/'.$value;
            });
            $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(DistProduct::with('images'), function (Form $form) {
            $form->select('category_id', admin_trans_label('category_name'))
                ->options(DistProductCategory::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',admin_trans_field('key'))->required();
                $table->text('value',admin_trans_field('value'))->required();
            });
            // 多图上传
            $form->multipleImage('images', admin_trans_label('images'))
                ->retainable()//禁止删OSS图
                ->sortable() // 可拖动排序
                ->removable() // 可移除图片
                ->autoUpload() // 自动上传
                ->uniqueName()
                ->limit(config('distributor.upload.oss_image.limit'))
                ->accept(config('distributor.upload.oss_image.accept'))
                ->maxSize(config('distributor.upload.oss_image.max_size'))
                ->dir(config("distributor.upload.directory.image").'/product/'.date("Ymd"))
                ->customFormat(function () {
                    // 数据格式化为数组['1.jpg','2.jpg'] 编辑时用到
                    return array_column($this->images, 'image_url');
                })
                ->saving(function ($images) use ($form) {
                    $id = $form->getKey();
                    $reslut =  DistProductImage::formatData($id,$images);
                    return $reslut;
                });
            $form->editor('content');
            //SEO
            $form->text('seo_title');
            $form->text('seo_keywords');
            $form->text('seo_description');
            $form->text('slug',admin_trans_label('url_and_handle'))->width(4, 2)->prepend(getSiteDomain().config('dictionary.site_url.products').'/');
            $form->number('order')
                ->default(0)
                ->rules('numeric');
            $form->switch('enabled')->default(1);
            //隐藏字段
            $form->hidden('dist_id'); // 隐藏dist_id字段,用于保存
            $form->hidden('status');
            $form->hidden('review_reply');
            $form->hidden('action');

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

            //插入JS
            $this->addParametersJs();
            //提交前
            // 在保存时进行验证
            $form->saving(function (Form $form) {
                $form->dist_id =getDistributorId();//保存时直接写死dist_id
                $id = $form->getKey();
                //slug配置是否重复
                $form->slug=trim($form->slug);
                if ($form->slug != '') {
                    //把slug中的空格替换成-，多个空格在一起只用一个-，大写字母转换成小写
                    $form->slug = preg_replace('/\s+/', '-', $form->slug);
                    $form->slug = strtolower($form->slug);

                    if (DistProduct::isRepeatedSlug($id, $form->slug)) {
                        //slug重复
                        return $form->response()->error(admin_trans_label('url_repeated'));
                    }
                }
                //当slug为空时生成slug
                if ($form->slug == '') {
                    $form->slug = DistProduct::generateSlug($form->title, $id);
                }
                //seo_title不能为空
                if ($form->seo_title == '') {
                    $form->seo_title = $form->title;
                }
                //增加审核状态
                $action = isset($_POST['action']) ? $_POST['action'] : '';
                if ($form->isCreating()) {
                    if ($action == 'save') {
                        $form->status = 0;//待审核
                    } else {
                        $form->status = 1;//审核中
                    }
                } else {
                    if (($form->status == 0 || $form->status == -1) && $action == 'submit') {
                        $form->status = 1;//审核中
                    }
                }
            });
            //页面底部自定义
            $status = $form->model()->status ?? 0;
            $isCreating = $form->isCreating() ? 0 : 1;
            $form->builder()->footer()->view('distributor.form_custom.review-footer',['status'=>$status,'isCreating'=>$isCreating]);
            //插入JS
            $this->addReviewJS();
            //禁用按钮
            $form->disableViewCheck();
            $form->disableEditingCheck();
            $form->disableViewButton();
        });

    }


    /*
     * 以json型式返回产品参数
     */
    public static function parameter(Request $request)
    {
        $id = $request->query('q');
        $content = DistProductCategory::getParameter($id);
        return $content;
    }
    /**
     * 分类与参数联动JS
     * @return void
     */
    private function addParametersJs()
    {
        $prefix = config('admin.route.prefix');
        //插入JS
        Admin::script(
            <<<JS


JS
        );
    }

    /*
     * 用于点击按钮时，将按钮的 value 值设置到隐藏 input[name="action"] 的值，并提交表单
     */
    private function addReviewJS()
    {
        Admin::script(
            <<<JS
  $('.submit').click(function(e) {
    // 阻止默认提交行为（可选，视需求而定）
    e.preventDefault();
    // 获取当前按钮的 value
    var value = $(this).val();
    // 将 value 设置为隐藏 input[name="action"] 的值
    $('input[name="action"]').val(value);
    // 提交表单
    $(this).closest('form').trigger('submit');
  });
JS
        );
    }
    private function addGridJS()
    {
        Admin::script(
<<<JS
 $('.status-popover').popover({
    container: 'body',
     trigger: 'hover'
  })
JS
        );
    }
}
