<?php


namespace App\Community\Controllers;


use App\Models\CdmsUsers;
use App\Models\Organization;
use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Form;

class DocterAccountController extends  AdminController
{
    protected $title = '添加账号';
    /**
     * Make a form builder.
     *
     * @return Form
     */
    public function form()
    {
        $userModel = config('tenancy.database.users_model');
        $roleModel = config('tenancy.database.roles_model');


        $org_id = request('org_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('docter_id'));
//        if($form->isEditing()){
//            $reoute = request()->route()->parameters();
//            $id = intval($reoute['docter_account']);
//            $org_id = CdmsUsers::where(['id'=>$id])->value('org_id');
//            $form->multipleSelect('roles', trans('tenancy.roles'))->options($roleModel::where('org_id',$org_id)->get()->pluck('name', 'id'));
//        } else {
//            $form->multipleSelect('roles', trans('tenancy.roles'))->options($roleModel::where('org_id',$org_id)->get()->pluck('name', 'id'));
//        }

        $form->multipleSelect('roles', trans('tenancy.roles'))->options($roleModel::whereIn('name',['门诊医生','儿保医生','计免医生','图文咨询','所有医生'])->get()->pluck('name', 'id'));

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

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

        $form->saved(function (){
            return redirect('/cdms/docters');
        });


        return $form;
    }
}
