<?php

namespace App\Admin\Controllers;

use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Widgets\Table;
use RuLong\Identity\Models\Identity;

class IdentityController extends AdminController
{

    protected $title = '用户身份配置';

    protected function grid()
    {
        $grid = new Grid(new Identity);
        $grid->disableCreateButton();
        $grid->disableFilter();
        $grid->disableExport();
        $grid->disableRowSelector();
        $grid->tools(function ($tools) {
            $tools->batch(function ($batch) {
                $batch->disableDelete();
            });
        });
        $grid->actions(function ($actions) {
            $actions->disableDelete();
            $actions->disableView();
        });
        $grid->fixColumns(0, 0);

        $grid->model()->orderBy('id', 'asc');
        $grid->column('id', '身份编号')->sortable();
        $grid->column('title', '身份');
        $grid->column('name', '等级');

        $grid->column('分润规则')->display(function ($title, $column) {
            return '点击查看';
        })->modal(function ($model) {
            $codes = $model->codes->map(function ($code) {
                return $code->only(['name', 'code', 'profit']);
            });

            return new Table(['名称', '规则项', '分润金额(元)'], $codes->toArray());
        });

        $grid->column('remark', '说明');
        $grid->column('updated_at', '修改时间');

        return $grid;
    }

    protected function form()
    {
        $form = new Form(new Identity);
        $form->display('id', 'ID');
        $form->text('title', '级别')->rules('required');
        $form->text('name', '等级')->rules('required');

        $form->hasMany('codes', '分润项目', function (Form\NestedForm $form) {
            $form->text('name', '标题');
            $form->text('code', '分润的项目');
            $form->text('profit', '分润金额');
        });

        $form->textarea('remark', '说明')->rules('required');

        $form->tools(function (Form\Tools $tools) {
            $tools->disableDelete();
            $tools->disableView();
        });

        $form->footer(function ($footer) {
            $footer->disableReset();
            $footer->disableViewCheck();
            $footer->disableCreatingCheck();
        });

        return $form;
    }

}
