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

/**
 * 修改应用分类
 */
var UpdateAppCategory = function() { 
  Service.call(this);
};

util.inherits(UpdateAppCategory, Service);

module.exports = UpdateAppCategory;

/**
 * 处理服务请求
 * @param  {Object} req 服务请求对象
 * @param  {Object} res 服务响应对象
 */
UpdateAppCategory.prototype.process =  function(req, res) {
  if(!req.id) {
    this.onLogicError(1, '请提供类别编号！');
    return;
  }

  if(!utils.isInt(req.id)) {
    this.onLogicError(4, '请提供正确的类别编号！');
    return;
  }

  if(!req.name) {
    this.onLogicError(2, '请提供类别名称！');
    return;
  }

  if(!req.order_no) {
    this.onLogicError(3, '请提供序号！');
    return;
  }

  if(!utils.isInt(req.order_no)) {
    this.onLogicError(4, '请提供正确的序号！');
    return;
  }
  
  /*if(req.group_apps=='1' && !req.iconPath){
    this.onLogicError(5, '请上传应用图标！');
    return;
  }*/

  var parent_id = 0;
  if(req.parent_id && utils.isInt(req.parent_id)) 
    parent_id = parseInt(req.parent_id);
  var icon_code = null;
  var group_apps = null;
  if(req.icon) {
    icon_code = req.icon.code;
    group_apps = 1;
  }
  
  var self = this;
  var dao = new Dao(this);
  dao.query({where: 'org_id=? and parent_id=? and name=? and id<>?', 
    params:[req.session.orgId,parent_id,req.name,req.id]}, function(rows) {
    if(rows.length>0) {
      self.onLogicError(4, '该类别已经存在！');
      return;
    }
    var category = {
      name: req.name, 
      parent_id: parent_id,
      icon_code: icon_code,
      order_no: parseInt(req.order_no),
      group_apps: group_apps
    };
    dao.update(category, {where: 'org_id=? and id=?', 
      params:[req.session.orgId,req.id]}, function(ret) {
      req.session.cache.set('app_category', req.id, category, true, function(err) {
        if(err) {
          self.onError(err);
          return;
        }
        self.end(res);
      });
    });
  });
};