import React from "react"
import { Modal, Button, Spin, message, } from 'antd'

import AssetAction from './AssetAction'
import { dispatch } from '../../../../model'
import { showMessage } from "../../../../util"

const FC = ({ visible, nodeId, template, onCancel }) => {
  const [animated, setAnimated] = React.useState(true)
  const [waiting, setWaiting] = React.useState(false)
  const basicRef = React.useRef()

  React.useEffect(() => {
    if (visible) {
      setTimeout(() => {
        setAnimated(false)
      }, 300)
    }
  }, [visible])

  const close = (refresh = false) => {
    setAnimated(true)
    setWaiting(false)
    onCancel?.(refresh)
  }

  const save = async () => {
    try {
      await basicRef.current?.validate()

      setWaiting(true)
      dispatch({
        type: 'assetmanage.checkIsNeedSaveAsDraft',
        callback: (data) => {
          const needSaveAsDraft = (data==='true')?true:false
          dispatch({
            type: needSaveAsDraft?'assetmanage.saveAsDraft':'assetmanage.addOrUpdateDataAsset',
            payload: { 
              params: {
                dirId: nodeId,
                operation: 'release',
              },
              data: basicRef.current?.getAsset() 
            },
            callback: () => {
              showMessage("success","新增成功");
              close(true)
            },
            error: () => {
              setWaiting(false);
            }
          })
        },
        error: () => {
          setWaiting(false);
        }
      })
    } catch (errInfo) {
      
    }
  }

  const footer = React.useMemo(() => {
    return [
      <Button key='cancel'
        onClick={() => close()}
      >取消</Button>,
      <Button key='save' type='primary'
        disabled={waiting}
        onClick={() => save()}
      >保存</Button>
    ]
  }, [close, save, waiting])

  return (
    <Modal
      title='新增资产目录信息'
      visible={visible}
      footer={footer}
      width='80%'
      bodyStyle={{ padding: '15px', overflowX: 'auto', height: '80vh' }}
      centered destroyOnClose
      onCancel={() => { close() }}
    >
      {
        !animated && <Spin spinning={waiting}>
          <AssetAction 
            ref={basicRef}
            dirId={nodeId} 
            action='add'
            template={template}
          />
        </Spin>
      }
    </Modal>
  )
}

export default FC