<?php


namespace App\Admin\Controllers;


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

class CdmsController extends AdminController
{

    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');

        $id = request('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.login_account'))
            ->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('id'));
        $form->multipleSelect('roles', trans('tenancy.roles'))->options($roleModel::all()->pluck('name', 'id'));
        $form->multipleSelect('permissions', trans('tenancy.permissions'))->options($permissionModel::all()->pluck('name', 'id'));

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

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

        $form->saved(function (Form $form) use ($id) {
            $org_id = $form->model()->org_id;
            \Log::info($form->model()->id.'--------id-----'.'组织id'.$org_id);
            Organization::where(['id'=>$org_id])->update(['cdms_id'=>$form->model()->id]);
           return redirect('/admin/organizations');
        });

        return $form;
    }
}
