import React from 'react';
import { Button, Icon, Tooltip, Upload } from 'antd';
import { config, networkUtils } from '@utils';
import styles from './index.less';
import Base64 from 'base64-js';

const { api ,baseURL} = config;
const { sfs } = api;

const onUpload = (repo, fileList) => {
  const formData = new FormData();
  fileList.forEach((file) => {
    formData.append('files', file);
  });

  networkUtils.request({
    url: sfs.upload.replace('{api}', repo),
    method: 'upload',
    data: formData,
  }).then((data) => {
    if (data.success) {
      console.log('上传成功：', data);
    } else {
      console.log('上传失败.');
      throw data;;
    }
  });
};

const onDelete = (repo, fileName) => {
  networkUtils.request({
    url: sfs.delete.replace('{repo}', repo).replace('{file}', fileName),
    method: 'post',
  }).then((data) => {
    if (data.success) {
      console.log('删除成功!');
    } else {
      throw data;;
    }
  });

};

const downloader = (data, fileName) => {
  const a = document.createElement('a');
  a.style.display = 'none';
  document.body.appendChild(a);

  const blob = new Blob([Base64.toByteArray(data)]);
  if ('msSaveOrOpenBlob' in window.navigator) {
    window.navigator.msSaveOrOpenBlob(blob, fileName);
  } else {
    const url = window.URL.createObjectURL(blob);
    a.href = url;
    a.download = fileName;
    a.click();
    window.URL.revokeObjectURL(url);
  }
};

const onDownload = (repo, fileName) => {
  networkUtils.request({
    url: sfs.download.replace('{repo}', repo).replace('{file}', fileName),
    method: 'get',
  }).then((data) => {
    if (data.success) {
      downloader(data.data, fileName);
    } else {
      throw data;;
    }
  });
}

const render = (fileName, beforeUpload, onRemove, onDownload,disabled) => {
  const props = {
    beforeUpload,
    onRemove,
  };
  return (<div>
    <Upload {...props} showUploadList={false}  disabled={disabled}>
      <Button><Icon type="upload"/></Button>
    </Upload>

    {fileName &&
      <div className={styles.upload}>
        <Icon type="paper-clip" />
        <Tooltip placement="topLeft" title={fileName}>
          <span onClick={onDownload}>{fileName}</span>
        </Tooltip>
        {!disabled &&<Icon type="close" className={styles.uploadClose} onClick={onRemove} />}
      </div>
    }
  </div>);
};


export default {
  onUpload,
  onDelete,
  onDownload,
  render,
};
