var Service = require('Service');
var utils = require('utils');
var fs = require('fs');
var util = require('util');
var Dao = require('../../dao/org_app_category');

/**
 * 创建应用分类
 */
var AddAppCategory = function() { 
  Service.call(this);
};

util.inherits(AddAppCategory, Service);

module.exports = AddAppCategory;

/**
 * 处理服务请求
 * @param  {Object} req 服务请求对象
 * @param  {Object} res 服务响应对象
 */
AddAppCategory.prototype.process =  function(req, res) {
  if(!req.code) {
    this.onLogicError(1, '请提供类别代码！');
    return;
  }
  if(!req.name) {
    this.onLogicError(2, '请提供类别名称！');
    return;
  }
  
  /*if(req.group_apps=='1' && !req.iconPath){
    this.onLogicError(2, '请上传应用图标！');
    return;
  }*/

  var parent_id = 0;
  if(req.parentId) parent_id = parseInt(req.parentId);

  var cdir = "/"+req.code;
  if(parent_id==0) {
    this.createDir(req, res, parent_id, cdir);
    return;
  }
  var self = this;
  req.session.cache.getPath("app_category", parent_id, "code", function(err, pdir) {
    cdir = pdir+cdir;
    self.createDir(req, res, parent_id, cdir);
  });
};

AddAppCategory.prototype.createDir =  function(req, res, parent_id, cdir) {  
  var pathService = server.serverPath+'/app';
  var pathWeb = server.serverPath+'/web/app';
  var arr = cdir.split('/');
  for(var i=0;i<arr.length;i++) {
    var str = arr[i];
    if(str=="") continue;
    pathService += "/"+str;
    if(!fs.existsSync(pathService)) fs.mkdirSync(pathService);
    pathWeb += "/"+str;
    if(!fs.existsSync(pathWeb)) fs.mkdirSync(pathWeb);
  }
  
  var self = this;
  var dao = new Dao(this);
  dao.query({where: 'org_id=? and parent_id=? and (name=? or code=?)', 
    params:[req.session.orgId,parent_id,req.name,req.code]}, function(rows) {
    if(rows.length>0) {
      self.onLogicError(3, '该类别已经存在！');
      return;
    }
    var icon_code = null;
    var group_apps = null;
    if(req.icon) {
      icon_code = req.icon.code;
      group_apps = 1;
    }
    var category = {
      code: req.code, 
      name: req.name, 
      org_id: req.session.orgId, 
      icon_code: icon_code,
      group_apps: group_apps,
      parent_id: parent_id
    };
    dao.create(category, function(ret) {
      dao.update({order_no: ret.insertId},'id='+ret.insertId, function(){
        res.categoryId = ret.insertId;
        category.id = ret.insertId;
        category.order_no = ret.insertId;
        category.apps = [];
        category.subCategorys = [];

        req.session.cache.set('app_category', category.id, category, false, function(err) {
          if(err) {
            self.onError(err);
            return;
          }
          res.category = category;
          self.end(res);
        });
      });
    });
  });
};