import * as XLSX from 'xlsx'

/**
 * 导出 Excel 文件
 * @param data 数据数组
 * @param filename 文件名
 * @param sheetName 工作表名称
 */
export function exportToExcel<T = any>(data: T[], filename: string, sheetName: string = 'Sheet1') {
  const ws = XLSX.utils.json_to_sheet(data) // 转换为工作表
  const wb = XLSX.utils.book_new() // 创建新工作簿
  XLSX.utils.book_append_sheet(wb, ws, sheetName) // 将工作表添加到工作簿
  XLSX.writeFile(wb, `${filename}.xlsx`) // 写入文件
}

/**
 * 读取 Excel 文件
 * @param file 文件对象
 * @returns Promise<T[]> 解析后的数据数组
 */
export function readExcel<T = any>(file: File): Promise<T[]> {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.onload = (e) => {
      try {
        const data = e.target?.result
        const workbook = XLSX.read(data, { type: 'binary' })
        const sheetName = workbook.SheetNames[0]
        const sheet = workbook.Sheets[sheetName]
        const json = XLSX.utils.sheet_to_json<T>(sheet)
        resolve(json)
      }
      catch (error) {
        reject(error)
      }
    }
    reader.onerror = error => reject(error)
    reader.readAsArrayBuffer(file)
  })
}
