/**
 * @describe 下载.xls文件
 * @param
 * 1、url（下载的路径）例：url='/public/bayzgz-sb/export-committed-bayzgz-sb-info'
 * 2、visible（按钮是否显示的状态，默认是可点击。true不可点，false可点）
 * 3、method（请求方式，不设置默认是get方法）
 * 4、searchData（请求参数，是个object）
 * 5、fileName(下载的文件需要叫什么名字)
 * 6、buttonName（按钮的名字，默认叫“下载”）
 */

import React, { Component } from 'react';
import { Button } from 'antd';
import * as api from '../../services/api';
import store from 'store';
import axios from 'axios';

export default class DownloadXls extends Component {
  constructor(props, context) {
    super(props, context);
    this.state = {
      method: 'get', //默认是用‘get’请求方式
      visible: false, //按钮展示状态，默认是可点击的
      url: props.url,
      searchData: props.searchData,
      fileName: 'upload.xls', //文件名
      buttonName: '下载'
    };
  }

  componentWillReceiveProps(nextprops) {
    this.setState({
      visible: nextprops.visible,
      searchData: nextprops.searchData,
      fileName: nextprops.fileName,
      method: nextprops.method,
      buttonName: nextprops.buttonName
    });
  }

  render() {
    return (
      <Button
        type="primary"
        disabled={this.state.visible}
        onClick={() => {
          axios({
            method: this.state.method,
            url: `${api.host}` + this.state.url, //后台请求地址
            params: {
              ...this.state.searchData
            },
            responseType: 'blob',
            headers: {
              access_token: store.get('saas')['access_token'],
        Accesstoken: store.get('saas')['access_token']|| sessionStorage.userV5Token,

            }
          }).then(data => {
            if (!data) {
              return;
            }
            let url = window.URL.createObjectURL(data.data);
            let link = document.createElement('a');
            link.style.display = 'none';
            link.href = url;
            link.setAttribute('download', this.state.fileName);
            document.body.appendChild(link);
            link.click();
          });
        }}
      >
        {this.state.buttonName}
      </Button>
    );
  }
}
