import React, { useEffect, useState } from 'react'
import { PageHeader, Form, Button, Spin, Modal, notification } from 'antd'

const formItemLayout = {
  labelCol: {
    xs: { span: 24 },
    sm: { span: 4 },
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 12 },
  },
}

const tailFormItemLayout = {
  wrapperCol: {
    xs: {
      span: 24,
      offset: 0,
    },
    sm: {
      span: 16,
      offset: 6,
    },
  },
}

export default Form.create({})(props => {
  const [title, updateTitle] = useState('详情' || props.title)
  const [loading, updateLoading] = useState(false)
  const [pageData, updatePageData] = useState(null)

  const id = props.dataId
  const { getFieldDecorator, setFieldsValue, validateFields, resetFields } = props.form

  const handleCancel = () => {
    if (props.onCancel) {
      props.onCancel()
    }
  }

  const { fetchAPI, saveAPI, updateAPI } = props

  const handleSubmit = (e) => {
    e.preventDefault();
    validateFields((err, values) => {
      if (!err) {
        updateLoading(true)
        if (!id && !props.record) {
          saveAPI({data: values}).then(res => {
            updateLoading(false)
            // 保存成功之后直接跳转到详情
            Modal.success({
              content: '保存信息成功',
              onOk: () => {
                if (props.onSuccess) {
                  props.onSuccess(res)
                }
              }
            })
          }).catch(err => {
            updateLoading(false)
            if (props.onError) {
              props.onError(err)
            }
          })
        } else {
          const pKey = id || props.dateKey(props.record)

          const data = props.record ? { ...props.record, ...values } : values
          updateAPI({ data, urlData: { id: pKey } }).then(res => {
            updateLoading(false)
            updatePageData(res)
            notification.success({ message: '更新信息成功' })
            if (props.onSuccess) {
              props.onSuccess(res)
            }
          }).catch(err => {
            updateLoading(false)
            if (props.onError) {
              props.onError(err)
            }
          })
        }
      }
    });
  }

  useEffect(() => {
    if (props.mode !== 'inner') {
      if (!pageData) {
        resetFields()
      } else {
        setFieldsValue(pageData)
      }
    }
  }, [props.mode, pageData])

  useEffect(() => {
    if (props.mode === 'inner') {
      if (!props.record) {
        resetFields()
      } else {
        setFieldsValue(props.record)
      }
      updatePageData(props.record)
    }
  }, [props.mode, props.record])

  useEffect(() => {
    if (props.mode !== 'inner' && id) {
      updateLoading(true)
      fetchAPI({ urlData: {id} }).then((res) => {
        updatePageData(res)
        updateLoading(false)
        if (!res) {
          notification.info({ message: '没有查询到数据' })
        } else {
          if (props.getPageTitle) {
            updateTitle(props.getPageTitle(res.typeName))
          }
        }
      }).catch(err => {
        updateLoading(false)
      })
    }
  }, [])

  const childProps = {
    form: props.form,
    dataSource: pageData
  }

  const showHeader = props.showHeader !== false

  return (
    <div>
      {
        showHeader && (
          <PageHeader
            ghost={false}
            backIcon={false}
            title={title}
          ></PageHeader>
        )
      }
      <div style={{marginTop: '16px'}}>
        <Spin spinning={loading} tip="请稍候...">
          <Form {...formItemLayout} onSubmit={handleSubmit} >
            {
              props.render(childProps)
            }
            <Form.Item {...tailFormItemLayout}>
              <Button type="primary" htmlType="submit">
                保存
              </Button>
              <Button onClick={handleCancel} style={{ marginLeft: '100px' }}>
                取消
              </Button>
            </Form.Item>
          </Form>
        </Spin>
      </div>
    </div>
  )
})
