<?php

namespace App\Admin\Controllers;

use App\Models\Apply;
use App\Models\User;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Show;
use Dcat\Admin\Http\Controllers\AdminController;

class ApplyController extends AdminController
{
    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Grid::make(new Apply(), function (Grid $grid) {
            $grid->column('id')->sortable();
            $grid->column('share_name');
            $grid->column('share_phone');
            $grid->column('state');
            $grid->column('user_id');
            $grid->column('created_at');
            $grid->column('updated_at')->sortable();
            $grid->disableCreateButton();
            $grid->disableViewButton();
            $grid->disableDeleteButton();
            $grid->filter(function (Grid\Filter $filter) {
                $filter->equal('id');

            });
        });
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     *
     * @return Show
     */
    protected function detail($id)
    {
        return Show::make($id, new Apply(), function (Show $show) {
            $show->field('id');
            $show->field('share_name');
            $show->field('share_phone');
            $show->field('state');
            $show->field('user_id');
            $show->field('created_at');
            $show->field('updated_at');
        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Form::make(new Apply(), function (Form $form) {
            $form->display('id');
            $form->display('share_name');
            $form->display('share_phone');
            $form->select('state')
                ->when(2, function (Form $form) {
                    $form->textarea('not_desc','原因');
                })
                ->options([1 => '通过申请',2 => '不通过申请'])->saving(function ($item) use(&$form){
                    if ($item == 1){
                        User::query()->where('id',$form->model()->user_id)->update([
                            'is_share' => 1,
                            'share_name'    => $form->model()->share_name,
                            'share_phone'    => $form->model()->share_phone,
                        ]);
                        return $item;
                    }
                });
            $form->hidden('user_id');
            $form->disableViewButton();
            $form->disableDeleteButton();
            $form->display('created_at');
            $form->display('updated_at');
        });
    }
}
