<?php
namespace App\Admin\Actions\Users;

use App\Models\User;
use Dcat\Admin\Contracts\LazyRenderable;
use Dcat\Admin\Traits\LazyWidget;
use Dcat\Admin\Widgets\Form;
use PHPUnit\Util\Exception;

class UsersInfo extends Form implements LazyRenderable
{
    use LazyWidget;


    public function __construct($data = [], $key = null)
    {
        parent::__construct($data, $key);
    }

    public function handle(array $input)
    {
        $user = User::query()->where('id',$input['id'])->first();
        if(!$user){

            return $this->response()->error('请刷新后重试');
        }
        if($input['mobile']!=$user->mobile && User::query()->where('mobile',$input['mobile'])->first()){
            return $this->response()->error('该手机号码已被使用');
        }else{
            $user->mobile = $input['mobile'];
        }
        if($input['password']!=''){
            $user->password = $input['password'];
        }
        $user->sex = $input['sex'];
        $user->save();
        return $this->response()->success('保存成功')->refresh();
    }


    public function form()
    {
        $user = User::query()->find($this->payload['id']);
        $this->hidden('id')->value($this->payload['id']);
        $this->text('mobile', '手机号')->value($user->mobile)->help('手机号,不修改则不变');
        $this->password('password', '密码')
            ->minLength(6)
            ->maxLength(20)
            ->customFormat(function ($v) {
                if ($v == $this->password) {
                    return;
                }
                return $v;
            })
            ->help('请输入6-20个字符,不填写则不修改');
        $this->radio('sex','性别')->options([1=>"男",2=>"女"])->value($user->sex);
    }
}
