/**
 *  @name:gw_exportModel
 *  用途:
 *         主要用于创建XMLHttpRequest对象请求处理导出word、excel。
 *  @author:tanghy
 *  @version:0.1.0
 */

export function exportModel(type, url, exportName, data) {
  return new Promise((resolve) => {
    // promise 对象的表达式
    let loadState = true; // 这里定义默认加载状态为true
    var xhr = new XMLHttpRequest(); // XMLHttpRequest 对象
    xhr.open(type, url, true); // 方式，url为服务器请求地址，true
    xhr.responseType = 'blob';
    xhr.setRequestHeader('Content-Type', 'application/json;charset=utf-8');
    xhr.setRequestHeader(
      'persId',
      localStorage.getItem('persId') ? localStorage.getItem('persId') : '',
    );
    xhr.setRequestHeader(
      'accessToken',
      localStorage.getItem('accessToken')
        ? localStorage.getItem('accessToken')
        : '',
    );
    xhr.setRequestHeader(
      'orgId',
      localStorage.getItem('orgId') ? localStorage.getItem('orgId') : '',
    );
    xhr.onload = function () {
      if (this.status == 200) {
        loadState = false;
        resolve(loadState); // 用于返回组件判断loading显隐
        var blob = this.response;
        var a = document.createElement('a');
        var url = window.URL.createObjectURL(blob);
        a.href = url;
        // 设置文件名称
        a.download = exportName;
        a.click();
      }
    };
    xhr.send(data);
  });
}
