import { useRequest } from 'umi'
import { useRef, useEffect } from 'react'
import ProForm, { ProFormSelect, ProFormText } from '@ant-design/pro-form'
import { message, Modal } from 'antd'
import { addProject, updateProject } from '@/services/api/project'
import type { FormInstance } from 'antd'

export enum ModalType {
  ADD = 0,
  UPDATE = 1
}

type ProjectModalProps = {
  visible: boolean
  setVisible: (visible: boolean) => void
  type: ModalType
  defaultFormData?: {
    id: string
    name: string
    project_type_id: string
  }
  pTypeList: API.ProjectTypeList
  reloadTable: () => void
}
const ProjectModal: React.FC<ProjectModalProps> = ({
  visible,
  setVisible,
  type,
  defaultFormData,
  pTypeList,
  reloadTable
}) => {
  const ref = useRef<FormInstance>(null)
  useEffect(() => {
    defaultFormData && ref.current?.setFieldsValue({ ...defaultFormData })
  }, [defaultFormData])
  const { run: tryUpdateProject } = useRequest(updateProject, {
    manual: true,
    onSuccess: () => {
      message.success('更新成功')
    }
  })
  const { run: tryAddProject } = useRequest(addProject, {
    manual: true,
    onSuccess: () => {
      message.success('创建成功')
    }
  })

  const handleOnFinish = () => {
    ref.current?.validateFields().then(async values => {
      try {
        // 执行表单提交
        if (type === ModalType.ADD) {
          await tryAddProject(values)
        } else {
          await tryUpdateProject(values)
        }
        setVisible(false)
        reloadTable()
        ref.current?.resetFields()
      } catch (error) {
        message.error(error)
      }
    })
  }
  return (
    <Modal
      width="35vw"
      visible={visible}
      onCancel={() => {
        ref.current?.resetFields()
        setVisible(false)
      }}
      title={type === ModalType.ADD ? '新增项目' : '编辑项目'}
      onOk={() => handleOnFinish()}>
      <ProForm formRef={ref} submitter={{ render: false }}>
        {type === ModalType.UPDATE ? <ProFormText name="id" hidden /> : null}
        <ProFormText
          name="name"
          label="项目名称"
          rules={[{ required: true, message: '请输入项目名称' }]}
        />
        <ProFormSelect
          name="project_type_id"
          label="项目类型"
          rules={[{ required: true, message: '请选择项目类型' }]}
          options={pTypeList}
        />
      </ProForm>
    </Modal>
  )
}

export default ProjectModal
