import ExcelJS from 'exceljs'

/**
 * 导出 excel
 * @param fileName
 * @param handler
 * @param drawBorder [rowLength, colLength]
 */
export const exportTempExcel = async (
  fileName: string,
  handler: (worksheet: ExcelJS.Worksheet, workbook: ExcelJS.Workbook) => void,
  drawBorder?: [number, number]
) => {
  const workbook = new ExcelJS.Workbook()
  const worksheet = workbook.addWorksheet('Sheet1', {
    properties: { defaultRowHeight: 30 },
    views: [{ showGridLines: false }],
    pageSetup: {
      horizontalCentered: true,
      verticalCentered: true,
      paperSize: 9
    }
  })

  handler(worksheet, workbook)

  if (drawBorder) {
    const borderStyle: ExcelJS.Border = {
      style: 'thin',
      color: { argb: 'FF000000' }
    }

    for (let row = 1; row <= drawBorder[0]; row++) {
      for (let col = 1; col <= drawBorder[1]; col++) {
        const cell = worksheet.getCell(row, col)
        cell.border = {
          top: borderStyle,
          left: borderStyle,
          bottom: borderStyle,
          right: borderStyle
        }
      }
    }

    worksheet.eachRow(row => {
      row.eachCell(cell => {
        cell.alignment = {
          vertical: 'middle',
          horizontal: 'center',
          wrapText: true
        }
      })
    })
  }

  const buffer = await workbook.xlsx.writeBuffer()
  const blob = new Blob([buffer], {
    type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
  })

  const url = URL.createObjectURL(blob)
  const a = document.createElement('a')
  a.href = url
  a.download = fileName + '.xlsx'
  a.click()

  // 释放内存
  setTimeout(() => URL.revokeObjectURL(url), 100)
}

export const getImageBase64Extension = (str: string): 'jpeg' | 'png' | 'gif' | null => {
  const base64Regex = /^data:image\/([a-zA-Z+]*);base64,([^\s]*)$/

  if (!base64Regex.test(str)) {
    return null
  }

  // 提取MIME类型
  const matches = str.match(base64Regex)
  if (!matches || matches.length < 2) {
    return null
  }

  const mimeType = matches[1].toLowerCase()

  // 只允许jpeg/jpg/png/gif三种类型
  switch (mimeType) {
    case 'jpeg':
    case 'jpg':
      return 'jpeg'
    case 'png':
      return 'png'
    case 'gif':
      return 'gif'
    default:
      return null
  }
}
