import * as ExcelJS from 'exceljs'
import { saveAs } from 'file-saver'
import imageToBase64 from 'image-to-base64/browser'

const obtenerExtensionImagen = (path) => {
  const ext = path.split('.').pop();
  return ext.toLowerCase();
}

const exportarExcelJS = async (
  columnas,
  datos,
  nombre = "archivo-excel",
  titulo = "archivo-excel",
  subtitulo = "",
  path = null
) => {


  try {
    const workbook = new ExcelJS.Workbook()
    const worksheet = workbook.addWorksheet(titulo.replace(/[^a-zA-Z ]/g, ""))

    if( path !== null && typeof path === 'string' ) {
      const img64 = await imageToBase64(path)
      const idImagen = workbook.addImage({
        base64: img64,
        extension: obtenerExtensionImagen(path), 
      })

      worksheet.addImage( idImagen, {
        tl: { col: 1.5, row: 0.5 },
        br: { col: 2.5, row: 3.5 },
        editAs: 'oneCell'
      })
    }

    const cols = columnas
    const data = datos
    const header = cols.map(c => (c.title));

    worksheet.columns = cols

    const styleTitle = {
      font: {
        bold: true,
        size: 18,
      },
      aligment: {
        horizontal: 'center',
        vertical: 'center',
        wrapText: true
      },
    }

    const styleSubTitle = {
      font: {
        bold: false,
        size: 15,
      },
      aligment: {
        horizontal: 'center',
        vertical: 'center',
        wrapText: true
      },
    }

    worksheet.mergeCells('A1:F4')
    worksheet.mergeCells('A5:F5')
    worksheet.mergeCells('A6:F6')

    worksheet.addRow(header)
    for( let i = 0; i < data?.length; i++ ) {
      let row = data[i]
      worksheet.addRow(row)
    }

    worksheet.columns.forEach(( column ) => {
      var dataMax = 0;
      column.eachCell({ includeEmpty: true }, (cell) => {
        var columnLength = cell.value?.length;
        if( columnLength > dataMax ) {
          dataMax = columnLength;
        }
      })
      column.width = dataMax < 10 ? 10 : dataMax;
    })

    const colA = worksheet.getColumn("A")
    colA.width = 15
    const colB = worksheet.getColumn("B")
    colB.width = 15
    const colC = worksheet.getColumn("C")
    colC.width = 15

    worksheet.getCell('A5').value = titulo.replace(/[^a-zA-Z ]/g, "")
    worksheet.getCell('A5').style = styleTitle
    worksheet.getCell('A5').alignment = { vertical: 'middle', horizontal: 'left' }

    worksheet.getCell('A6').value = subtitulo.replace(/[^a-zA-Z ]/g, "")
    worksheet.getCell('A6').style = styleSubTitle
    worksheet.getCell('A6').alignment = { vertical: 'middle', horizontal: 'left' }

    workbook.xlsx.writeBuffer().then(( data ) => {
      const blob = new Blob([data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' })
      saveAs(blob, `${nombre}.xlsx`)
    })

  } catch (error) {
    console.log(error)
  }

}

export default exportarExcelJS