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

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

util.inherits(ExportPdf, Service);

module.exports = ExportPdf;

/**
 * 处理服务请求
 * @param  {Object} req 服务请求对象
 * @param  {Object} res 服务响应对象
 */
ExportPdf.prototype.process = function (req, res, cb) {
  if (!req.html) {
    this.onLogicError(1, '请提供要导出的数据！');
    return;
  }
  if (!req.options) {
    this.onLogicError(1, '请提供要导出的配置！');
    return;
  }
  if (!req.appCode) {
    this.onLogicError(2, '请提供应用代码！');
    return;
  }
  if (req.fileName) {
    if (utils.isValidDirOrFileName(req.fileName)) {
      this.onLogicError(3, '文件名称不能包含特殊字符：\\/:*?"<>|！');
      return;
    }
    if (!req.fileName.endWith('.pdf')) {
      this.onLogicError(4, '文件扩展名仅支持.pdf');
      return;
    }
  }

  pdf.create(req.html, req.options).toBuffer(function (err, buffer) {
    var rootpath = app.serverPath;
    var filepath = '/' + ((app.config.attach && app.config.attach.dir) ?
      app.config.attach.dir : 'files') + '/' + req.session.org.code + '/';
    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 + '.pdf';
    if (req.fileName) fileName = req.fileName;
    filepath += fileCode + '.pdf';
    var filePath = app.getPath(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.user.name;
    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(res);
      } else {
        self.end(res);
      }
    });
  });
};