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

import SelectAsset from './select-asset'
import SelectDataService from './select-data-service'
import { dispatch } from '../../../../model';

const FC = ({ visible, item, type, 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 = (data = null) => {
    setWaiting(false)
    setAnimated(true)
    onCancel?.(data)
  }

  const save = async () => {
    const selectedRows = basicRef.current?.selectedRows
    if ((selectedRows??[]).length === 0) {
      message.warn(type==='asset'?'请先选择资产':'请先选择服务')
      return
    }

    if (type === 'asset') {
      setWaiting(true)
      dispatch({
        type: 'assetmanage.fillRelationDisplayInfo',
        payload: {
          relatedDataAssetIds: (selectedRows??[]).map(item => item.id).toString()     
        },
        callback: (data) => {
          setWaiting(false)
          close(data)
        },
        error: () => {
          setWaiting(false)
        }
      })
    } else {
      close((selectedRows??[]).map(item => ({
        cnName: item.basicInfo?.cnName,
        name: item.basicInfo?.name,
        path: item.path,
        relatedServiceCode: item.basicInfo?.code,
        relatedServiceId: item.id,
        remark: item.remark,
      })))
    }
  }

  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={type==='asset'?'新增资产':'新增服务'}
      visible={visible}
      footer={footer}
      width='80%'
      bodyStyle={{ padding: '15px', overflowX: 'auto', height: '80vh' }}
      centered destroyOnClose
      onCancel={() => { close() }}
    >
      {
        !animated && <Spin spinning={waiting}>
          <Basic ref={basicRef} type={type} />
        </Spin>
      }
    </Modal>
  )
}

export default FC

const Basic = React.forwardRef(function ({ type }, ref) {
  const [selectedRows, setSelectedRows] = React.useState()

  React.useImperativeHandle(ref, () => ({
    selectedRows
  }), [selectedRows])

  const onChange = (val) => {
    setSelectedRows(val)
  }

  return (
    <div>
      {
        type === 'asset' && <SelectAsset onChange={onChange} />
      }
      {
        type === 'service' && <SelectDataService onChange={onChange} />
      }
    </div>
  )
})