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

/**
 * 修改角色信息
 */
var Update = function() { 
  Service.call(this);
};

util.inherits(Update, Service);

module.exports = Update;

/**
 * 处理服务请求
 * @param  {Object} req 服务请求对象
 * @param  {Object} res 服务响应对象
 */
Update.prototype.process =  function(req, res) {
  if(!req.id) {
    this.onLogicError(1, '请提供角色编号！');
    return;
  }
  if(!utils.isInt(req.id)) {
    this.onLogicError(2, '请提供正确的角色编号！');
    return;
  }
  if(!req.code) {
    this.onLogicError(2, '请提供角色编码！');
    return;
  }
  if(!req.name) {
    this.onLogicError(3, '请提供角色名称！');
    return;
  }
  var self = this;
  var dao = new Role(this);
  dao.query({ 
    where: 'org_id='+req.session.orgId+' and id='+req.id+' and status=0',
    fields: 'name'
  }, function(rows1) {
    if(rows1.length==0) {
      self.onLogicError(2, '请提供正确的角色编码！');
      return;
    }
    if((rows1[0].name=='系统管理员' && req.name!=rows1[0].name)
      ||(rows1[0].name=='所有人' && req.name!=rows1[0].name)) {
      self.onLogicError(3, '该角色不允许修改名称！');
      return;
    }
    dao.query({ 
      where: 'name=? and org_id='+req.session.orgId
      +' and id<>'+req.id+' and status=0',
      fields: 'id',
      params: [req.name]
    }, function(rows) {
      if(rows.length>0) {
        self.onLogicError(5, '该角色已经存在！');
        return;
      }
      var type = '';
      if(req.type) type = req.type;
      dao.update({
        code: req.code,
        name: req.name, 
        type: type,
        description: req.description}, 
        {where: 'id='+req.id+' and org_id='+req.session.orgId}, function(ret) {
          var orgDao = new Org(self);
          orgDao.setLastUpdate(req.session.orgId, function(lastUpdate) {
            //修改缓存中的角色信息
            var role = {};
            role.id = parseInt(req.id);
            role.code = req.code;
            role.name = req.name;
            role.type = type;

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