import Exceljs from 'exceljs'

export const commonExport = (headers, datas, fileName) => {

    const workbook = new Exceljs.Workbook()
    workbook.created = new Date();
    const sheet = workbook.addWorksheet("Sheet1", { views: [{ ySplit: 1, state: 'frozen' }] })
    sheet.columns = headers
    sheet.addRows(datas)
    sheet.eachRow({ includeEmpty: true }, (row, rowNumber) => {
        console.log('rowNumber', rowNumber)
        row.eachCell({ includeEmpty: true }, (cell, colNumber) => {
            console.log('colNumber', colNumber)
            cell.alignment = { vertical: 'middle', horizontal: 'center' }
            cell.border = {
                top: { style: 'thin' },
                left: { style: 'thin' },
                bottom: { style: 'thin' },
                right: { style: 'thin' }
            }
        })
    })

    downExcel(workbook, fileName)
}

export const downExcel = (wb, fileName) => {
    wb.xlsx.writeBuffer().then(buffer => {
        let blob = new Blob([buffer], {
            type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
        })
        let ele = document.createElement('a')
        ele.style.display = 'none'
        ele.href = URL.createObjectURL(blob)
        ele.download = fileName
        document.body.appendChild(ele)
        ele.click()
        document.body.removeChild(ele)
        URL.revokeObjectURL(ele.href)
        wb = null
    })
}