import React, { useEffect, useState } from 'react'
import { Form, Input, Button, message } from 'antd';
import { history } from 'umi';
import md5 from 'md5';
import { saveOrgUser, getOrgAdminDetail } from '@/services/org';

export default (props) => {
  const { id } = props;
  const [adminForm] = Form.useForm();
  const [adminFormData, setAdminFormData] = useState()
  const [adminLoading, setAdminLoading] = useState(false)

  const onAdminFinish = (values) => {
    if (!/^1[0-9]{10}$/.test(values.phone)) {
      message.warning('请输入正确的十一位手机号');
      setLoading(false);
      return false;
    }
    var data = { ...adminFormData, ...values, password: md5(values.password), isAdmin: true };
    setAdminLoading(true)
    saveOrgUser(id, data).then(res => {
      message.success('保存成功');
      history.go(-1);
      setAdminLoading(false)
    }).catch(err => {
      console.log(err);
      setAdminLoading(false)
    })
  }
  useEffect(() => {
    if (id) {
      getOrgAdminDetail(id).then((res) => {
        setAdminFormData(res);
        adminForm.setFieldsValue(res);
      })
    }
  }, [id])
  return (
    <div style={{ maxWidth: '600px' }}>
      <Form
        form={adminForm}
        labelCol={{ span: 8 }}
        wrapperCol={{ span: 16 }}
        onFinish={onAdminFinish}
      >
        <Form.Item
          label="姓名"
          name="userName"
          rules={[{ required: true, message: '请填写管理员姓名!' }]}
        >
          <Input />
        </Form.Item>
        <Form.Item
          label="手机号"
          name="phone"
          rules={[{ required: true, message: '请填写手机号!' }]}
        >
          <Input maxLength={11} />
        </Form.Item>
        <Form.Item
          label="登录账号"
          name="loginName"
          rules={[{ required: true, message: '请填写登录账号!' }]}
        >
          <Input />
        </Form.Item>
        <Form.Item
          label="密码"
          name="password"
          rules={[{ required: true, message: '请填写密码!' }]}
        >
          <Input />
        </Form.Item>
        <Form.Item label=' ' colon={false} >
          <Button type="primary" htmlType="submit" loading={adminLoading}>
            保存
          </Button>
          <Button style={{ marginLeft: '32px' }} onClick={() => { history.go(-1); }}>返回</Button>
        </Form.Item>
      </Form>
    </div>

  )
}