import { connect, useRequest } from 'umi'
import { useEffect } from 'react'
import { Button, Drawer, message } from 'antd'
import { addProject, updateProject } from '@/services/api/project'
import { delay } from '@/utils/util'
import FormRender, { useForm } from 'form-render'
import { BaseMenuEnum } from '@/pages/Schema/Base'
import type { SchemaBaseModelState } from '@/pages/Schema/Base/model'
import type { ConnectProps } from 'umi'
import type { ProjectModelState } from '../../model'

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

type ProjectModalProps = ConnectProps & {
  visible: boolean
  setVisible: (visible: boolean) => void
  type: ModalType
  defaultFormData?: {
    ID: string
    name: string
    projectTypeID: string
  }
  pTypeList: API.ProjectTypeList
  reloadTable: () => void
  schema?: Record<string, any> | null
}
const ProjectModal: React.FC<ProjectModalProps> = ({
  visible,
  setVisible,
  dispatch,
  schema,
  type,
  defaultFormData,
  pTypeList,
  reloadTable
}) => {
  const form = useForm()
  useEffect(() => {
    if (visible && !schema) {
      dispatch({
        type: 'schemaBase/querySchema',
        payload: {
          columnType: BaseMenuEnum.PROJECT
        }
      })
    }
  }, [visible])

  const { run: tryUpdateProject } = useRequest(updateProject, {
    manual: true,
    onSuccess: () => {
      message.success('更新成功')
    }
  })
  const { run: tryAddProject } = useRequest(addProject, {
    manual: true,
    onSuccess: () => {
      message.success('创建成功')
    }
  })

  const onMount = () => {
    form.setValues({ ...defaultFormData })
    delay().then(() => {
      form.setSchemaByPath('projectTypeID', {
        enum: pTypeList.map(item => item.value),
        enumNames: pTypeList.map(item => item.label)
      })
    })
  }

  const onFinish = async (formData, errors) => {
    console.log('formData:', formData, 'errors', errors)
    try {
      // 执行表单提交
      if (type === ModalType.ADD) {
        await tryAddProject(formData)
      } else {
        await tryUpdateProject(formData)
      }
      setVisible(false)
      reloadTable()
    } catch (error) {
      message.error(error)
    }
  }
  return (
    <Drawer
      width="50vw"
      visible={visible}
      onClose={() => {
        // ref.current?.resetFields()
        setVisible(false)
      }}
      title={type === ModalType.ADD ? '新增项目' : '编辑项目'}>
      {schema && (
        <FormRender form={form} schema={JSON.parse(schema)} onFinish={onFinish} onMount={onMount} />
      )}
      <div>
        <Button onClick={form.submit}>提交</Button>
      </div>
    </Drawer>
  )
}

export default connect(
  ({ project, schemaBase }: { project: ProjectModelState; schemaBase: SchemaBaseModelState }) => ({
    pTypeList: project.projectTypeList.map(item => ({ label: item.name, value: item.ID })),
    schema: schemaBase.base[BaseMenuEnum.PROJECT]?.schema
  })
)(ProjectModal)
