<?php

namespace App\Admin\Controllers\Content;

use App\Http\Controllers\Controller;
use App\Models\Help;
use App\Models\HelpCategory;
use Encore\Admin\Admin;
use Encore\Admin\Controllers\HasResourceActions;
use Encore\Admin\Facades\Admin as userAdmin;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Show;
use Illuminate\Http\Request;

class HelpController extends Controller
{
    use HasResourceActions;

    /**
     * Index interface.
     *
     * @param Content $content
     * @return Content
     */
    public function index(Content $content)
    {
        return $content
            ->header('帮助中心')
            ->description(' ')
            ->body($this->grid());
    }

    /**
     * Show interface.
     *
     * @param mixed $id
     * @param Content $content
     * @return Content
     */
    public function show($id, Content $content)
    {
        return $content
            ->header('帮助中心')
            ->description(' ')
            ->body($this->detail($id));
    }

    /**
     * Edit interface.
     *
     * @param mixed $id
     * @param Content $content
     * @return Content
     */
    public function edit($id, Content $content)
    {
        return $content
            ->header('帮助中心')
            ->description(' ')
            ->body($this->form()->edit($id));
    }

    /**
     * Create interface.
     *
     * @param Content $content
     * @return Content
     */
    public function create(Content $content)
    {
        return $content
            ->header('帮助中心')
            ->description(' ')
            ->body($this->form());
    }

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        $grid = new Grid(new Help);

        $grid->model()->orderBy('list_order', 'desc')->orderBy('created_at', 'desc');

        $grid->title('标题')->display(function () {
            $cate = HelpCategory::where(array('id'=>$this->type_id))->first();
            if ($this->parent_id=='0') {
                $params = '?type_id=&parent_id='.$this->type_id;
            } else {
                $params = '?type_id='.$this->type_id.'&parent_id='.$this->parent_id;
            }
            $title_url = url(admin_base_path().'/content/help/index'.$params);
            return '<a href='.$title_url.' style="color: #006699;">['.$cate->category_name.']</a>'.' '.$this->title;
        })->width(450);
        $grid->list_order('排序');
        $grid->click('点击量');
        $grid->created_at('添加时间');

        $grid->tools(function (Grid\Tools $tools) {
            $tools->disableRefreshButton();
        });
        //新增按钮
        if (userAdmin::user()->can('content_help_list_create')) {
            $grid->disableCreateButton(false);
        }
        //批量删除
        if (userAdmin::user()->can('content_help_list_delete')) {
            $grid->tools(function ($tools) {
                $tools->batch(function ($batch) {
                    $batch->disableDelete(false);
                });
            });
        } else {
            $grid->disableRowSelector();
        }
        $grid->actions(function ($actions) {
            if (userAdmin::user()->can('content_help_list_edit')) {
                $actions->disableEdit(false);
            }
            if (userAdmin::user()->can('content_help_list_delete')) {
                $actions->disableDelete(false);
            }
        });

        $this->script = <<<EOT
            $('select[name="type_id"]').parent().parent().attr('id','type_div');
            $('select[name="parent_id"]').change(function(){
                if($('select[name="parent_id"]').val()){
                    $('#type_div').css('display','block');
                }else{
                    $('#type_div').css('display','none');
                    $('#type_div select[name="type_id"]').val('');
                }
            });            
            $(document).ready(function(){
                //判断是否显示子分类
                var \$children = $('select[name="parent_id"]').val();
                if(\$children){
                    $('#type_div').css('display','block');
                }else{
                    $('#type_div').css('display','none');
                }
            });
EOT;
        Admin::script($this->script);
        $grid->filter(function ($filter) {
            $filter->disableIdFilter();
            $filter->equal('ID', 'ID');
            $filter->like('title', '标题');
            $cate_option = HelpCategory::where(array('parent_id'=>0))->OrderBy('list_order', 'desc')->OrderBy('created_at', 'desc')->get()->pluck('category_name', 'id');
            $cate_option = $cate_option->toArray();
            $cate_option = array(''=>'不限')+$cate_option;
            $filter->where(function ($query) {
                $query->where('parent_id', '=', "{$this->input}")->orWhere('type_id', '=', "{$this->input}");
            }, '帮助分类', 'parent_id')->select($cate_option)->load('type_id', 'childCategory', 'id', 'category_name');
            $pid = \Illuminate\Support\Facades\Request::input('parent_id');
            if ($pid) {
                $child_option = HelpCategory::where(array('parent_id'=>$pid))->OrderBy('list_order', 'desc')->OrderBy('created_at', 'desc')->get()->pluck('category_name', 'id')->toArray();
                $child_option = array(''=>'不限')+$child_option ;
            } else {
                $child_option = array(''=>'不限');
            }
            $filter ->equal('type_id', '子分类')->select($child_option);
        });
        return $grid;
    }

    public function childCategorys(Request $request)
    {
        $parent_id = $request->get('q');
        $rst = HelpCategory::where('parent_id', $parent_id)->get(['id', 'category_name'])->toArray();
        $pre_arr = array('id'=>'','category_name'=>'不限');
        array_unshift($rst, $pre_arr);
        return collect($rst);
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     * @return Show
     */
    protected function detail($id)
    {
        $show = new Show(Help::findOrFail($id));

        $show->id('ID');
        $show->title('标题');
        /*$show->show_category()->category_name('所属分类');*/
        $show->show_category("所属分类")->as(function ($show_category) {
            return $show_category->category_name;
        });
        $show->content('内容')->as(function ($content) {
            return $content?$content:'&nbsp;';
        })->setEscape(false);
        $show->list_order('排序');
        $show->click('点击量');
        $show->created_at('添加时间');
        $show->updated_at('更新时间');

        /*$show->panel()
            ->tools(function ($tools) {
                $tools->disableEdit();
                $tools->disableDelete();
            });*/

        return $show;
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        $form = new Form(new Help);

        $form->text('title', '标题')->rules('required|max:50', array('required'=>'标题不能为空。','max'=>'标题长度不能超过50。'))->setWidth(4)->setMustMark();
        $form->number('list_order', '排序')->min(0)->default(0)->rules('required', array('required'=>'排序不能为空。'))
             ->attribute('maxlength', '10')->help('数字越大越靠前')->setMustMark();
        $cate_option = HelpCategory::selectOptions(function ($query) {
            return $query->orderBy('list_order', 'desc')->orderBy('created_at', 'desc');
        });
        unset($cate_option[0]);
        $form->select('type_id', '帮助分类')->options($cate_option)
             ->default(key($cate_option))->rules('required', array('required'=>'请选择帮助分类。'))
             ->setWidth(4)->setMustMark();
        $form->editor('content', '内容')->rules('required', array('required'=>'内容不能为空。'))->setMustMark();
        $form->hidden('parent_id');
        $form->hidden('click');
        $form->saving(function (Form $form) {
            if (!$id = $form->model()->id) {
                $form->click = 0;
            }
            $type_info = HelpCategory::find($form->type_id);
            $form->parent_id = $type_info->parent_id;
        });

        $form->footer(function ($footer) {
            $footer->disableViewCheck();
            $footer->disableEditingCheck();
            $footer->disableCreatingCheck();
            $footer->disableReset();
        });
        $form->tools(function (Form\Tools $tools) {
            $tools->disableDelete();
            $tools->disableView();
        });
        return $form;
    }
}