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

/**
 * 上传附件
 */
var UploadAttachByHttp = function() { 
  Service.call(this);
  this.attachDao = new AppAttachDao(this);
  this.checkAuthority = false;
};

util.inherits(UploadAttachByHttp, Service);

module.exports = UploadAttachByHttp;

/**
 * 处理服务请求
 * @param  {Object} req 服务请求对象
 * @param  {Object} res 服务响应对象
 */
UploadAttachByHttp.prototype.process =  function(req, res) {
  if(!req.appCode) {
    this.onLogicError(1, '请提供应用编码！', req);
    return;
  }
  if(!req.fileCode) {
    this.onLogicError(2, '请提供文件编码！', req);
    return;
  }
  if(!req.fileName) {
    this.onLogicError(3, '请提供文件名！', req);
    return;
  }
  if(!req.fileSize) {
    this.onLogicError(4, '请提供文件大小！', req);
    return;
  }
  
  var self = this;
  //创建文件保存路径
  var relativePath = '/'+req.session.orgCode+'/';
  var absolutePath = path.join(server.attachSavePath, relativePath);
  if(!fs.existsSync(absolutePath)) fs.mkdirSync(absolutePath);
  relativePath += req.appCode+'/';
  absolutePath = path.join(server.attachSavePath, relativePath);
  if(!fs.existsSync(absolutePath)) fs.mkdirSync(absolutePath);
  relativePath += utils.formatDate(new Date(), 'yyyy_MM')+'/';
  absolutePath = path.join(server.attachSavePath, relativePath);
  if(!fs.existsSync(absolutePath)) fs.mkdirSync(absolutePath);

  var ext = path.extname(req.fileName);
  if(req.retainExt && (ext=='.mp4' || ext=='.mp3' || ext=='.amr' 
    ||ext=='.jpg' || ext=='.png' || ext=='.gif')) {
    relativePath += req.fileCode+path.extname(req.fileName);
  } else {
    relativePath += req.fileCode+'.file';
  }
  absolutePath = path.join(server.attachSavePath, relativePath);
  console.log('文件路径：'+absolutePath);

  var tmpPath = server.attachSavePath+'/tmp/upload_'+req.fileCode;
  fs.rename(utils.formatPath(tmpPath), utils.formatPath(absolutePath), function() {
    if(req.appDataId && req.appDataId>0 && req.onlyOne) {
      self.attachDao.delete('app_code="'+req.appCode+'" and app_data_Id='
        +req.appDataId+' and org_id='+req.session.orgId, function() {
          self.addAttach(req, res, relativePath, absolutePath);
      });
    } else {
      self.addAttach(req, res, relativePath, absolutePath);
    }
  });
};

UploadAttachByHttp.prototype.addAttach =  function(req, res, relativePath, absolutePath) {
  var self = this;
  var attach = {};
  attach.code = req.fileCode;
  attach.name = req.fileName;
  attach.size = req.fileSize;
  attach.type = path.extname(req.fileName);
  attach.app_code = req.appCode;
  if(req.appDataId && req.appDataId>0) attach.app_data_id = req.appDataId;
  attach.uploader_id = req.session.userId;
  attach.uploader_name = req.session.userName;
  attach.upload_time = new Date();
  attach.save_path = relativePath;
  attach.org_id = req.session.orgId;
  
  this.attachDao.create(attach, function(ret) {
    if(req.appCode=='KindEditor') {
      res.error = 0;
      //res.url = '/TaskMsgDownload?sessionId='+req.session.id+'&fileCode='+req.fileCode;
      res.url = '/TaskMsgDownload?fileCode='+req.fileCode;
    } else {
      res.fileCode = req.fileCode;
      res.fileSize = req.fileSize;
      res.fileName = req.fileName;
      res.fileId = ret.insertId;
    }
    attach.id = ret.insertId;
    self.end(res);
  });
};