var 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) {
      var self = this;

      var title = params.title || "";
      var code = params.code || uuidv4();
      var fileName = params.fileName || code + ".xlsx";
      var filePath = params.filePath || "/tmp/" + fileName;
      var rows = params.rows || [];
      var user = params.user || {};

      var wb = new excel.Workbook();
      wb.properties.date1904 = true;
      var sheet = wb.addWorksheet("sheet1");
      var 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' };

        var colkey = 0;
        if(headers.length > 0) {
          colkey = headers.length - 1;
        }
        var endColumn = this.columns[colkey] || "A";
        sheet.mergeCells("A1:" + endColumn + "1");
      }

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

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

module.exports = ExcelClient;
