var util = require('util');
var Service = require('Service');
var utils = require('utils');
var DepUserDao = require('../../dao/dep_user');

var ChangeDep = function() {
  this.list = [];
  this.index = 0;
  Service.call(this);
};

util.inherits(ChangeDep, Service);

module.exports = ChangeDep;

ChangeDep.prototype.process =  function(req, res) {
  if(!req.userIds){
    this.onLogicError(1, "请选择要转移的用户！");
    return;
  }
  var userIds = utils.strToIntArray(req.userIds);
  if(userIds.length==0) {
    this.onLogicError(2, '请选择要转移的用户！');
    return;
  }
  if(!req.curDepId){
    this.onLogicError(3, "请选择迁出部门！");
    return;
  }
  if(!utils.isInt(req.curDepId)) {
    this.onLogicError(4, '请提供正确的部门编号！');
    return;
  }
  if(!req.depId){
    this.onLogicError(5, "请选择迁入部门！");
    return;
  }
  if(!utils.isInt(req.depId)) {
    this.onLogicError(6, '请提供正确的部门编号！');
    return;
  }
  this.list = userIds;
  this.oldDepId = parseInt(req.curDepId);
  this.newDepId = parseInt(req.depId);
  this.addDep(req, res);
};

ChangeDep.prototype.addDep =  function(req, res) {
  if(this.list.length == this.index){
    this.end(res);
    return;
  }
  var userId = this.list[this.index];
  var self = this;
  req.depId = this.newDepId;
  req.userId = userId;
  this.pipe(require('./addDep'), req, res, function(reqD, resD) {
    self.index++;
    self.deleteDep(req, res, userId);
  });
};

ChangeDep.prototype.deleteDep =  function(req, res, userId) {
  var self = this;
  req.depId = this.oldDepId;
  req.userId = userId;
  this.pipe(require('./deleteDep'), req, res, function(reqD, resD) {
    self.addDep(req, res);
  });
};