import React, { useState } from 'react';
import { Button, Upload, Modal } from 'antd';
import { DownloadOutlined, UploadOutlined } from '@ant-design/icons';

import { dispatchLatest } from '../../../../model'; 
import { showMessage } from '../../../../util';
import { getTemplateType } from '../../../../util/axios';

const ImportElement = (props) => {
  const { onCancel, visible } = props;
  const [ fileList, setFileList ] = useState([]);
  const [ confirmLoading, setConfirmLoading ] = useState(false);

  const downloadTemplate = () => {
    window.open(`/api/dataassetmanager/elementApi/getImportTemplate?templateType=${getTemplateType()}`);
  }

  const uploadProps = {
    onRemove: file => {

      const index = fileList.indexOf(file);
      const newFileList = fileList.slice();
      newFileList.splice(index, 1);

      setFileList(newFileList);
    },
    beforeUpload: file => {
      
      setFileList([file]);
      return false;
    },
    fileList: fileList||[],
    accept:".xlsx",
  };

  const handleOk = () => {

    if ((fileList||[]).length === 0) {
      showMessage('info', '请先选择模板上传');
      return;
    }

    setConfirmLoading(true);
    dispatchLatest({
      type: 'assetmanage.importElement',
      payload: { fileList },
      callback: data => {
        setConfirmLoading(false);
        reset();
        onCancel && onCancel(false, true, data);
      },
      error: () => {
        setConfirmLoading(false);
      }
    })
  }

  const reset = () => {
    setFileList([]);
  }

  return (
    <Modal 
      forceRender
      visible={visible}
      title='资产目录属性导入'
      width={520}
      confirmLoading={confirmLoading}
      onCancel={() => {
        reset();
        onCancel && onCancel();
      }}
      onOk={handleOk}
    >
      <div>
        <Button icon={<DownloadOutlined />} onClick={ downloadTemplate }>
        模板下载
        </Button>
      </div>
      <div className='mt-3'>
        <Upload {...uploadProps}>
          <Button icon={<UploadOutlined />}>
            选择文件上传
          </Button>
        </Upload>
      </div>
    </Modal>
  )
}

export default ImportElement;