import React, { useEffect } from 'react'
import { message, Button, Drawer } from 'antd'
import { connect, useRequest } from 'umi'
// import consts from '@/utils/consts'
import { addAccount, updateAccount } from '@/services/api/institution'
// import DebounceSelect from './DebounceSelect'
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 { InstitutionsModelState } from '../../model'

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

type StaffModalProps = ConnectProps & {
  visible: boolean
  setVisible: (visible: boolean) => void
  type: ModalType
  defaultFormData?: {
    ID: string
    name: string
    accountType: string
    dataID: string
  }
  accountTypeList: API.AccountType
  organizationList: API.OrganizationalStructureListItem
  reload: () => void
  schema?: Record<string, any> | null
}

const StaffDrawer: React.FC<StaffModalProps> = ({
  visible,
  setVisible,
  schema,
  dispatch,
  type,
  defaultFormData,
  accountTypeList,
  organizationList,
  reload
}) => {
  console.log(organizationList)

  const form = useForm()
  useEffect(() => {
    if (visible) {
      if (!schema) {
        dispatch({
          type: 'schemaBase/querySchema',
          payload: {
            columnType: BaseMenuEnum.STAFF
          }
        })
      }
      if (!organizationList?.length) {
        dispatch({
          type: 'institutions/queryOrganizationList',
          payload: {
            dataID: defaultFormData?.dataID,
            structureType: '1'
          }
        })
      }
    }
  }, [visible])
  // useEffect(() => {
  //   defaultFormData && ref.current?.setFieldsValue({ ...defaultFormData })
  // }, [defaultFormData])

  const { run: tryUpdateAccount } = useRequest(updateAccount, {
    manual: true,
    onSuccess: () => {
      message.success('更新成功')
    }
  })

  const { run: tryAddAccount } = useRequest(addAccount, {
    manual: true,
    onSuccess: () => {
      message.success('创建成功')
    }
  })

  const onMount = () => {
    // console.log(defaultFormData)

    form.setValues({ ...defaultFormData })
    delay(80).then(() => {
      form.setSchemaByPath('accountType', {
        enum: accountTypeList.map(item => item.value),
        enumNames: accountTypeList.map(item => item.label)
      })
      form.setSchemaByPath('institution', {
        enum: organizationList.map(item => item.value),
        enumNames: organizationList.map(item => item.label)
      })
    })
  }

  // const handleOnFinish = () => {
  //   ref.current?.validateFields().then(async values => {
  //     try {
  //       // 执行表单提交
  //       if (type === ModalType.ADD) {
  //         await tryAddAccount(values)
  //       } else {
  //         await tryUpdateAccount(values)
  //       }
  //       setVisible(false)
  //       reloadTable()
  //       ref.current?.resetFields()
  //     } catch (error) {
  //       message.error(error)
  //     }
  //   })
  // }
  const onFinish = async (formData, errors) => {
    console.log('formData:', formData, 'errors', errors)
    try {
      // 执行表单提交
      if (type === ModalType.ADD) {
        await tryAddAccount(formData)
      } else {
        await tryUpdateAccount(formData)
      }
      setVisible(false)
      reload()
    } catch (error) {
      message.error(error)
    }
  }
  // const queryInstitutionOptions = async search => {
  //   const { code = -1, data = {} } = await queryInstitutionList({
  //     search,
  //     current: 1,
  //     pageSize: 100
  //   })
  //   if (code === consts.RET_CODE.SUCCESS) {
  //     return data.items.map(item => ({ label: item.name, value: item.ID }))
  //   }
  //   return []
  // }
  // const { institution } = defaultFormData || {}
  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(
  ({
    institutions,
    schemaBase
  }: {
    institutions: InstitutionsModelState
    schemaBase: SchemaBaseModelState
  }) => ({
    accountTypeList: institutions.accountType.map(item => ({
      label: item.name,
      value: item.value
    })),
    organizationList: institutions.organizationType.map(item => ({
      label: item.name,
      value: item.dataID
    })),
    schema: schemaBase.base[BaseMenuEnum.STAFF]?.schema
  })
)(StaffDrawer)
