import XLSX from 'xlsx'
import { saveAs } from 'file-saver'

function s2ab (s) {
  const buf = new ArrayBuffer(s.length)
  const view = new Uint8Array(buf)
  for (let i = 0; i !== s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF
  return buf
}

export default function json2xlsx (json, {sheetName = 'sheet1', filename = 'statistics.xlsx'} = {}) {
  const wb = {
    SheetNames: [],
    Sheets: {},
    Props: {
      Title: '小云蜂巢数据统计',
      Author: '小云蜂巢'
    }
  }
  const ws = XLSX.utils.json_to_sheet(json)
  XLSX.utils.book_append_sheet(wb, ws, sheetName)
  const wbout = XLSX.write(wb, {
    bookType: 'xlsx',
    bookSST: false,
    type: 'binary'
  })
  saveAs(new Blob([s2ab(wbout)], { type: 'application/octet-stream' }), filename)
}
