var Service = require('Service');
var utils = require('utils');
var User = require('../../dao/vuser');
var util = require('util');

/**
 * 查找用户和群组
 */
var Find = function() { 
  Service.call(this);
  this.checkAuthority = false;
};

util.inherits(Find, Service);

module.exports = Find;

/**
 * 处理服务请求
 * @param  {Object} req 服务请求对象
 * @param  {Object} res 服务响应对象
 */
Find.prototype.process =  function(req, res) {
  if(!req.keyword) {
    this.onLogicError(1, '请提供关键字！');
    return;
  }
  if(utils.haveEspecialChar(req.keyword)) {
    this.onLogicError(2, '关键字中不能包含特殊字符！');
    return;
  }
  if(req.keyword.length>20) {
    this.onLogicError(3, '关键字长度超出限制！');
    return;
  }

  var self = this;
  var dao = new User(this);
  dao.query({
    fields:'id,name,sex,head_id,motto,(select code from sys_app_attach where '
      +'id=vsys_user.head_id and org_id=vsys_user.org_id) as head_code',
    where:'org_id='+req.session.orgId+' and (loginname=? or mobile=?) and id<>'+req.session.userId, 
    params:[req.keyword,req.keyword]}, function(rows) {
    res.users = rows;
    self.emit('end', res);
  });
};