<?php

namespace App\Community\Controllers;

use Encore\Admin\Controllers\AuthController as BaseAuthController;

class AuthController extends BaseAuthController
{
    protected $title = '医生账号';
    /**
     * Make a form builder.
     *
     * @return Form
     */
    public function form()
    {
        $userModel = config('tenancy.database.users_model');
        $permissionModel = config('tenancy.database.permissions_model');
        $roleModel = config('tenancy.database.roles_model');

        $org_id = request('org_id');
        $doc_id = request('doc_id');

        $form = new Form(new $userModel());

        $userTable = config('tenancy.database.users_table');
        $connection = config('tenancy.database.connection');

        $form->display('id', 'ID');
        $form->text('username', trans('tenancy.username'))
            ->creationRules(['required', "unique:{$connection}.{$userTable}"])
            ->updateRules(['required', "unique:{$connection}.{$userTable},username,{{id}}"]);

        $form->text('name', trans('tenancy.name'))->rules('required');
        $form->image('avatar', trans('tenancy.avatar'));
        $form->password('password', trans('tenancy.password'))->rules('required|confirmed');
        $form->password('password_confirmation', trans('tenancy.password_confirmation'))->rules('required')
            ->default(function ($form) {
                return $form->model()->password;
            });

        $form->ignore(['password_confirmation']);

        $form->hidden('org_id')->value(request('org_id'));
        $form->hidden('docter_id')->value(request('doc_id'));
        $form->multipleSelect('roles', trans('tenancy.roles'))->options($roleModel::where('org_id',$org_id)->all()->pluck('name', 'id'))->rule('required',['requried'=>'请选择角色']);

        $form->display('created_at', trans('tenancy.created_at'));
        $form->display('updated_at', trans('tenancy.updated_at'));

        $form->saving(function (Form $form) use ($doc_id,$org_id){
            if ($form->password && $form->model()->password != $form->password) {
                $form->password = bcrypt($form->password);
            }
        });


        return $form;
    }
}
