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

import { dispatch } from '../../../../model';
import { showNotifaction } from '../../../../util';
import { getTemplateType } from '../../../../util/axios';

const ImportDirectory = (props) => {
  const { visible, onCancel, dirId } = props;
  const [ uploading, setUploading ] = useState(false);
  const [ fileList, setFileList ] = useState([]);
  const [ form ] = Form.useForm();
  const [ dir, setDir ] = useState(null);
  const [modal, contextHolder] = Modal.useModal();

  useEffect(() => {

    if(visible) {

      form.resetFields();
      setFileList([]);

      if ((dirId||'')!=='') {
        getDirectory();
      }
    }
    //eslint-disable-next-line react-hooks/exhaustive-deps
  }, [ visible, dirId ])

  const getDirectory = () => {
    setDir(null);
    dispatch({
      type: 'assetmanage.getDirectoryById',
      payload: { 
        dirId
      },
      callback: data => {
        setDir(data);
      }
    })
  }

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

  const upload = async (ignoreRepeatPath = false) => {

    try {
      const row = await form.validateFields();
      
      setUploading(true);

      const payload = { 
        params: {
          ignoreRepeatPath
        },
        fileList: fileList,
      };

      dispatch({
        type: 'assetmanage.directoryImport',
        payload: payload,
        callback: data => {
          setUploading(false);

          if (!ignoreRepeatPath) {
            if (!data.existRepeatPath) {
              onCancel && onCancel(true, (row.type==='root'? true : false));
              const msg = (data.message||'').replace(RegExp(";", "g"),"<br />")
              showNotifaction('导入提示', msg, 5);
            } else {
              modal.confirm({
                title: '提示',
                content: (
                  <div style={{ maxHeight: '70vh', overflow: 'auto' }}>
                  {`${data.message||'存在重复路径'}，确定导入吗?`}
                  </div>
                ),
                onOk: () => {
                  upload(true);
                }
              })
            }
          } else {
            onCancel && onCancel(true, (row.type==='root'? true : false));
            const msg = (data.message||'').replace(RegExp(";", "g"),"<br />")
            showNotifaction('导入提示', msg, 5);
          }
        },
        error: () => {
          setUploading(false);
        }
      })

    } catch (errInfo) {
      console.log('Validate Failed:', errInfo);
    }
  }

  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;
    },
    accept:".xlsx",
    fileList: fileList||[]
  };

  const formItemLayout = {
    labelCol: {
      xs: { span: 24 },
      sm: { span: 5 },
    },
    wrapperCol: {
      xs: { span: 24 },
      sm: { span: 17 },
    },
  };

  return (
    <Modal
      title={`目录导入`}
      visible={visible}
      onCancel={() => { onCancel && onCancel() }}
      footer={
        <Space>
          <Button type="primary" onClick={ download } >模板下载</Button>
          <Button type="primary" onClick={() => { upload(false); } } loading={uploading}>上传</Button>
          <Button onClick={() => { onCancel && onCancel() }}>返回</Button>
        </Space>
      }
    >
      <Form {...formItemLayout} form={form}>
        <Form.Item 
          label="挂载位置"
          // name="type"
          rules={[{ required: true, message: '必填项'}]}
        >
          <span>根节点导入</span>
        </Form.Item>
        <Form.Item 
          label="文件"
          name="file"
          rules={[{ required: true, message: '请上传附件'}]}
        >
          <Upload {...uploadProps}>
            <Button icon={<UploadOutlined />}>
              选择文件上传
            </Button>
          </Upload>
        </Form.Item>
      </Form>
      {contextHolder}
    </Modal>
  );
}

export default ImportDirectory;