var Service = require('../../../../common/Service');
var utils = require('../../../../common/utils');
var UserFriend = require('../../dao/user_friend');
var User = require('../../dao/user');
var util = require('util');

/**
 * 同意加为好友
 */
var AgreeAddFriend = function () {
  Service.call(this);
};

util.inherits(AgreeAddFriend, Service);

module.exports = AgreeAddFriend;

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

  var self = this;
  var daoUser = new User(this);
  daoUser.query({
    fields: 'id,name',
    where: 'org_id=' + req.session.orgId + ' and id=' + req.userId
  }, function (rowsUser) {
    if (rowsUser.length == 0) {
      self.onLogicError(2, '用户不存在！');
      return;
    }
    var user = rowsUser[0];
    var daoFriend = new UserFriend(self);
    daoFriend.query({
      where: 'org_id=' + req.session.orgId + ' and user_id=' +
        req.session.userId + ' and friend_id=' + req.userId
    }, function (rows) {
      if (rows.length > 0) {
        self.onLogicError(3, '该用户已加为好友！');
        return;
      }
      var friend = {};
      friend.org_id = req.session.orgId;
      friend.user_id = req.session.userId;
      friend.friend_id = req.userId;
      friend.friend_comment = req.comment;
      friend.createtime = new Date();
      friend.msg_top = 0;
      friend.msg_no_hint = 0;
      daoFriend.create(friend, function () {
        var friend2 = {};
        friend2.org_id = req.session.orgId;
        friend2.user_id = req.userId;
        friend2.friend_id = req.session.userId;
        friend2.friend_comment = '';
        friend2.createtime = new Date();
        friend2.msg_top = 0;
        friend2.msg_no_hint = 0;
        daoFriend.create(friend2, function () {
          req.appCode = 'sys';
          req.appDataType = 'user/agreeAddFriend';
          req.receiversId = '' + req.userId;
          req.message = user.name + '已通过您的好友验证请求';
          self.sendAppMsg(req, res);
        });
      });
    });
  });
};