<?php

namespace App\Distributor\Controllers;


use App\Distributor\Actions\MenuShow;
use App\Distributor\Repositories\DistProduct;
use App\Distributor\Repositories\DistProductCategory;
use App\Distributor\Repositories\DistVideoCategory;
use App\Distributor\Repositories\SiteMenu;
use App\Distributor\Repositories\SitePages;
use App\Distributor\Repositories\SitePagesTag;
use App\Libraries\CommonHelper;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Layout\Content;
use Dcat\Admin\Admin;
use Dcat\Admin\Tree;
use Dcat\Admin\Layout\Row;
use Dcat\Admin\Widgets\Box;
use function Symfony\Component\String\u;
use Dcat\Admin\Layout\Column;

class SiteMenuController extends AdminDistController
{

    /**
     * page index
     */
    public function index(Content $content)
    {
        $location = isset($_GET['location']) ? intval($_GET['location']) : 0;
        //保存临时变量
        setTempValue('location', $location);
        //翻译
        $header = admin_trans( 'admin.top_menu');
        if ($location == 1) {
            $header = admin_trans( 'admin.footer_menu');
        }
        return $content
            ->header($header)
            ->description('')
            ->body($this->tree($location));
    }



    private function tree($location)
    {
        $thisObject = $this;
        return function (Row $row) use ($location, $thisObject) {
            $tree = new Tree(new SiteMenu);
            //两层
            $tree->maxDepth(2);
            //标题显示
            $tree->branch(function ($branch) {
                return $branch['title'];
            });
            //是否显示操作
            $tree->actions(function (Tree\Actions $actions) {
                $actions->prepend(new MenuShow());
            });
            //按钮
            $tree->disableEditButton();
            $tree->disableCreateButton();
            $tree->showQuickCreateButton();
            $tree->showQuickEditButton();
            $row->column(6, $tree);
            //增加JS，使新增与编辑带location
            $paramsUrl = 'location='.$location;
            CommonHelper::replaceAddEditerUrl('.tree-quick-create', '.tree-quick-edit', $paramsUrl);
            //主页权限
            $tree->query(function ($model) use ($location) {
                return $model->where('dist_id', getDistributorId())->where('menu_location', $location);
            });
        };
    }



    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        $location = isset($_GET['location']) ? intval($_GET['location']) : 0;
        $thisObject = $this;
        return Form::make(new SiteMenu(), function (Form $form) use ($thisObject,$location) {
            $menuConfig = $form->model()->menu_config;
            //$menuConfig = json_decode($menuConfig,true);
            //父ID
            $form->select('parent_id', admin_trans_label('parent_id'))
                ->options(SiteMenu::selectOptions(function ($query) use ($location) {
                    $query =  $query->where('menu_location',$location)->where('dist_id', getDistributorId())->orderBy('order', 'asc');
                    return $query;
                }))->required();
            //标题
            $form->text('title')->required();
            //图片
            $form->image("image_url", admin_trans_label('images'))
                ->retainable()//禁止删OSS图
                ->autoUpload()
                ->uniqueName()
                ->accept(config('distributor.upload.oss_image.accept'))
                ->maxSize(config('distributor.upload.oss_image.max_size'))
                ->dir(config("distributor.upload.directory.image").'/menu/'.date("Ymd"));
            //类型
            $form->select('menu_type')->options(admin_trans_array(config('dictionary.menu_type')))->required()
                ->when(1, function (Form $form) use ($menuConfig,$thisObject) {
                    //选择集合类型
                    $form->select('collections_type')->options(admin_trans_array(config('dictionary.collections_type')))
                        ->value($thisObject->getArrayValue('collections_type',$menuConfig))
                        ->when(0, function (Form $form) use ($menuConfig,$thisObject) {
                            //产品分类
                            $form->select('product_category')->options(DistProductCategory::selectOptions())->value($thisObject->getArrayValue('product_category',$menuConfig));
                        })->when(1, function (Form $form) use ($menuConfig,$thisObject) {
                            //文章标签
                            $form->select('pages_tag')->options('api/tag')->value($thisObject->getArrayValue('pages_tag',$menuConfig));
                        })->when(2, function (Form $form) use ($menuConfig,$thisObject) {
                            //视频
                            $form->select('video_category')->options(DistVideoCategory::selectOptions())->value($thisObject->getArrayValue('video_category',$menuConfig));
                        });
                })
                ->when(2, function (Form $form) use ($menuConfig,$thisObject) {
                    //选择产品
                    $form->select('product',admin_trans_label('select_product'))->options('api/products')
                        ->value($thisObject->getArrayValue('product',$menuConfig))
                        ->help('The latest 30 products are displayed by default, and you can also use the search function to find all products.');
                })
                ->when(3, function (Form $form) use ($menuConfig,$thisObject) {
                    //选择页面
                    $form->select('pages',admin_trans_label('select_pages'))->options('api/pages')
                        ->value($thisObject->getArrayValue('pages',$menuConfig))
                        ->help('The latest 30 published posts are displayed by default, and you can also use the search function to find all posts.');
                })
                ->when(10, function (Form $form) use ($menuConfig,$thisObject) {
                    //url
                    $form->text('url')->value($thisObject->getArrayValue('url',$menuConfig));
                })
                ->when(4, function (Form $form) use ($menuConfig,$thisObject) {
                    $form->select('landing_page',admin_trans_label('landing_page'))->options('api/landing-pages')
                        ->value($thisObject->getArrayValue('landing_page',$menuConfig));
                })->when(5, function (Form $form) use ($menuConfig,$thisObject) {
                    $form->select('videos',admin_trans_label('videos'))->options('api/videos')
                        ->value($thisObject->getArrayValue('videos',$menuConfig));
                });

            //显示
            $form->switch('show')->default(1);
            //隐藏字段
            $form->textarea('menu_config')->hideInDialog();
            $form->hidden('menu_location')->value($location);
            $form->hidden('uri');
            $form->hidden('dist_id'); // 隐藏dist_id字段,用于保存
            //以下字段不保存
            $form->ignore(['collections_type','product_category','pages_tag','product','pages','url','landing_page','videos','video_category']);
            //保存事件
            $form->submitted(function (Form $form) use ($thisObject) {
                $result = $thisObject->convertMenuConfig($form);
                $form->uri = $result['uri'];
                $form->menu_config = $result['menuConfig'];
            });
            //保存前，强制写死dist_id
            $form->saving(function (Form $form) {
                $form->dist_id =getDistributorId();
            });
        });
    }

    protected function convertMenuConfig(Form $form) {
        $menuConfig = [
            'collections_type' => $form->input('collections_type'),
            'product_category' => $form->input('product_category'),
            'video_category' => $form->input('video_category'),
            'pages_tag' => $form->input('pages_tag'),
            'product' => $form->input('product'),
            'pages' => $form->input('pages'),
            'url' => $form->input('url'),
            'landing_page' => $form->input('landing_page'),
            'videos' => $form->input('videos'),
        ];
        $menuType = $form->input('menu_type');
        $uri = SiteMenu::generateUri($menuType,$menuConfig);
        return ['uri'=>$uri,'menuConfig'=>$menuConfig];
    }
    protected function getArrayValue($key,$arr) {
        if (isset($arr[$key])) {
            return $arr[$key];
        }
        return "";
    }

    /*
     * 重写store
     */
    public function store()
    {
        $location = getTempValue('location');
        return $this->form()->store(null,'/site-menu?location='.$location);
    }
}
