import { Button, Col, Icon, message, Modal, Upload } from 'antd';
import React from 'react';
import { config, networkUtils, stringUtils } from '../../utils';
import file from './file.svg';
import styles from './UploadEL.less';

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

class UploadEL extends React.PureComponent {
  constructor(props) {
    super(props);
    const {
      listType,
    } = props;
    this.state = {
      previewVisible: false,
      previewImage: '',
      accept: '',
      listType: listType || 'text',
      fileList: [],
      uploading: false,
      repoInfo: null,
      tokenInfo: null,
    };
  }

  public componentDidMount = () => {
    const { disabled, api, dataKey } = this.props;
    this.fetchTokenInfo(api).then(
      (data) => {
        if (data.success) {
          this.fetchRepoInfo().then((info) => {
            this.fetchList();
          });
        } else {
          message.error(data.message);
        }
      },
    );
  };

  public componentWillReceiveProps = (nextProps) => {
    if (!nextProps.api) {
      this.setState({
        fileList: [],
      });
    }
  };

  public fetchRepoInfo = () => {
    const { tokenInfo } = this.state;
    return new Promise((resolve) => {
      tokenInfo !== null && networkUtils.request({
        url: sfs.repoInfo.replace('{api}', tokenInfo.ownerApi),
        method: 'get',
        data: { ...tokenInfo },
      }).then((data) => {
        this.setState({
            repoInfo: data.data,
          },
          () => {
            resolve(data);
          });
      });
    });
  };

  public fetchTokenInfo = (api) => {
    return new Promise((resolve) => {
      api !== undefined && networkUtils.request({
        url: api,
        method: 'get',
      }).then((data) => {
        this.setState({
          tokenInfo: data.data,
        }, () => {
          resolve(data);
        });
      });
    });
  };

  public fetchList = () => {
    const { disabled, api, dataKey } = this.props;
    const { tokenInfo, repoInfo } = this.state;
    api !== undefined && networkUtils.request({
      url: sfs.list.replace('{api}', api),
      method: 'get',
      data: { dataKey, ...tokenInfo },
    }).then((data) => {
      if (data.success) {
        this.setState({
          fileList: data.data.map((f) => {
            const url = `${baseURL}${sfs.download}?${stringUtils.JSON2QueryString({
              'hash': f.itemHash,
              dataKey,
              ...tokenInfo,
              'el-xsrf': localStorage.getItem('csrfToken'),
              '_t': Date.parse(new Date()) / 1000,
            })}`;

            return {
              uid: f.itemName,
              name: f.itemName,   // 文件名
              url: f.itemMime.indexOf('image') === 0 ? url : file,
              thumbUrl: f.itemMime.indexOf('image') === 0 ? url : file,
              link: url,
              // status: 'done', // 状态有：uploading done error removed
              // response: { 'status': 'success' }, // 服务端响应内容
              // linkProps: '{"download": "image"}', // 下载链接额外的 HTML 属性
              ...f,
            };
          }),
        });
      } else {
        throw data;
      }
    });
  };

  public handleUpload = (req) => {
    // console.log(req);
    const { tokenInfo } = this.state;
    const { api, dataKey } = this.props;

    const formData = new FormData();

    formData.append('file', req.file);
    formData.append('dataKey', dataKey);
    Object.keys(tokenInfo).forEach((key) => {
      formData.append(key, tokenInfo[key]);
    });

    networkUtils.request({
      url: sfs.upload.replace('{api}', api),
      method: 'upload',
      data: formData,
    }).then((data) => {
      if (data.success) {
        message.success('上传成功.');
        this.fetchList();
        // this.setState({
        // fileList: [],
        // uploading: false,
        // });
      } else {
        // console.log(req, data);
        // this.setState({
        //   uploading: false,
        // });
        message.error(data.message);
        // throw data;;
      }
    });
  };

  public reqRemove = (file) => {
    // console.log(file);
    const { api, dataKey } = this.props;
    const { tokenInfo } = this.state;
    networkUtils.request({
      url: sfs.delete,
      method: 'form',
      params: {
        ...tokenInfo,
        dataKey,
        hash: file.itemHash,
      },
    }).then((data) => {
      if (data.success) {
        message.success('删除成功!');
        this.fetchList();
      } else {
        throw data;

      }
    });
  }

  public handleRemove = (file) => {
    const _this = this;
    const { listType } = this.state;
    if (listType === 'text') {
      confirm({
        title: '确定要删除此附件么?',
        okType: 'danger',
        onOk() {
          // console.log('OK');
          _this.reqRemove(file);
        },
        onCancel() {
          // console.log('Cancel');
        },
      });
    } else {
      _this.reqRemove(file);
    }
  };

  public downloader = (url, fileName) => {
    const a = document.createElement('a');
    // a.style = 'display: none';
    a.style.display = 'none';
    a.download = fileName;
    a.href = url;
    a.target = '_blank';

    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
  };

  public batchDownload = () => {
    this.state.fileList.map((file) => {
        networkUtils.request({
          url: sfs.download.replace('{repo}', this.props.repo).replace('{file}', file.fileName),
          method: 'get',
        }).then((data) => {
          if (data.success) {
            // message.success('下载成功!');
            // this.fetchList()
            this.downloader(data.data, file.fileName);
          } else {
            throw data;

          }
        });
      },
    );
  };

  public handlePreview = (file) => {
    // console.log(file);
    if (file.itemMime.indexOf('image') === 0) {
      this.setState({
        previewImage: file.url || file.thumbUrl,
        previewVisible: true,
      });
    } else {
      this.downloader(file.link, file.itemName);
    }
  };

  public handleCancel = ({ fileList }) => this.setState({
    previewVisible: false,
    previewImage: '',
  });

  public render() {
    const { uploading, repoInfo, fileList, previewVisible, previewImage } = this.state;
    const { disabled, api, size, listType, beforeUpload, ...otherProps } = this.props;
    const props = {
      accept: repoInfo && repoInfo.accept || '',
      listType,
      multiple: true,
      action: sfs.upload.replace('{api}', api),
      customRequest: this.handleUpload,
      onRemove: this.handleRemove,
      onPreview: this.handlePreview,
      beforeUpload,
      fileList,
      disabled,
      showUploadList: { showRemoveIcon: !disabled },
    };

    return (
      <div>
        <Modal closable={false} visible={previewVisible} footer={<div>
          <Button size={'small'} onClick={this.downloader.bind(this, previewImage)}>
            <Icon type="download"/>
          </Button>
          <Button size={'small'} onClick={this.handleCancel}>
            <Icon type="close"/>
          </Button>
        </div>} onCancel={this.handleCancel}>
          <img alt="preview" style={{ width: '100%' }} src={previewImage}/>

        </Modal>
        {/*<div></div>*/}
        <Col className={styles.zone}>
          <Upload {...props} fileList={fileList}>
            {!disabled && <Button size={size}>
              <Icon type="upload"/>{'选择文件'}
            </Button>}
          </Upload>
        </Col>
      </div>
    );
  }
}

export default UploadEL;
