var excel = require('exceljs');
const system = require("../system");
const uuidv4 = require('uuid/v4');
const fs = require("fs");
const xlsx = require('node-xlsx')
const json2csv = require('json2csv');
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.restClient = system.getObject("util.restClient");
  }

  async download(params, cb) {
    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 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) {});
      if (cb) {
        cb(rtn.url);
      }
    });
  }

  async readExcel(id, ossurl) {
    var result = {
      code: 0,
      data: [],
    };
    var names = [];
    var filePath = "/tmp/ecompany_contract_" + id + ".xlsx";
    try {
      await this.restClient.execDownload("'" + ossurl + "'", filePath);

      var sheets = xlsx.parse(filePath);
      fs.unlink(filePath, e => {
        console.log("fail");
      });

      if (!sheets || sheets.length == 0) {
        return result;
      }

      var sheet = sheets[0];
      if (!sheet || !sheet.data || sheet.data.length == 0) {
        return result;
      }

      var rows = sheet.data;

      for (var idx in rows) {
        if (idx == 0) {
          continue;
        }

        var cells = rows[idx];
        if (!cells || cells.length == 0 || !cells[0]) {
          continue;
        }
        var c = cells[0];
        if (names.indexOf(c) > -1) {
          continue;
        }
        names.push(c);
      }

      console.log(sheet);
      result.code = 1;
      result.data = names;
      return result;
    } catch (error) {
      console.log(error.stack);
      return result;
    }
  }

  async exportCsv(req, res, csvobj) {
    var userAgent = (req.headers['user-agent'] || '').toLowerCase();
    var fileName = csvobj.fileName || new Date().getTime();

    if (userAgent.indexOf('msie') >= 0 || userAgent.indexOf('chrome') >= 0) { 
      await res.setHeader('Content-Disposition', 'attachment; filename=' + encodeURIComponent(fileName));
    } else if (userAgent.indexOf('firefox') >= 0) {
      await res.setHeader('Content-Disposition', 'attachment; filename*="utf8\'\'' + encodeURIComponent(fileName) + '"');
    } else {
      await res.setHeader('Content-Disposition', 'attachment; filename=' + new Buffer(fileName).toString('binary'));
    }
    await res.writeHead(200,{'Content-Type':'application/octet-stream;charset=utf-8'});

    let csv = json2csv.parse(csvobj.rows, csvobj.opts);
    if(csvobj.headers) {
      for(var field of csvobj.opts.fields) {
        csv = csv.replace(field, csvobj.headers[field]);
      }
    }
    await res.write("\uFEFF" + csv);
    await res.write('\n');
  }
}

module.exports = ExcelClient;