import { connect, useRequest } from 'umi'
import { useEffect, useRef, useState } from 'react'
import { message, Tabs, Form } from 'antd'
import { getApprovalList, getProject, setApproval } 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'
import ProForm from '@ant-design/pro-form'
import TreeNodeSelect from './TreeNodeSelect'
import { ModalType } from '@/utils/enum'
import consts from '@/utils/consts'

type ProjectModalProps = ConnectProps & {
  visible: boolean
  onVisibleChange: (visible: boolean) => void
  type: ModalType
  defaultFormData?: {
    dataID: string
  }
  reload: () => void
  schema?: Record<string, any> | null
}
const DetailModal: React.FC<ProjectModalProps> = ({
  visible,
  // onVisibleChange,
  dispatch,
  schema,
  type,
  defaultFormData,
  pTypeList,
  reload
}) => {
  const form = useForm()
  const ref = useRef<FormInstance>(null)
  const { TabPane } = Tabs
  const [state, setState] = useState({
    acountInstitutionList: [],
    approvalList: [],
    activeKey: '',
    account: null
  })

  const { run: tryApprovalList } = useRequest(() => getApprovalList(), {
    manual: true,
    onSuccess: result => {
      setState({ ...state, approvalList: result.items })
    }
  })

  const { run: trySetApproval } = useRequest(setApproval, {
    manual: true,
    onSuccess: () => {
      message.success('提交成功')
    }
  })

  useEffect(() => {
    if (visible && !schema) {
      dispatch({
        type: 'schemaBase/querySchema',
        payload: {
          columnType: BaseMenuEnum.PROJECT
        }
      })
    }
    if (state.activeKey === '2') {
      const TabFormData = {
        accountID: state.account.reportAccount?.ID,
        approvalID: state.account.approval?.ID
      }
      ref.current?.setFieldsValue({ ...TabFormData })
    }
  }, [visible, state.activeKey])

  const onMount = async () => {
    const { dataID } = defaultFormData
    const { code = -1, data } = await getProject({ ID: dataID })
    if (code === consts.RET_CODE.SUCCESS) {
      const currentFormData = { ...data }
      setState({ ...state, account: data })
      const keys = Object.keys(currentFormData)
      keys.forEach(key => {
        if (currentFormData[key] instanceof Object) {
          const targetMap = currentFormData[key]
          delete currentFormData[key]
          currentFormData[`${key}ID`] = targetMap.ID
        }
      })
      form.setValues({ ...currentFormData })
    }
    delay(80).then(() => {
      form.setSchemaByPath('projectTypeID', {
        enum: pTypeList.map(item => item.value),
        enumNames: pTypeList.map(item => item.label)
      })
    })
  }

  const onChange = key => {
    setState({ ...state, activeKey: key })
    if (key === '2') {
      // if (!state.acountInstitutionList?.length) {
      //   tryAcountInstitutionList()
      // }
      if (!state.approvalList?.length) {
        tryApprovalList()
      }
    }
  }

  const onFinish = async formData => {
    try {
      await trySetApproval({ ...formData, ID: defaultFormData.dataID })
      setState({
        ...state,
        account: {
          ...state,
          approval: { ID: formData.approvalID },
          reportAccount: { ID: formData.accountID }
        }
      })
      reload()
      return true
    } catch (error) {
      console.log(error)
      return false
    }
  }
  return (
    <Tabs onChange={onChange}>
      <TabPane tab="项目信息" key="1">
        {schema && (
          <FormRender
            form={form}
            schema={schema}
            onMount={onMount}
            readOnly={type === ModalType.PREVIEW ? true : false}
          />
        )}
      </TabPane>
      <TabPane tab="上传权限" key="2">
        <ProForm
          formRef={ref}
          submitter={{ resetButtonProps: { style: { display: 'none' } } }}
          onFinish={onFinish}>
          <Form.Item label="指定人员" name="accountID">
            <TreeNodeSelect />
            {/* <TreeSelect
              style={{ width: '100%' }}
              placeholder="请选择上报人"
              treeDefaultExpandAll
              treeData={state.acountInstitutionList}
            /> */}
          </Form.Item>
          {/* <ProFormSelect
            name="approvalID"
            label={'审批流程'}
            placeholder="请选择审批流程"
            options={state.approvalList.map(item => ({
              label: item.name,
              value: item.ID
            }))}
          /> */}
        </ProForm>
      </TabPane>
    </Tabs>
  )
}

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
  })
)(DetailModal)
