import React, { useEffect } from 'react'
import ProForm, {
  ProFormText,
} from '@ant-design/pro-form';
import UploadImage from '@/components/UploadImage';
import { notification, Form } from 'antd';
import request from '@/utils/request';

export default (props) => {
  const [form] = Form.useForm();

  const handleSubmit = (values) => {
    if (!props.user?.userId) {
      // 新增
      request('/user', { method: 'post', data: values }).then(res => {
        notification.success({ message: '新增用户成功' })
        props.onChange(res)
      }).catch((e) => {
        notification.error({ message: e.message })
      })
    } else {
      //
    }
  }

  useEffect(() => {
    if (props.user && props.user.userId) {
      form.setFieldsValue(props.user);
    }
  }, [props.user, form]);

  return (
    <ProForm form={form} onFinish={handleSubmit}>
      <ProFormText
        label="姓名"
        placeholder="请输入姓名"
        name="userName"
        rules={[{ required: true, message: '请填写姓名' }]}
      />

      <Form.Item name="avatar" label="头像" placeholder="请设置头像">
        <UploadImage />
      </Form.Item>

      <ProFormText
        label="手机号"
        placeholder="请输入手机号"
        name="phone"
      />

      <ProFormText
        label="登录名"
        placeholder="请设置用户登录名"
        name="loginName"
        rules={[{ required: true, message: '请设置用户登录名' }]}
        extra="默认密码 abc@123 "
      />
    </ProForm>
  )
}
