<?php

namespace App\Admin\Controllers;

use App\Import;

use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Layout\Content;
use App\Http\Controllers\Controller;
use Encore\Admin\Controllers\ModelForm;
use Illuminate\Support\Facades\Artisan;

class ImportController extends Controller
{
    use ModelForm;

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

            $content->header('数据管理');
            $content->description('列表');

            $content->body($this->grid());
        });
    }

    /**
     * Edit interface.
     *
     * @param $id
     * @return Content
     */
    public function edit($id)
    {
        return Admin::content(function (Content $content) use ($id) {

            $content->header('数据管理');
            $content->description('编辑');

            $content->body($this->form()->edit($id));
        });
    }

    /**
     * Create interface.
     *
     * @return Content
     */
    public function create()
    {
        return Admin::content(function (Content $content) {

            $content->header('数据管理');
            $content->description('导入');

            $content->body($this->form());
        });
    }

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Admin::grid(Import::class, function (Grid $grid) {
            $grid->disableExport();
            
            $grid->id('ID')->sortable();

            $grid->name('任务名');
            $grid->category('类型')->display(function ($v) {
                return collect(Import::$CATEGORY)->where('id', $v)->first()['name'];
            });

            $grid->is_import('是否导入')->display(function ($v) {
                if ($v === 'F') {
                    return "<span class='label label-default'>未导入</span>";
                }
                return "<span class='label label-success'>已导入</span>";
            });

            $grid->created_at();
            $grid->updated_at();
        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Admin::form(Import::class, function (Form $form) {

            $form->display('id', 'ID');

            $form->text('name', '任务名');
            $form->select('category', '类型')->options(collect(Import::$CATEGORY)->pluck('name', 'id'));
            $form->file('path', '选择文件');

            $states = [
                'on' => ['value' => 'T', 'text' => '导入', 'color' => 'success'],
                'off' => ['value' => 'F', 'text' => '不导入', 'color' => 'danger'],
            ];
            $form->switch('is_import', '是否导入')->states($states);

            $form->saved(function (Form $form) {
                $id = $form->model()->id;
                Artisan::queue('excel:load', ['id' => $id]);
            });

        });
    }
}
