import React, { useEffect, useState } from 'react'
import { Form, Input, Button, Checkbox } from 'antd';
import ProCard from '@ant-design/pro-card';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import { getDetail, saveOrg, updateOrg } from '@/services/org';

export default (props) => {
  const { history } = props;
  const { id } = history.location.query;

  const [form] = Form.useForm();
  const [formData, setFormData] = useState()
  const [loading, setLoading] = useState(false)

  useEffect(() => {
    if (id) {
      getDetail(id).then(res => {

        setFormData(res);
        form.setFieldsValue(res);
      })
    }
  }, [id, form])

  const onFinish = (values) => {
    setLoading(true)
    if (id) {
      updateOrg(id, values).then(() => {
        setLoading(false);
        history.go(-1);
      }).catch(() => {
        setLoading(false);
      })
    } else {
      saveOrg(values).then(() => {
        setLoading(false);
        history.go(-1);
      }).catch(() => {
        setLoading(false);
      })
    }
  };

  const onFinishFailed = (errorInfo) => {
    console.log('Failed:', errorInfo);
  };

  return (
    <PageHeaderWrapper>
      <ProCard bordered>
        <div style={{ maxWidth: '600px' }}>
          <Form
            name="basic"
            form={form}
            labelCol={{ span: 8 }}
            wrapperCol={{ span: 16 }}
            initialValues={formData}
            onFinish={onFinish}
            onFinishFailed={onFinishFailed}
            autoComplete="off"
          >
            <Form.Item
              label="企业名称"
              name="orgName"
              rules={[{ required: true, message: '请填写企业名称!' }]}
            >
              <Input />
            </Form.Item>
            <Form.Item
              label="权重"
              name="weight"
              rules={[{ required: true, message: '请填写企业名称!' }]}
            >
              <Input type='number' min='0' />
            </Form.Item>
            <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
              <Button type="primary" htmlType="submit" loading={loading}>
                保存
              </Button>
            </Form.Item>
          </Form>
        </div>
      </ProCard>
    </PageHeaderWrapper>
  )
}
