var angular = require('angular');
require('jsUtil');
require('../modules');
require('../services/WorkflowConfig');

var module = angular.module('flow');

module.controller('SelectStaffCtrl', function($scope, WorkflowConfig) {
  $scope.result = {order: '1'};
  $scope.disablePerson = true;
  $scope.seconds = 5;
  $scope.orderKey = '1';
  $scope.hasSend = false;
  $scope.order = [{
    'text': '同时办',
    'value': '1',
    'ifchecked': true,
    'show': true
  }, {
    'text': '顺序办',
    'value': '2',
    'ifchecked': false,
    'show': true
  }];

  function setOrder() {
    var config = WorkflowConfig.getConfig($scope.data.filetypeid);
    if (config && config.moreOrder) {
      $scope.order[1].show = config.moreOrder.shunxuban;
      $scope.order[0].show = config.moreOrder.tongshiban;
    }
  }
  setOrder();

  function getSelectUsers() {
    if (!$scope.data.more && $scope.result.selectedUser) {
      return [$scope.result.selectedUser];
    } else if ($scope.data.more && $scope.result.selectedUsers) {
      var selectedUsers = $scope.result.selectedUsers,
        userIds = [];
      for (var userId in selectedUsers) {
        if (selectedUsers.hasOwnProperty(userId) && selectedUsers[userId]) {
          userIds.push(userId);
        }
      }
      return userIds;
    }
    return [];
  }

  $scope.$watch(function() {
    $scope.disablePerson = getSelectUsers().length <= 0;
    return $scope.disablePerson;
  });

  $scope.submit = function() {
    $scope.disable = true;
    $scope.hasSend = true;
    var selectUsers = getSelectUsers();

    //TODO 提交工作流
    if($scope.data.more) {
      $scope.data.selectuserlist = [$scope.data.wfoperateid, '=|$|', selectUsers[0], '|$|'].join('');
      for(var i = 1; i < selectUsers.length; i++) {
        $scope.data.selectuserlist =
          $scope.data.selectuserlist.concat(selectUsers[i] + '|$|');
      }
      $scope.data.selectuserlist = $scope.data.selectuserlist.concat('#' + $scope.result.order + ',');
    } else {
      $scope.data.selectuserlist = [$scope.data.wfoperateid, '=|$|', selectUsers[0], '|$|#,'].join('');
    }

    $scope.close(false);
  };

  $scope.close = function(cancel) {
    $scope.onSelected(cancel);
  };
});
