<?php

namespace App\Admin\Controllers\Content;

use App\Models\FeatureSort;
use App\Http\Controllers\Controller;
use Encore\Admin\Controllers\HasResourceActions;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Show;

class FeatureSortController extends Controller
{
    use HasResourceActions;

    /**
     * Index interface.
     *
     * @param Content $content
     * @return Content
     */
    public function index(Content $content)
    {

        if (request()->has('_expand_')) {
            $FeatureSort=FeatureSort::find(request()->get('_expand_'));
            if (!$FeatureSort || $FeatureSort->children->isEmpty()) {
                $data['has_children'] =0;
                return response()->json($data);
            }
            $data['has_children'] =1;
            $data['html']=view(
                'admin.grid.policy_category_expand',
                [
                    'parent_group'=>implode(" ", explode(",", request()->get('parent_group'))),
                    'key'=>request()->get('_expand_'),
                    'list'=>$FeatureSort->children,
                    'level'=>request()->get('level')+1,
                ]
            )->render();
            return response()->json($data);
        }
        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->editForm()->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 FeatureSort);
        $grid->model()->where('parent_id',0)->orderBy('category_order', 'desc');
        $grid->id('id');
        $grid->categoryname('名称')->ajaxExpand();
        $grid->admin_set('类型')->display(function ($admin_set) {
            if ($admin_set == 1) {
                return '系统分类';
            }else{
                return '自定义分类 ';
            }
        });
        $grid->category_order('排序');
        $grid->disableCreateButton(false);
        $grid->actions(function ($actions) {
            $actions->disableEdit(false);
            $actions->disableDelete(false);
        });
        $grid->filter(function ($filter) {
            $filter->like('categoryname', '名称');
        });

        return $grid;
    }

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

        $show->id('ID');
        $show->created_at('Created at');
        $show->updated_at('Updated at');

        return $show;
    }

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

        $array = $this->featureSortArr(FeatureSort::all()->toArray(),0);
        $array = array_pluck($array,'categoryname','id');
        $option = ['0'=>'顶级'] +$array;
        $form->select('parent_id', '所属上级')->options($option)->setMustMark();
        $form->text('categoryname', '名称');
        $form->text('title', 'Title');
        $form->text('description', 'Description');
        $form->number('category_order', '排序')->default(0)->min(0);
        $form->hidden('admin_set')->value(0);
        return $form;
    }

    protected function editForm()
    {
        $form = new Form(new FeatureSort);

        $array = $this->featureSortArr(FeatureSort::all()->toArray(),0);
        $array = array_pluck($array,'categoryname','id');
        $option = ['0'=>'顶级'] +$array;
        $form->select('parent_id', '所属上级')->options($option)->setMustMark();
        $form->text('categoryname', '名称');
        $form->text('title', 'Title');
        $form->text('description', 'Description');
        $form->number('category_order', '排序')->default(0)->min(0);
        return $form;
    }

    public function update($id)
    {
        return $this->editForm()->update($id);
    }


    //递归查询
    protected function featureSortArr($data,$pid,$level=''){
        static $arr=array();
        foreach($data as $k => $v){
            //如果该分类pid=0
            if($v['parent_id']==$pid){
                $v['categoryname']= $level.$v['categoryname'];
                $arr[]=$v;
                self::featureSortArr($data,$v['id'],$level.'&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;');
            }
        }
        return $arr;
    }


    public function destroy($id)
    {
        \DB::beginTransaction();
        try {
            $res = FeatureSort::all()->toArray();
            $list = $this->featureSortArr($res,$id);
            $ids = array_pluck($list,'id');
            FeatureSort::where('id',$id)->delete();
            FeatureSort::whereIn('id',$ids)->delete();
            $data = [
                'status'  => true,
                'message' => '删除成功!',
            ];
            \DB::commit();
            return response()->json($data);
        } catch (\Exception $e) {
            \DB::rollback();
            $data = [
                'status'  => false,
                'message' => '删除失败!',
            ];
            return response()->json($data);
        }
    }
}