var Service = require('Service');
var utils = require('utils');
var Dao = require('../../dao/org_app');
var DaoAuth = require('../../dao/app_auth');
var util = require('util');

/**
 * 启用应用
 */
var Enable = function() { 
  Service.call(this);
};

util.inherits(Enable, Service);

module.exports = Enable;

/**
 * 处理服务请求
 * @param  {Object} req 服务请求对象
 * @param  {Object} res 服务响应对象
 */
Enable.prototype.process =  function(req, res) {
  if(!req.id) {
    this.onLogicError(1, '请提供应用编号！');
    return;
  }
  var ids = utils.strToIntArray(req.id);
  if(ids.length==0) {
    this.onLogicError(1, '请提供应用编号！');
    return;
  }
  ids = ids.join();
  var self = this;
  var dao = new Dao(this);
  dao.update({status: 0},{
    where: 'org_id='+req.session.orgId+' and app_id in ('+ids+')'}, 
    function(ret) {
    dao.query({where: 'org_id='+req.session.orgId+' and app_id in ('+ids+')'}, function(apps) { 
      var daoAuth = new DaoAuth(self);
      daoAuth.query({where: 'org_id='+req.session.orgId+' and app_id in ('+ids+')'}, function(auths) {  
        var params = [];
        for(var i=0;i<apps.length;i++) {
          var app = apps[i];
          app.auths = [];
          params.push({
            modelName: 'app',
            key: app.app_id,
            value: app
          });
        }
        for(var i=0;i<auths.length;i++) {
          var auth = auths[i];
          params.push({
            modelName: 'app_auth',
            key: auth.id,
            value: auth
          });
        }
        req.session.cache.mset(params, function(err) {
          self.end(res);
        });
      });
    });
  });
};