import { connect, useRequest } from 'umi'
import { useEffect, useRef, useState } from 'react'
import { message, Tabs } from 'antd'
import { getApprovalList, setApproval } from '@/services/api/project'
import { queryAcountList } from '@/services/api/institution'
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, { ProFormSelect } from '@ant-design/pro-form'

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

type ProjectModalProps = ConnectProps & {
  visible: boolean
  onVisibleChange: (visible: boolean) => void
  readOnly: boolean
  type: ModalType
  defaultFormData?: {
    ID: string
    name: string
  }
  reloadTable: () => void
  schema?: Record<string, any> | null
}
const DetailModal: React.FC<ProjectModalProps> = ({
  visible,
  onVisibleChange,
  readOnly,
  dispatch,
  schema,
  defaultFormData,
  pTypeList,
  reloadTable
}) => {
  // console.log(defaultFormData)

  const form = useForm()
  const ref = useRef<FormInstance>(null)
  const { TabPane } = Tabs
  const [state, setState] = useState({
    acountList: [],
    approvalList: [],
    activeKey: ''
  })

  const { run: tryAcountList } = useRequest(() => queryAcountList(), {
    manual: true,
    onSuccess: result => {
      setState({ ...state, acountList: result.items })
    }
  })

  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: defaultFormData.approval.name,
        approvalID: defaultFormData.reportAccount.name
      }
      ref.current?.setFieldsValue({ ...TabFormData })
    }
  }, [visible, state.activeKey])

  const onMount = () => {
    const currentFormData = { ...defaultFormData }
    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
      }
    })
    // console.log(currentFormData)
    form.setValues({ ...currentFormData })
    // form.setValues({ ...defaultFormData })
    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.acountList?.length) {
        tryAcountList()
      }
      if (!state.approvalList?.length) {
        tryApprovalList()
      }
    }
  }

  const onFinish = async (formData, value) => {
    await trySetApproval({ ...formData, ...value, ID: defaultFormData.ID })
    onVisibleChange(false)
    reloadTable()
  }
  return (
    <Tabs onChange={onChange}>
      <TabPane tab="项目信息" key="1">
        {schema && <FormRender form={form} schema={schema} onMount={onMount} readOnly={readOnly} />}
      </TabPane>
      <TabPane tab="审批流程" key="2">
        <ProForm
          formRef={ref}
          submitter={{ resetButtonProps: { style: { display: 'none' } } }}
          onFinish={onFinish}>
          <ProFormSelect
            name="accountID"
            label={'上报人'}
            placeholder="请选择上报人"
            options={state.acountList.map(item => ({
              label: item.name,
              value: item.ID
            }))}
          />
          <ProFormSelect
            name="approvalID"
            label={'审批流程'}
            placeholder="请选择审批流程"
            options={state.approvalList.map(item => ({
              label: item.name,
              value: item.ID
            }))}
          />
        </ProForm>
      </TabPane>
    </Tabs>
    // <Drawer
    //   width="50vw"
    //   visible={visibles}
    //   onClose={() => {
    //     // ref.current?.resetFields()
    //     setVisible(false)
    //   }}
    //   title={defaultFormData?.name}>
    // <Tabs>
    //   <TabPane tab="项目信息" key="1">
    //     {schema && (
    //       <FormRender form={form} schema={schema} onMount={onMount} readOnly={readOnly} />
    //     )}
    //   </TabPane>
    //   <TabPane tab="审批流程" key="2">
    //     <ProForm
    //       formRef={ref}
    //       submitter={{ resetButtonProps: { style: { display: 'none' } } }}
    //       onFinish={onFinish}>
    //       <ProFormSelect
    //         name="accountID"
    //         label={'上报人'}
    //         placeholder="请选择上报人"
    //         options={state.acountList.map(item => ({
    //           label: item.name,
    //           value: item.ID
    //         }))}
    //       />
    //       <ProFormSelect
    //         name="approvalID"
    //         label={'审批流程'}
    //         placeholder="请选择审批流程"
    //         options={state.approvalList.map(item => ({
    //           label: item.name,
    //           value: item.ID
    //         }))}
    //       />
    //     </ProForm>
    //   </TabPane>
    // </Tabs>
    // </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
  })
)(DetailModal)
