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

'use strict';

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

module.controller('InfoReleaseGroupCtrl', function($stateParams, $scope, $state, CoreAppConfig,
  ModelService, $q, Timer, $toast, $ionicScrollDelegate, $timeout, $ionicViewSwitcher, ModelLocalStorageService) {
  $scope.title = '信息发布';
  $scope.showCard = ModelService.getShowCard();
  $scope.refreshx = false;

  var left = 0;
  var scrollView = $ionicScrollDelegate.$getByHandle('infosListScrollView');
  $scope.region = [];//区块信息
  var ctrl = this;
  ctrl.loadingState = 2;
  var pathMap = {};

  $scope.$on('$ionicView.loaded', function() {
    $scope.init('loaded');
  });

  var loaded = false;
  $scope.$on('$ionicView.beforeEnter', function() {
    if(loaded) {
       $scope.init('beforeEnter');
    }
    loaded = true;
  });

  $scope.init = function(source) {
    ctrl.loadingState = ModelService.alreadyStorage() ? 2 : 1;
    return initData(source, true).then(function(data) {
      setCardScrollPosition();
      ctrl.loadingState = !_.isEmpty(data) ? 2 : 4;
    }, function() {
      ctrl.loadingState = 3;
    });
  }


  /**
   * 将每次标签滑动的位置保存下来
   */
  $scope.onScroll = function() {
    $timeout(function() {
      if (scrollView && scrollView.getScrollPosition()) {
        left = scrollView.getScrollPosition().left;
        localStorage.setItem('left', left);
      }
    });
  }

  /**
   * 在数据加载完之后，将标签移动到之前滑动的位置
   */
  function setCardScrollPosition() {
    if (!_.isEmpty($scope.showCard)) {
      $timeout(function() {
        scrollView.scrollTo(localStorage.getItem('left'), 0);
      });
    }
  }

  /**
   * 初始数据
   */
  function initData(source, initing) {
    var _infos = [],//某区块的信息列表
      modelMap = {};

    var dataPromise = initing ? ModelService.getModel() : ModelService.refreshStorageModel();

    return dataPromise.then(function(data) {
      var modelRegion = {};
      var regionArray = [];
      _.each(data, function(model) {
        var region = modelRegion[model.region];//划分区块
        region = region || [];
        region.push(model);
        modelRegion[model.region] = region;
        modelMap[model.id] = model;//根据不同的区块将model放进去
        model.subject = null;
      });
      _.each(modelRegion, function(models, region) {
        _infos.push(models);
        regionArray.push(region);//初始化获得有多少个区块
      });
      $scope.region = regionArray;
      $scope.showCard = _.isEmpty($scope.showCard) ? $scope.region[0] : $scope.showCard;
      if(source == 'loaded') {//初始化时
        var index = _.isEmpty($scope.showCard) ? 0 : $scope.region.indexOf($scope.showCard);
        $scope.items = _.isEmpty(_infos) || _.isEmpty(_infos[index]) ? [] : _infos[index];
      }
      if(source != 'loaded' && ModelService.getModelsChange()) {//判断模块有没有更新
        var index = _.isEmpty($scope.showCard) ? 0 : $scope.region.indexOf($scope.showCard);
        $scope.items = _.isEmpty(_infos) || _.isEmpty(_infos[index]) ? [] : _infos[index];
      }

    }).then(function(data) {
      ModelService.getLatestInfos().then(function(data) {
        _.each(data, function(item) {
          if(!_.isEmpty(item)) {
            var model = modelMap[item.modelId];
            if (model) {
              model.subject = item.title;
              model.infoId = item.infoId;
            }
          }

        });
        $scope.infos = _infos;
      });
      return _infos;
    }, function() {
      $q.when(false);
    }).then(function(_infos) {
      refreshBackPic();
      return _infos;
    });
  }

  $scope.getItemsStyle = function() {
    var _width = _.isEmpty($scope.region) ?  window.screen.availWidth : window.screen.availWidth / 2 * $scope.region.length;
    var style = {
      'width': _width + 'px'
    };
    return style;
  };

  $scope.getItemStyle = function() {
    var style = {
      'width': window.screen.availWidth / 2 + 'px'
    };
    return style;
  };

  /**
   * 根据不同的showCard返回该标签下的内容
   */
  function changeCardRefresh() {
    var index = $scope.region.indexOf($scope.showCard);
    $scope.items = $scope.infos[index] || [];
    refreshBackPic();
  }
  /**
   * [onClickTab 刚刚标签之间的切换]
   * @param  {[string]} showCard [标签类型字符串，从页面直接传入 标签名称]
   * @return
   */
  $scope.onClickTab = function(showCard) {
    $scope.showCard = showCard;
    changeCardRefresh();
  };

  /**
   * 点击进入列表页
   */
  $scope.toMoreList = function(item) {
    $ionicViewSwitcher.nextDirection('forward');
    if(item.mode == 'yzap') {
      $state.go('infoRelease-infoReleaseYzap');
    } else if (item.mode == 'archivein' || item.mode == 'archiveout'){
      $state.go('infoRelease-infoReleaseMoreOffice', {
        modelId: item.id,
        pageNo: 0,
        enterSign: 'group'
      });
    } else if(item.mode == 'cggs') {
      $state.go('infoRelease-infoReleaseMoreCggs', {
        modelId: item.id,
        pageNo: 0,
        enterSign: 'group'
      });
    } else if(item.mode == 'ccdt') {
      $state.go('infoRelease-infoReleaseMoreCcdt');
    }else {
      $state.go('infoRelease-infoReleaseMore', {
        modelId: item.id,
        pageNo: 0,
        enterSign: 'group'
      });
    }

    ModelService.refreshShowCard($scope.showCard);//放进缓存中去
  };

  /**
   * 返回随机的背景颜色
   */
  function backgroundcolor(index) {
    var color = ['#b3e5fc', '#81d4fa', '#4fc3f7', '#29b6f6', '#03a9f4', '#039be5', '#0288e1', '#0277bd', '#01579b', '#00acc1', '#0097a7', '#00838f', '#006064'];
    if(index > 26) {//模块数 > 颜色数 * 2
      index = index -26;
    }
    return color[Math.floor(index / 2)];
  }

  /**
   * 返回有图片的背景图
   */
  $scope.backPic = function(modlId, mode, infoId) {
    var _image_url = window.localStorage.getItem('info_image_url_' + modlId);
    if(!_.isEmpty(_image_url)) {
      var image_url = _image_url.substring(1,_image_url.length - 1);
      var width = parseInt((document.body.getBoundingClientRect().width / 2) * (window.devicePixelRatio || 1));
      var url = CoreAppConfig.serverUrl + image_url +'&minWidth=' + width +
        '&minHeight=' + width + '&cut=true' ;
      return  url;
    }
  };

  /**
   * 获取背景图
   */
  $scope.getStyle = function(modlId, mode, infoId, index) {

    var styles = {
      'background': backgroundcolor(index) + ' no-repeat',
      'background-size': 'cover'
    };
    if(!_.isEmpty(backPic(modlId, mode, infoId))) {
      styles['background-image'] = 'url(' + backPic(modlId, mode, infoId) + ')';
    }

    return styles;
  };

  /**
   * 更新背景图链接
   * 如果有变化，会更新图片链接缓存
   */
  function refreshBackPic() {
    if(!_.isEmpty($scope.items)) {
      $scope.items.forEach(function(item) {
        item.imgUrl = ModelLocalStorageService.getImgPath(item.id);
        ModelService.getImgPath(item.id).then(function(imgUrl) {
          item.imgUrl =  ModelLocalStorageService.getImgPath(item.id);
        });
      });
    }
  }

  /**
   * 刷新（按钮）
   */
  $scope.onRefresh = function () {
    $scope.refreshx = true;
    initData().then(function(data) {
      $scope.refreshx = false;
      changeCardRefresh();
      if(!_.isEmpty(data)) {
        $toast.showLongCenter('更新到最新信息！');
      }else {
         $toast.showLongCenter('获取最新信息失败！');
      }

    });
  };

  /**
   * 下滑刷新
   */
  $scope.refresher = function () {
    Timer.delay(function() {
      initData().finally(function() {
        $scope.$broadcast('scroll.refreshComplete');
        changeCardRefresh();
      });
    }, 800);

  };
});
