var angular = require('angular'),
  _ = require('jsUtil');

require('../modules');
require('../../modules/linker/services/throttleService');

angular
  .module('commons.directives')
  .directive('sinoFlowSearchInPane', sinoFlowSearchInPane);

/** @ngInject */
function sinoFlowSearchInPane($timeout, sinoListTabsService, $rootScope, throttleService, $q) {
  return {
    restrict: 'E',
    require: '^?sinoListPane',
    templateUrl: 'views/commons/directives/sinoArchiveSearch.tpl.html',
    scope: true,
    link: link
  };
  function link(scope, element, attrs, ctrl) {
    var cacheArray = ctrl.$scope.cacheArray;
    scope.$on('scroll.refreshComplete', scrollToHide);
    $timeout(scrollToHide, 300);
    scope.search= _.clone(ctrl.$scope.cacheArray.params) || {};
    scope.state = ctrl.$scope.state;

    $rootScope.$on('$ionicView.beforeEnter', function() {
      cacheArray.sinoFlowSearchInPaneNoOnceScroll = cacheArray.onceCache;
    });

    $rootScope.$on('$ionicView.beforeLeave', function() {
      if (!cacheArray.onceCache) { // 退出
        delete cacheArray.params;
      }
    });

    function scrollToHide() {
      if (ctrl.$scope.selected && (!cacheArray.sinoFlowSearchInPaneNoOnceScroll)) {
        var delegate = ctrl.$scope.scrollDelegate;
        if (delegate) {
          delegate.scrollTo(0, 164, true);
        }
      }

      cacheArray.sinoFlowSearchInPaneNoOnceScroll = false;
    }

      if(!scope.search || !scope.search.subflag) {
        scope.search.subflag = 'all';
      }

      scope.clearButtonClick = function() {
        throttleService.throttle(clear(), 1000, true, true);
      };

      function clear() {
        cacheArray.sinoFlowSearchInPaneNoOnceScroll = true;
        scope.search = {};
        scope.search.subflag = 'all';
        cacheArray.params = {};
        ctrl.$scope.onRefresh();
      };

      scope.onSearchButtonClick = function() {
        throttleService.throttle(searchButtonClick(), 1000, true, true);
      };

      function searchButtonClick() {
        cacheArray.sinoFlowSearchInPaneNoOnceScroll = true;
        var search = {};
        if(scope.search) {
          search.title = scope.search.title;
          if(scope.search.subflag && scope.search.subflag != 'all') {
            search.subflag = scope.search.subflag;
          }
        }
        cacheArray.params = search;
        ctrl.$scope.onRefresh();
        return $q.when(true);
      }
  }
}
