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

/**
 * 导出文本数据
 */
var ExportText = function () {
  Service.call(this);
};

util.inherits(ExportText, Service);

module.exports = ExportText;

/**
 * 处理服务请求
 * @param  {Object} req 服务请求对象
 * @param  {Object} res 服务响应对象
 */
ExportText.prototype.process = function (req, res, cb) {
  if (!req.text) {
    this.onLogicError(1, '请提供要导出的数据！');
    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;
    }
  }

  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, req.text);
  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);
    }
  });
};