var Service = require('Service');
var utils = require('utils');
var Role = require('../../dao/role');
var Org = require('../../dao/org');
var util = require('util');

/**
 * 创建角色
 */
var Add = function() { 
  Service.call(this);
};

util.inherits(Add, Service);

module.exports = Add;

/**
 * 处理服务请求
 * @param  {Object} req 服务请求对象
 * @param  {Object} res 服务响应对象
 */
Add.prototype.process =  function(req, res) {
  if(!req.code) {
    this.onLogicError(1, '请提供角色编码！');
    return;
  }
  if(!req.name) {
    this.onLogicError(2, '请提供角色名称！');
    return;
  }
  
  var self = this;
  var dao = new Role(this);
  dao.query({ 
    where: 'name=? and org_id='+req.session.orgId+' and status=0',
    fields: 'id',
    params: [req.name]
  }, function(rows) {
    if(rows.length>0) {
      self.onLogicError(4, '该角色已经存在！');
      return;
    }
    var type = '';
    if(req.type) type = req.type;
    dao.create({
      code: req.code,
      name: req.name, 
      org_id: req.session.orgId, 
      status: 0,
      type: type,
      allow_apply_join: 0,
      only_app_center:0,
      disable_app_center:0,
      disable_taskmsg:0,
      disable_address_book:0,
      disable_work_circle:0,
      description: req.description,
      creater_id: req.session.userId, 
      createtime: new Date()}, function(ret) {
        var orgDao = new Org(self);
        orgDao.setLastUpdate(req.session.orgId, function(lastUpdate) { 
          //将角色添加到缓存
          var role = {};
          role.id = ret.insertId;
          role.code = req.code;
          role.name = req.name;
          role.type = type;
          role.users = new Array();

          res.id = role.id;

          req.session.cache.set('role', role.id, role, false, function(err) {
            if(err) {
              self.onError(err);
              return;
            }
            self.end(res);
          });
        });
    });
  });
};