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

/**
 * 创建应用权限
 */
var AddAuth = function() { 
  Service.call(this);
};

util.inherits(AddAuth, Service);

module.exports = AddAuth;

/**
 * 处理服务请求
 * @param  {Object} req 服务请求对象
 * @param  {Object} res 服务响应对象
 */
AddAuth.prototype.process =  function(req, res) {
  if(!req.appId) {
    this.onLogicError(1, '请提供应用编号！');
    return;
  }
  if(!req.ownerType) {
    this.onLogicError(2, '请选择权限拥有者类型！');
    return;
  }
  if(!["user","dep","role"].contains(req.ownerType)) {
    this.onLogicError(2, '请提供正确的权限拥有者类型！');
    return;
  }
  if(!req.ownerIds) {
    this.onLogicError(3, '请选择权限拥有者！');
    return;
  }
  var ownerIds = utils.strToIntArray(req.ownerIds);
  if(ownerIds.length==0) {
    this.onLogicError(3, '请选择权限拥有者！');
    return;
  }
  ownerIds = ownerIds.join();
  if(!req.terminal) {
    self.onLogicError(4, '请选择终端类型！');
    return;
  }
  var self = this;
  var dao = new Dao(this);
  var options = {
    where: 'org_id=? and app_id=? and owner_type=? and owner_id in ('+ownerIds+') and terminal=?',
    params: [req.session.orgId, req.appId,req.ownerType,req.terminal]
  };
  dao.delete(options, function() {
    dao.execute('insert into sys_app_auth(org_id,app_id,owner_type,owner_id,terminal) '
      +'select ?,?,?,id,? from sys_'+req.ownerType+' where id in ('
      +ownerIds+') and org_id=? and status=0', 
      [req.session.orgId,req.appId,req.ownerType,req.terminal,req.session.orgId], 
      function(){
      dao.query(options, function(auths){
        req.session.cache.del('app_auth', "#{app_id}=="+req.appId+" && #{owner_type}=='"
          +req.ownerType+"' && #{terminal}=='"+req.terminal+"' && ["+req.ownerIds
          +"].contains(#{owner_id})", function(err1) {
          if(err1) {
            self.onError(err1);
            return;
          }
          var params = [];
          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(err2) {
            if(err2) {
              self.onError(err2);
              return;
            }
            self.end(res);
          });
        });
      });
    });
  });
};