import React from 'react'
import { Button, Card, Row, Col, Form } from 'antd'
import { ProForm } from '@ant-design/pro-components'
import { useSearchParams, useNavigate } from 'react-router-dom'

const noop = (x) => x

export default React.forwardRef(function EditForm(props, ref) {
  const {
    rowId,
    rowKey,
    request,
    transform, // 提交时转换数据
    convertValue, // 初始化表单时数值转换
    maxWidth = '800px',
    renderItems,
    formRef,
    initialValues, // 初始化 form 只生效一次
    initialData, // 初始化 form 每次都生效
    onFinish,
    ...leftProps
  } = props

  const navigate = useNavigate()
  const [form] = Form.useForm()

  if (formRef) {
    formRef.current = form
  }

  // 表单提交
  const onSubmit = async (values) => {
    // 可能需要转换下格式
    if (rowId) {
      values[rowKey] = rowId
    }
    const data = transform ? transform(rowId, values) : values


    
    if (rowId && request?.update) {
      const res = await request.update(rowId, data)
      if (onFinish) {
        onFinish(res)
      }
    } else if (request?.save) {
      const res = await request.save(data)
      if (onFinish) {
        onFinish(res)
      }
    }

    return true
  }

  // 查询详情
  React.useEffect(() => {
    form.resetFields()

    if (rowId && request?.get) {
      request.get(rowId).then((res) => {
        // 此处可能需要转换下数据格式
        const formData = convertValue ? convertValue(res) : res
        form.setFieldsValue(formData)
      })
    }
  }, [request?.get, rowId])

  React.useEffect(() => {
    form.resetFields()
    const formData = convertValue ? convertValue(initialData) : initialData
    form.setFieldsValue(formData)
  }, [initialData])

  React.useImperativeHandle(ref, () => ({
    form: form,
  }))

  return (
    <ProForm
      form={form}
      onFinish={onSubmit}
      style={{ maxWidth }}
      layout="horizontal"
      labelCol={{ flex: '0 0 120px' }}
      initialValues={initialValues}
      submitter={{
        render: (_, doms) => [
          <Row gutter={48}>
            <Col flex="200px"></Col>
            <Col>
              <Button type="primary" htmlType="submit">
                提交
              </Button>
            </Col>
            <Col>
              <Button onClick={() => navigate(-1)}>返回</Button>
            </Col>
          </Row>,
        ],
      }}
      {...leftProps}
    >
      {renderItems()}
    </ProForm>
  )
})
