var Service = require('Service');
var utils = require('utils');
var RoleType = require('../../dao/role_type');
var util = require('util');

/**
 * 修改类型
 */
var UpdateType = function() { 
  Service.call(this);
};

util.inherits(UpdateType, Service);

module.exports = UpdateType;

/**
 * 处理服务请求
 * @param  {Object} req 服务请求对象
 * @param  {Object} res 服务响应对象
 */
UpdateType.prototype.process =  function(req, res, cb) {
  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 RoleType(this);
  dao.query({ 
    where: 'name=? and org_id='+req.session.orgId+' and id<>'+req.id,
    fields: 'id',
    params: [req.name]
  }, function(rows) {
    if(rows.length>0) {
      self.onLogicError(4, '名称已经存在！');
      return;
    }
    var post = {};
    post.code = req.code;
    post.name = req.name;
    dao.update(post, {where: 'org_id='+req.session.orgId+' and id='+req.id}, function() {
      self.end(res);
    });
  });
};