var util = require('util');
var fs= require('fs');
var path= require('path');
var xlsx = require('node-xlsx');
var uuid = require('node-uuid');
var Service = require('Service');
var utils = require('utils');
var AppAttachDao = require('../../dao/app_attach');

/**
 * 导出Excel数据
 */
var ExportExcel = function() { 
  Service.call(this);
};

util.inherits(ExportExcel, Service);

module.exports = ExportExcel;

/**
 * 处理服务请求
 * @param  {Object} req 服务请求对象
 * @param  {Object} res 服务响应对象
 */
ExportExcel.prototype.process =  function(req, res, cb) {
  if(!req.data && !req.sheets) {
    this.onLogicError(1, '请提供要导出的数据！', req, res, cb);
    return;
  }
  if(!req.appCode) {
    this.onLogicError(2, '请提供应用代码！', req, res, cb);
    return;
  }
  if(req.fileName) {
    if(utils.isValidDirOrFileName(req.fileName)) {
      this.onLogicError(3, '文件名称不能包含特殊字符：\\/:*?"<>|！', req, res, cb);
      return;
    }
    if(req.fileName.indexOf(".")<0) {
      req.fileName += ".xlsx";
    } else if(!req.fileName.endWith('.xlsx')) {
      this.onLogicError(4, '文件扩展名仅支持.xlsx！', req, res, cb);
      return;
    }
  }
  var buffer;
  if(req.fields) {
    let data = [];
    let col = [];
    for(var i=0;i<req.fields.length;i++) {
      col.push(req.fields[i].column);
    }
    data.push(col);
    console.log(data);
    for(var i=0;i<req.data.length;i++) {
      let dataRow = req.data[i];
      let excelRow = [];
      for(var j=0;j<req.fields.length;j++) {
        excelRow.push(dataRow[req.fields[j].name]);
      }
      data.push(excelRow);
      if(i<5) console.log(excelRow);
    }
    buffer = xlsx.build([{"name": "工作表一", "data": data}]);
  } else if(req.data) {
    var tableName = '工作表一';
    if(req.tableName) tableName = req.tableName;
    buffer = xlsx.build([{"name": tableName, "data": req.data}]);
  } else {
    buffer = xlsx.build(req.sheets);
  }
  var rootpath = utils.formatPath(server.attachSavePath);
  var filepath = '/'+req.session.orgCode+'/';
  if(!fs.existsSync(path.join(rootpath,filepath))) fs.mkdirSync(path.join(rootpath,filepath));
  filepath += 'exportFiles/';
  if(!fs.existsSync(path.join(rootpath,filepath))) fs.mkdirSync(path.join(rootpath,filepath));
  filepath += req.appCode+'/';
  if(!fs.existsSync(path.join(rootpath,filepath))) fs.mkdirSync(path.join(rootpath,filepath));
  var fileCode = uuid.v1().replace(/-/g,'');
  var fileName = fileCode+'.xlsx';
  if(req.fileName) fileName = req.fileName;
  filepath += fileCode+'.file';
  
  var filePath = utils.formatPath(path.join(rootpath,filepath));
  fs.writeFileSync(filePath, buffer, 'binary');
  
  var stat = fs.statSync(filePath);
  var attach = {};
  attach.code = fileCode;
  attach.name = fileName;
  attach.size = stat.size;
  attach.type = path.extname(fileName);
  attach.app_code = req.appCode;
  attach.app_data_id = 0;
  attach.uploader_id = req.session.userId;
  attach.uploader_name = req.session.userName;
  attach.upload_time = new Date();    
  attach.save_path = filepath;
  attach.org_id = req.session.orgId;

  var self = this;
  var attachDao = new AppAttachDao(this);
  attachDao.create(attach, function(ret) {
    res.fileCode = attach.code;
    res.fileSize = attach.size;
    res.fileName = attach.name;
    res.fileId = ret.insertId;
    if(cb) {
      cb(req, res);
    } else {
      self.end(res);
    }
  });
};