<?php

namespace Modules\Base\Http\Controllers\Admin;

use Modules\Base\Entities\Openid;
use App\Http\Controllers\Controller;
use SMG\Admin\Controllers\HasResourceActions;
use SMG\Admin\Facades\Admin;
use SMG\Admin\Form;
use SMG\Admin\Grid;
use SMG\Admin\Layout\Content;
use SMG\Admin\Show;

class OpenidsController extends Controller
{
    use HasResourceActions;

    /**
     * Index interface.
     *
     * @param Content $content
     * @return mixed
     */
    public function index(Content $content)
    {
        return $content
            ->header('openid列表')
            ->body($this->grid());
    }

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

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

    /**
     * Create interface.
     *
     * @param Content $content
     * @return mixed
     */
    public function create(Content $content)
    {
        return $content
            ->header('新增')
            ->body($this->form());
    }

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Admin::Grid(new Openid(), function($grid) {
            $grid->model()->withCount('user')->orderBy('id', 'desc');
            $grid->id('Id');
            $grid->user_id('用户id');
            $grid->user()->name('用户名');
            $grid->user()->sex('性别?')->display(function ($sex) {
                return $sex ? $sex ==1?'男':'女' : '未知';
            });
            $grid->type('类型');
            $grid->openid('openid');
            $grid->created_at('添加时间');
        });
    }

    /**
     * Make a show builder.
     *
     * @param mixed   $id
     * @return Show
     */
    protected function detail($id)
    {
        $show = new Show(Openid::findOrFail($id));
        $show->id('Id');
        $show->type('类型');
        $show->openid('openid');
        $show->user_id('用户id');
        $show->created_at('创建时间');
        return $show;
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        $form = new Form(new Openid);
        $form->number('type', '类型')->rules('required');
        $form->text('openid', 'openid')->rules('required');
        $form->number('user_id', '用户id')->rules('required');
        $form->text('extra', '额外信息');
        return $form;
    }
}
