/* oss.sheetjs.com (C) 2014-present SheetJS -- http://sheetjs.com */
/* vim: set ts=2: */

var DropSheet = function DropSheet(opts) {
  if(!opts) opts = {};
  var nullfunc = function(){};
  if(!opts.errors) opts.errors = {};
  if(!opts.errors.badfile) opts.errors.badfile = nullfunc;
  if(!opts.errors.pending) opts.errors.pending = nullfunc;
  if(!opts.errors.failed) opts.errors.failed = nullfunc;
  if(!opts.errors.large) opts.errors.large = nullfunc;
  if(!opts.on) opts.on = {};
  if(!opts.on.workstart) opts.on.workstart = nullfunc;
  if(!opts.on.workend) opts.on.workend = nullfunc;
  if(!opts.on.sheet) opts.on.sheet = nullfunc;
  if(!opts.on.wb) opts.on.wb = nullfunc;

  var rABS = false; // typeof FileReader !== 'undefined' && FileReader.prototype && FileReader.prototype.readAsBinaryString;
  var useworker = typeof Worker !== 'undefined';
  var pending = false;

  function sheetjsw(data, cb, readtype) {
    pending = true;
    opts.on.workstart();
    var scripts = document.getElementsByTagName('script');
    var dropsheetPath;
    for (var i = 0; i < scripts.length; i++) {
      if (scripts[i].src.indexOf('dropsheet') != -1) {
        dropsheetPath = scripts[i].src.split('dropsheet')[0];
      }
    }
    var worker = new Worker(dropsheetPath + 'sheetjsw.js');
    worker.onmessage = function(e) {
      switch(e.data.t) {
        case 'ready': break;
        case 'e': pending = false; console.error(e.data.d); break;
        case 'xlsx':
          pending = false;
          opts.on.workend();
          cb(JSON.parse(e.data.d)); break;
      }
    };
    worker.postMessage({d:data,b:readtype,t:'xlsx'});
  }

  var last_wb;

  function to_json(workbook) {
    if(useworker && workbook.SSF) XLSX.SSF.load_table(workbook.SSF);
    var result = {};
    workbook.SheetNames.forEach(function(sheetName) {
      var roa = XLSX.utils.sheet_to_json(workbook.Sheets[sheetName], {raw:false, header:1});
      if(roa.length > 0) result[sheetName] = roa;
    });
    return result;
  }

  function choose_sheet(sheetidx) { process_wb(last_wb, sheetidx); }

  function process_wb(wb, sheetidx) {
    last_wb = wb;
    opts.on.wb(wb, sheetidx);
    var sheet = wb.SheetNames[sheetidx||0];
    var json = to_json(wb)[sheet];
		console.log(wb);
    opts.on.sheet(json, wb.SheetNames, choose_sheet);
  }

  function handleDrop(e) {
    e.stopPropagation();
    e.preventDefault();
    if(pending) return opts.errors.pending();
    var files = e.dataTransfer.files;
    var i,f;
    for (i = 0, f = files[i]; i != files.length; ++i) {
      var reader = new FileReader();
      var name = f.name;
      reader.onload = function(e) {
        var data = e.target.result;
        var wb, arr;
        var readtype = {type: rABS ? 'binary' : 'array' };
        function doit() {
          try {
            if(useworker) { sheetjsw(data, process_wb, readtype); return; }
            wb = XLSX.read(data, readtype);
            process_wb(wb);
          } catch(e) { console.log(e); opts.errors.failed(e); }
        }

        if(e.target.result.length > 1e6) opts.errors.large(e.target.result.length, function(e) { if(e) doit(); });
        else { doit(); }
      };
      if(rABS) reader.readAsBinaryString(f);
      else reader.readAsArrayBuffer(f);
    }
  }

  function handleDragover(e) {
    e.stopPropagation();
    e.preventDefault();
    e.dataTransfer.dropEffect = 'copy';
  }

  if(opts.drop.addEventListener) {
    opts.drop.addEventListener('dragenter', handleDragover, false);
    opts.drop.addEventListener('dragover', handleDragover, false);
    opts.drop.addEventListener('drop', handleDrop, false);
  }
  //官方写法
  /*function handleFile(e) {
    if(pending) return opts.errors.pending();
    var files = e.target.files;
    var i,f;
    for (i = 0, f = files[i]; i != files.length; ++i) {
      var reader = new FileReader();
      var name = f.name;
      reader.onload = function(e) {
        var data = e.target.result;
        var wb, arr;
        var readtype = {type: rABS ? 'binary' : 'array' };
        function doit() {
          try {
            if(useworker) { sheetjsw(data, process_wb, readtype); return; }
            wb = XLSX.read(data, readtype);
            process_wb(wb);
          } catch(e) { console.log(e); opts.errors.failed(e); }
        }

        if(e.target.result.length > 1e6) opts.errors.large(e.target.result.length, function(e) { if(e) doit(); });
        else { doit(); }
      };
      if(rABS) reader.readAsBinaryString(f);
      else reader.readAsArrayBuffer(f);
    }
  }*/
  //重写,通过url获取文件对象
  function handleFile(file) {
    if(pending) return opts.errors.pending();
    var reader = new FileReader();
    reader.onload = function(e) {
      var data = e.target.result;
      var wb, arr;
      var readtype = {type: rABS ? 'binary' : 'array' };
      function doit() {
        try {
          if(useworker) { sheetjsw(data, process_wb, readtype); return; }
          wb = XLSX.read(data, readtype);
          process_wb(wb);
        } catch(e) { console.log(e); opts.errors.failed(e); }
      }

      if(e.target.result.length > 1e6) opts.errors.large(e.target.result.length, function(e) { if(e) doit(); });
      else { doit(); }
    };
    if(rABS) reader.readAsBinaryString(file);
    else reader.readAsArrayBuffer(file);
  }

  if(opts.file && opts.file.addEventListener) opts.file.addEventListener('change', handleFile, false);
  function getFileFromUrl(url, fileName) {
    return new Promise((resolve, reject) => {
      var blob = null;
      var xhr = new XMLHttpRequest();
      xhr.open("GET", url);
      //此处类型依据具体情况设置
      xhr.setRequestHeader('Accept', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
      xhr.responseType = "blob";
      // 加载时处理
      xhr.onload = () => {
        // 获取返回结果
        blob = xhr.response;
        //此处类型依据具体情况设置，同上
        let file= new File([blob], fileName, { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
        // 返回结果
        resolve(file);
      };
      xhr.onerror = (e) => {
        reject(e)
      };
      // 发送
      xhr.send();
    });
  }
  function getUrlParam(name) {
    let url=window.location.href;
    let index = url.indexOf("?");
    let paramStr = url.substr(index,url.length);
    let reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
    let r = paramStr.substr(1).match(reg);  //匹配目标参数
    if (r != null){
      return decodeURI(r[2]);//返回参数值
      //return unescape(r[2]);// unescape()会乱码
    }else{
      return null;
    }
  }
  //let fileUrl='http://big-model.kanhouchu.com/minio-big-model/202312/SheetJSTest.xlsx';
  //let fileUrl='../sheetjs/SheetJSTest.xlsx';
  let fileUrl=getUrlParam('file')
  if(fileUrl!=null&&fileUrl.length>0){
    let file=null;
    let fileName=getUrlParam('fileName');
    fileUrl = atob(fileUrl);
    fileUrl = decodeURIComponent(fileUrl);
    if(fileName==null||fileName.length==0){
      fileName = fileUrl.split("/").pop();
    }
    console.log(1111)
    document.querySelector('title').innerText=fileName;
    getFileFromUrl(fileUrl,fileName)
        .then((response)=>{
          file = response
          if(file.size==92){
            alert('请检查文件路径');
          }else{
            handleFile(file);
          }
        })
        .catch((e)=>{
          console.error(e)
        });
  }
};