/*
 * @Description:定出Excel文件方法封装处理
 * @Author: Rockery
 * @Date: 2021-04-20 14:01:42
 * @LastEditors: Rockery
 * @LastEditTime: 2021-04-26 15:55:00
 * @FilePath: \pc_web\src\utils\exportexcel.js
 * @Copyright: Copyright (c) 2016~2021 Rockery(1113269755@qq.com)
 */

import { parseTime } from "@/utils/ruoyi";
import { Message } from 'element-ui';

/**
 * 导出Excel文件
 * @param {*} data 文件数据流
 * @param {String} filePrefix 文件前缀名
 * @param {String} fileSuffix 文件后缀名
 */
export function exportExcel(data, filePrefix, fileSuffix) {
  // 判断文件前缀名是否存在，不存在默认'EXPORTEXCEL'
  filePrefix = filePrefix ?? 'EXPORTEXCEL';
  // 判断文件后缀名是否存在，不存在默认'.xls'
  fileSuffix = fileSuffix ?? '.xls';

  // 处理文件数据流
  const contentByExportExcel = data;
  const blobByExportExcel = new Blob([contentByExportExcel], { type: "application/vnd.ms-excel;charset=utf-8" });

  // 组装文件名称
  const filenameByExportExcel = `${filePrefix}_${parseTime(new Date(), "{y}-{m}-{d}")}_${new Date().getTime()}${fileSuffix}`;

  // 执行文件下载操作
  if ('download' in document.createElement('a')) {
    const elink = document.createElement('a');
    elink.download = filenameByExportExcel;
    elink.style.display = 'none';
    elink.href = URL.createObjectURL(blobByExportExcel);
    document.body.appendChild(elink);
    elink.click();
    URL.revokeObjectURL(elink.href);
    document.body.removeChild(elink);
    Message({
      message: "导出Excel成功！",
      type: 'success',
      showClose: true,
      center: true
    });
  } else {
    navigator.msSaveBlob(blobByExportExcel, filenameByExportExcel);
    Message({
      message: "导出Excel成功！",
      type: 'success',
      showClose: true,
      center: true
    });
  }
}
