const excel = require('exceljs');
const system = require('../system');
const uuidv4 = require('uuid/v4');
const fs = require('fs');

class ExcelClient {
  constructor() {
    this.columns = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];
    this.ossClient = system.getObject('util.ossClient');
    this.filedownloadDao = system.getObject('db.filedownloadDao');
  }

  async download(params) {
    const self = this;

    const title = params.title || '';
    const code = params.code || uuidv4();
    const fileName = params.fileName || `${code}.xlsx`;
    const filePath = params.filePath || `/tmp/${fileName}`;
    const rows = params.rows || [];
    const user = params.user || {};

    const wb = new excel.Workbook();
    wb.properties.date1904 = true;
    const sheet = wb.addWorksheet('sheet1');
    const headers = rows[0];
    console.log(headers, '@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@2 headers');
    if (title) {
      sheet.addRow([title]);
      sheet.getCell('A1').font = {
        name: '微软雅黑',
        family: 4,
        size: 12,
        bold: true,
      };
      sheet.getCell('A1').alignment = { vertical: 'middle', horizontal: 'center' };

      let colkey = 0;
      if (headers.length > 0) {
        colkey = headers.length - 1;
      }
      const endColumn = this.columns[colkey] || 'A';
      sheet.mergeCells(`A1:${endColumn}1`);
    }

    for (const r of rows) {
      sheet.addRow(r);
    }

    wb.xlsx.writeFile(filePath).then(async (d) => {
      const rtn = await self.ossClient.upfile(fileName, filePath);
      fs.unlink(filePath, (err) => { });
      let obj = {
        user_id: user.id || 0,
        userName: user.userName || '',
        code,
        fileName,
        filePath: rtn.url || '',
        isDownload: false,
      };
      obj = await self.filedownloadDao.create(obj);
    });
  }
}

module.exports = ExcelClient;
