import * as XLSX from 'xlsx';

/**
 * 导出Excel
 * @param {*} data 表格数据-Array
 * @param {*} tableHeader 表头数据-Object
 * @param {*} columnWidth 列宽-Number
 * @param {*} tableName 表格名称-String
 * @param {*} addTime 表格名称加上导出时间-Boolean 格式：yyyy-mm-dd_hh-mm-ss
 */
export function exportToExcel(data, tableHeader, columnWidth = 15, tableName, addTime = false) {
    return new Promise((resolve, reject) => {
        try {
            // 创建一个工作簿
            const wb = XLSX.utils.book_new();
            // 将表格数据转换为工作表
            data = [...data]
            let colWidth = [] //列宽

            // 使用 map 方法遍历 data 数组
            let translatedData = data.map(item => {
                let newItem = {};
                // 遍历 tableHeader 进行键名替换
                Object.keys(tableHeader).forEach(key => {
                    if (item[key] !== undefined) {
                        newItem[tableHeader[key]] = item[key]; // 赋值为 tableHeader 映射的中文名
                        colWidth.push({ wch: columnWidth }) // 设置列宽
                    }
                });

                return newItem;
            });

            const ws = XLSX.utils.json_to_sheet(translatedData)

            // 设置列宽
            ws['!cols'] = colWidth;

            // 设置对齐方式
            const cellAlignment = {
                alignment: { horizontal: "center" }
            };

            // 遍历工作表的每个单元格并应用样式
            for (let row = 0; row < translatedData.length; row++) {
                for (let col = 0; col < Object.keys(translatedData[row]).length; col++) {
                    const cellAddress = XLSX.utils.encode_cell({ c: col, r: row });
                    if (!ws[cellAddress]) {
                        ws[cellAddress] = {};
                    }
                    ws[cellAddress].s = cellAlignment; // 应用样式
                }
            }

            // 将工作表添加到工作簿
            XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');

            // 导出 Excel 文件
            let name = addTime ? `${getCurrentDateTime()}_${tableName}.xlsx` : `${tableName}.xlsx`;
            XLSX.writeFile(wb, name);

            resolve(true);
        } catch (error) {
            console.error("Excel 导出失败:", error);
            reject(false);
        }
    });
}

/**
 * 导出时间
 * @returns 时间格式：yyyy-mm-dd_hh-mm-ss
 */
function getCurrentDateTime() {
    const now = new Date();
    const year = now.getFullYear();
    const month = String(now.getMonth() + 1).padStart(2, '0'); // 月份从 0 开始，需要 +1
    const day = String(now.getDate()).padStart(2, '0');
    const hours = String(now.getHours()).padStart(2, '0');
    const minutes = String(now.getMinutes()).padStart(2, '0');
    const seconds = String(now.getSeconds()).padStart(2, '0');

    return `${year}-${month}-${day}_${hours}-${minutes}-${seconds}`;
}