var Service = require('../../../../common/Service');
var utils = require('../../../../common/utils');
var RoleUser = require('../../dao/role_user');
var util = require('util');

/**
 * 申请加入
 */
var ApplyJoin = function() { 
  Service.call(this);
  this.checkAuthority = false;
};

util.inherits(ApplyJoin, Service);

module.exports = ApplyJoin;

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

  if(!utils.isInt(req.roleId)) {
    this.onLogicError(2, '请提供正确的群组编号！');
    return;
  }

  var role = req.session.org.roles[req.roleId];
  if(!role) {
    this.onLogicError(3, '请提供正确的群组编号！');
    return;
  }

  var self = this;
  var dao = new RoleUser(this);
  dao.query({fields: 'user_id', where: 'org_id='+req.session.orgId
    +' and role_id='+req.roleId+' and is_admin=1'}, function(rows) {
    if(rows.length==0) {
      self.onLogicError(4, '该群目前没有管理员，无法申请加入！');
      return;
    }
    var usersId = '';
    for(var i=0;i<rows.length;i++) {
      if(i>0) usersId += ',';
      usersId += ''+rows[i].user_id;
    }
    req.appCode = 'sys';
    req.appDataType = 'role/applyJoin';
    req.receiversId = usersId;
    req.content = role.id+','+role.name;
    req.message = req.session.user.name+'请求加入群：'+role.name;
    self.sendAppMsg(req, res);
  });
};