'use strict';

var angular = require('angular'),
 _ = require('jsUtil');
require('../modules');
require('../../info/services/ModelService');

angular
  .module('infoDisplay.directives')
  .directive('sinoModelListButton', sinoModelListButton)
  .controller('sinoModelListButtonCtrl', sinoModelListButtonCtrl);

/** @ngInject */
function sinoModelListButton() {

  return {
    restrict: 'E',
    template: '<button class="button button-icon icon ion-ios-plus-empty" ng-click="modelListButtonCtrl.openModelList()"></button>',
    controller: 'sinoModelListButtonCtrl',
    controllerAs: 'modelListButtonCtrl',
    require: '^sinoInfoListPage'
  };
}

/** @ngInject */
function sinoModelListButtonCtrl($scope, $element, CommonService, $window, $toast) {
  var self = this;

  self.editButton = false;

  self.openModelList = openModelList;
  self.close = close;

  self.onClickItem = onClickItem;
  self.addItem = addItem;
  self.removeItem = removeItem;
  self.onHold = onHold;
  self.selectItemClass = selectItemClass;

  init();

  function init() {
    $window.addEventListener('click', windowFn);
  }

  /** 监听销毁 */
  $scope.$on('$destroy', function() {
    if (self.modal) {
      self.modal.remove();
      self.modal = null;
    }
    $window.removeEventListener('click', windowFn);
  });

  function openModelList() {
    var url = 'views/infoDisplay/directives/sinoModelList.tpl.html';
    if (!self.modal) {
      CommonService.createModal(url, $scope).then(function(modal) {
        self.modal = modal;
        self.modal.show();
      });
    } else {
      self.modal.show();
    }
  }

  function close() {
    $scope.refreshItems($scope.selectedItems, $scope.notSelectedItems);
    $scope.$parent.$broadcast('infoModelChange',
      $scope.$parent.selectedItemId, $scope.$parent.selectedItems);
    if (self.modal) {
      self.modal.hide();
    }
  }

  function onClickItem(item) {
    if (!self.editButton) {
      $scope.$parent.selectedItemId = item.id;
      self.close();
    } else {
      removeItem(item);
    }
  }

  function addItem(item) {
    $scope.selectedItems.push(item);
    _.remove($scope.notSelectedItems, item);
  }

  function removeItem(item) {
    if($scope.selectedItems.length === 1) {
      return $toast.showLongCenter('已经是最后一个了');
    }
    _.remove($scope.selectedItems, item);
    $scope.notSelectedItems.push(item);
    if (item.id === $scope.selectedItemId) { // 如果删除选中的则跳转到第一个页面
      $scope.$parent.selectedItemId = $scope.selectedItems[0].id;
    }
  }

  function onHold() {
    self.editButton = true;

  }

  function windowFn() {
    $scope.$apply(function() {
      self.editButton = false;
    });
  }

  function selectItemClass(item) {
    if (item.id === $scope.selectedItemId) {
      return 'sino-model-list-select-button';
    }
  }
}
