import { Form, Input, Button } from 'antd';
import { history } from 'umi';
import React, { useEffect, useState, useCallback, useRef, useMemo } from 'react'
import { useModel } from 'umi'
import { getDetail, saveOrg, updateOrg } from '@/services/org';
import QRCode from './QRCode'

export default (props) => {
  const { id } = props;
  const { initialState } = useModel('@@initialState');

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

  const qrcodeText = useMemo(() => initialState.report_url + '#resume-work-form?org=' + id, [id, initialState.report_url])

  const onFinish = (values) => {
    setLoading(true)
    if (id) {
      updateOrg(id, values).then(() => {
        setLoading(false);
        history.go(-1);
      }).catch(() => {
        setLoading(false);
      })
    } else {
      saveOrg(values).then((res) => {
        setLoading(false);
        history.replace(`/org/Edit?id=${res.orgId}`)
      }).catch(() => {
        setLoading(false);
      })
    }
  };
  const onFinishFailed = (errorInfo) => {
    console.log('Failed:', errorInfo);
  };
  useEffect(() => {
    if (id) {
      getDetail(id).then(res => {
        setFormData(res);
        form.setFieldsValue(res);
      })
    }
  }, [id])
  return (
    <div style={{ maxWidth: '600px' }}>
      <Form
        name="basic"
        form={form}
        labelCol={{ span: 8 }}
        wrapperCol={{ span: 16 }}
        onFinish={onFinish}
        onFinishFailed={onFinishFailed}
        autoComplete="off"
      >
        <Form.Item
          label="企业名称"
          name="orgName"
          rules={[{ required: true, message: '请填写企业名称!' }]}
        >
          <Input readOnly={formData?.canEditName} />
        </Form.Item>
        <Form.Item
          label="权重"
          name="weight"
          rules={[{ required: true, message: '请填写企业权重!' }]}
        >
          <Input type='number' min='0' />
        </Form.Item>
        {
          id && <Form.Item label='申报二维码' >
            <QRCode text={qrcodeText} title={formData?.orgName} />
          </Form.Item>
        }
        <Form.Item label=' ' colon={false} >
          <Button type="primary" htmlType="submit" loading={loading}>
            保存
          </Button>
          <Button style={{ marginLeft: '32px' }} onClick={() => { history.go(-1); }} >返回</Button>
        </Form.Item>
      </Form>
    </div>

  )
}
