const ExcelJS = require('exceljs');

/**
 * Excel导出工具类
 */
class ExcelExport {
  /**
   * 创建Excel工作簿并导出数据
   * @param {Array} data - 要导出的数据
   * @param {Array} columns - 列定义 [{ header: '列名', key: '字段名', width: 宽度 }]
   * @param {String} sheetName - 工作表名称
   * @returns {Promise<Buffer>} Excel文件Buffer
   */
  static async exportToExcel(data, columns, sheetName = 'Sheet1') {
    const workbook = new ExcelJS.Workbook();
    const worksheet = workbook.addWorksheet(sheetName);

    // 设置列
    worksheet.columns = columns;

    // 设置表头样式
    worksheet.getRow(1).eachCell((cell) => {
      cell.font = { bold: true, color: { argb: 'FFFFFFFF' } };
      cell.fill = {
        type: 'pattern',
        pattern: 'solid',
        fgColor: { argb: 'FF4472C4' }
      };
      cell.alignment = { vertical: 'middle', horizontal: 'center' };
    });

    // 添加数据
    data.forEach((item) => {
      worksheet.addRow(item);
    });

    // 自动调整列宽
    worksheet.columns.forEach((column) => {
      if (!column.width) {
        const maxLength = Math.max(
          column.header.length,
          ...worksheet.getColumn(column.key).values.map(v => 
            v ? String(v).length : 0
          )
        );
        column.width = Math.min(Math.max(maxLength + 2, 10), 50);
      }
    });

    // 生成Excel文件Buffer
    const buffer = await workbook.xlsx.writeBuffer();
    return buffer;
  }

  /**
   * 格式化日期
   * @param {Date|String} date - 日期
   * @returns {String} 格式化后的日期字符串
   */
  static formatDate(date) {
    if (!date) return '';
    const d = new Date(date);
    const year = d.getFullYear();
    const month = String(d.getMonth() + 1).padStart(2, '0');
    const day = String(d.getDate()).padStart(2, '0');
    const hours = String(d.getHours()).padStart(2, '0');
    const minutes = String(d.getMinutes()).padStart(2, '0');
    const seconds = String(d.getSeconds()).padStart(2, '0');
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
  }

  /**
   * 格式化金额
   * @param {Number} amount - 金额
   * @returns {String} 格式化后的金额字符串
   */
  static formatAmount(amount) {
    if (!amount && amount !== 0) return '';
    return `¥${Number(amount).toFixed(2)}`;
  }

  /**
   * 格式化状态
   * @param {String} status - 状态值
   * @param {Object} statusMap - 状态映射表
   * @returns {String} 状态文本
   */
  static formatStatus(status, statusMap) {
    return statusMap[status] || status || '';
  }
}

module.exports = ExcelExport;

