<?php

namespace Modules\Cms\Http\Controllers\Admin;

use App\Admin\Traits\WithUploads;
use Closure;
use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Form;
use Encore\Admin\Layout\Column;
use Encore\Admin\Layout\Row;
use Encore\Admin\Tree;
use Encore\Admin\Widgets\Box;
use Encore\Admin\Widgets\Form as WidgetsForm;
use Modules\Cms\Models\Category;

class CategoryController extends AdminController
{

    use WithUploads;

    protected $title = '分类管理';

    public function grid(): Closure
    {
        return function (Row $row) {
            $row->column(6, $this->treeView());

            $row->column(6, function (Column $column) {
                $form = new WidgetsForm();
                $this->formData($form, true);
                $form->action(route('admin.cms.categories.store'));
                $column->append((new Box('新增分类', $form))->style('success'));
            });
        };
    }

    protected function treeView(): Tree
    {
        return Category::tree(function (Tree $tree) {
            $tree->disableCreate();
            $tree->branch(function ($branch) {
                if ($branch['status'] == 1) {
                    $payload = "<i class='fa fa-eye text-primary'></i> ";
                } else {
                    $payload = "<i class='fa fa-eye text-gray'></i> ";
                }

                $payload .= " [ID:{$branch['id']}] - ";
                $payload .= " <strong>{$branch['title']}</strong> ";

                return $payload;
            });
        });
    }

    protected function form(): Form
    {
        $form = new Form(new Category);

        $this->formData($form);

        return $form;
    }

    private function formData($form, $hideContent = false)
    {
        $form->select('parent_id', '上级分类')
             ->options(Category::selectOptions(function ($model) {
                 return $model->where('status', 1);
             }, '一级分类'))
             ->required();
        $form->text('title', '分类名称')
             ->rules('required');
        $form->text('slug', '英文别名')
             ->rules([
                 'nullable',
                 'alpha_dash',
             ], [
                 'alpha_dash' => '别名中包含非法字符',
             ])
             ->help('字母、数字、下划线组成，用来展示简短的URL');
        $form->textarea('description', '分类简介')
             ->rules('nullable');

        $this->cover($form);

        $this->pictures($form);

        $form->number('order', '排序')->default(0);

        if (!$hideContent) {
            $form->ueditor('content', '分类内容');
        }

        $form->switch('status', '状态')->default(1);
    }

}