<?php

namespace App\Admin\Controllers;

use App\Admin\Actions\Grid\BatchProduct;
use App\Models\Product;
use App\Models\ProductCategory;
use App\Models\ProductSpec;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Layout\Content;
use Dcat\Admin\Layout\Row;
use Dcat\Admin\Show;
use Dcat\Admin\Http\Controllers\AdminController;
use Dcat\Admin\Widgets\Tab;
use Dingo\Api\Http\Request;
use function AlibabaCloud\Client\json;

class ProductController extends AdminController
{
    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Grid::make(Product::with(['cate','specs']), function (Grid $grid) {
            $grid->model()->orderByDesc('sort');
            $grid->column('id')->sortable();
            $grid->column('name')->label('info');
            $grid->column('cate_id')->display(function (){
                if($this->cate){
                    return $this->cate->name;
                }else{
                    return '';
                }
            })->label('success');
            $grid->column('cover_img')->image('',80);
            $grid->column('cases')->display(function (){
                $html = '';
                foreach ($this->cases as $case){
                    $html .= '<img data-action="preview-img" src="'.$case.'"
style="max-width:80px;max-height:80px;cursor:pointer"
class="img img-thumbnail">';
                }
                return $html;
            })->width(300);
            $grid->column('tech_param')->display(function (){
                $html = '';
                foreach ($this->tech_param as $key => $item){
                    $html .= "<a href='{$item['url']}' download target='_blank'>技术参数</a><br>";
                }
                return $html;
            });
            $grid->column('cad_model')->display(function (){
                $html = '';
                foreach ($this->cad_model as $key => $item){
                    $html .= "<a href='{$item['url']}' download target='_blank'>CAD模型</a><br>";
                }
                return $html;
            });
            $grid->column('cad_design')->display(function (){
                $html = '';
                foreach ($this->cad_design as $key => $item){
                    $html .= "<a href='{$item['url']}' download target='_blank'>CAD设计</a><br>";
                }
                return $html;
            });
            $grid->column('su_model')->display(function (){
                $html = '';
                foreach ($this->su_model as $key => $item){
                    $html .= "<a href='{$item['url']}' download target='_blank'>SU模型</a><br>";
                }
                return $html;
            });
            $grid->column('other')->display(function (){
                $html = '';
                foreach ($this->other as $key => $item){
                    $html .= "<a href='{$item['url']}' download target='_blank'>{$item['name']}</a><br>";
                }
                return $html;
            });
            $grid->column('is_opened')->switch();
            $grid->column('sort')->editable();
            $grid->column('created_at');
            $grid->column('spec','规格')->display(function (){
                $url = '/admin/product/'.$this->id.'/spec';
                return "<a href='$url'>规格管理</a>";
            });


            $grid->filter(function (Grid\Filter $filter) {
                $filter->panel();
                $filter->equal('cate_id')->select(function (){
                    return ProductCategory::select(['id','name'])->get()->pluck('name','id')->toArray();
                })->width(2);
                $filter->like('name')->width(2);

                //$filter->between('name')->datetime()->width(4);
            });

            $grid->batchActions([new BatchProduct()]);

            $grid->disableViewButton();

            $grid->export()
                ->titles([
                    'name'       => '产品名称',
                    'cate_name'  => '产品分类',
                    'cover_img'  => '产品截面图',
                    'cases_value'      => '案例',
                    'tech_param_value' => '技术参数文件',
                    'cad_model_value'  => 'CAD模型文件',
                    'cad_design_value' => 'CAD设计文件',
                    'su_model_value'   => 'SU模型文件',
                    'other_value'      => '其他文件',
                    'opened_value'  => '上架状态',
                    'sort'       => '排序(越大越靠前)',
                    'specs_value'      => '规格',
                ])->rows(function ($rows){
                    foreach ($rows as $index => &$row) {
                        $specs = [];
                        foreach ($row['specs'] as $spec){
                            $arr = [];
                            foreach ($spec['specs'] as $item){
                                $arr[] = "{$item['name']}(￥{$item['price']})";
                            }
                            $specs[] = $spec['name'].':('.implode(",",$arr).')';
                        }
                        $row['cate_name'] = $row['cate']['name'];
                        $row['cases_value'] = implode(";",$row['cases']);
                        $row['tech_param_value']   = implode(";", array_column($row['tech_param'],'url'));
                        $row['cad_model_value']  = implode(";",  array_column($row['cad_model'],'url'));
                        $row['cad_design_value']   = implode(";", array_column($row['cad_design'],'url'));
                        $row['su_model_value']  = implode(";", array_column($row['su_model'],'url'));
                        $row['other_value']  = implode(';',  array_column($row['other'],'url'));
                        $row['opened_value']  = config('global.bool_status')[$row['is_opened']];
                        $row['specs_value']  = implode(";",$specs);

                    }
                    return $rows;
                })
                ->csv()
                ->disableExportSelectedRow();
        });
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     *
     * @return Show
     */
    protected function detail($id)
    {
        return Show::make($id, new Product(), function (Show $show) {
            $show->field('id');
            $show->field('name');
            $show->field('cover_img');
            $show->field('cases');
            $show->field('origin_price');
            $show->field('sale_price');
            $show->field('sort');
            $show->field('is_opened');
            $show->field('tech_param');
            $show->field('cad_model');
            $show->field('cad_design');
            $show->field('su_model');
            $show->field('other');
            $show->field('created_at');
            $show->field('updated_at');
        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Form::make(Product::with(['specs']), function (Form $form) {
            $form->display('id');
            $cates = ProductCategory::select(['id','name'])->where('is_opened',1)->get()->toArray();
            /* @var Form $form*/
            $form->select('cate_id')
                ->options(array_column($cates,'name','id'))
                ->required();
            $form->text('name')->required();
            $form->image('cover_img','产品截面图（宽高比 0.9:1）')->saveFullUrl()
                ->uniqueName()->autoUpload()
                ->autoSave(false)
                ->removable(false)
                ->width(4)
                ->required();
            $form->multipleImage('cases','案例（宽高比 7.5:x）')->saveFullUrl()
                ->uniqueName()->autoUpload()
                ->autoSave(false)
                ->removable(false)
                ->width(4)->sortable();

            $form->table('tech_param', function (Form\NestedForm $table) {
                $table->url('url','链接');
            });
            $form->table('cad_model', function (Form\NestedForm $table) {
                $table->url('url','链接');
            });
            $form->table('cad_design', function (Form\NestedForm $table) {
                $table->url('url','链接');
            });
            $form->table('su_model', function (Form\NestedForm $table) {
                $table->url('url','链接');
            });
            $form->table('other', function (Form\NestedForm $table) {
                $table->text('name','名称')->required();
                $table->url('url','链接');
            });


            $form->radio('is_opened')->options(config('global.bool_status'))->default(1);
            $form->number('sort');
            $form->saving(function (Form $form) {
                $form->tech_param = $form->tech_param ?? [];
                $form->cad_model = $form->cad_model ?? [];
                $form->cad_design = $form->cad_design ?? [];
                $form->su_model = $form->su_model ?? [];
                $form->other = $form->other ?? [];
            });

            $form->disableViewButton();
            $form->disableDeleteButton();
            $form->disableListButton();
            $form->disableEditingCheck();
            $form->disableViewCheck();
            $form->disableCreatingCheck();
        });
    }

    public function product()
    {
        $cateId = \request()->input('q');

        $list = Product::where('cate_id', $cateId)
            ->select(['id', 'name as text'])
            ->get();

        $arr = [];
        foreach ($list as $key => $value) {
            $arr[] = ["id" => $value->id, "text" => $value->text];
        }

        return $arr;//返回数组到地区的option

    }
}
