/**
 * 导出excel格式的表格
 * param:
 * 1、params（Object）：查询条件
 * 2、apiurl（String）：请求接口
 * 3、method（String）：请求方法
 * 4、downloadname（String）：下载文件名
 */
import React, { Component } from "react";
import { Button } from 'antd';
import axios from 'axios';
import { getHostByPath } from '../../utils/config'
// import { host } from '../../services/api';
import store from 'store';
export default class ExcelButton extends Component {
  constructor(props, context) {
    super(props, context);
    this.state = {

    };
  }
  componentDidMount() {

  }
  componentWillReceiveProps(props) {

  }

  render() {
    return (
      <Button
        {...this.props}
        type="primary"
        onClick={() => {
          const { params, apiurl, disable, method = 'GET', downloadname = '百宝盾' } = this.props;
          // if(disabled) return;
          let queryStr = '?';
          if (params) {
            Object.keys(params).forEach(key => {
              queryStr += `${key}=${params[key]}&`;
            });
          }
          queryStr = queryStr.slice(0, -1);
          if (!apiurl) return;
          const url = getHostByPath()+`${apiurl}${queryStr}`;
          axios({
            method,
            url, //后台请求地址
            responseType: 'blob',
            headers: {
              access_token: store.get('saas')['access_token']
            }
          }).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', `${downloadname}.xls`);
            document.body.appendChild(link);
            link.click();
            this.props.onClick && this.props.onClick();
          });
        }}
      >
        {this.props.children}
      </Button>
    );
  }
}

export const excelButtonHOC = (props, Btn) => {
  const onClick = props.onClick;
  props.onClick =  () => {
    const { params, apiurl, disable, method = 'GET', downloadname = '百宝盾' } = props;
    // if(disabled) return;
    let queryStr = '?';
    if (params) {
      Object.keys(params).forEach(key => {
        queryStr += `${key}=${params[key]}&`;
      });
    }
    queryStr = queryStr.slice(0, -1);
    if (!apiurl) return;
    const url = getHostByPath()+`${apiurl}${queryStr}`;
    axios({
      method,
      url, //后台请求地址
      responseType: 'blob',
      headers: {
        access_token: store.get('saas')['access_token']
      }
    }).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', `${downloadname}.xls`);
      document.body.appendChild(link);
      link.click();
      onClick && onClick();
    });
  }
  return (
    <Btn {...props}>{props.children}</Btn>
  );
}