var angular = require('angular');
require('../modules');
'use strict';

/**
 * 信息发布Detail页面 缓存服务
 */
var module = angular.module('notice.directives');

module.directive('sinoNoticeMessage', function(AppConfig, $state, $toast) {
  return {
    restrict: 'E',
    templateUrl: 'views/notice/sinoNoticeMessage.tpl.html',
    link: function(scope) {
      var unKnowModuleClass = 'icon ion-help-circled',
        unKnowModuleName = '未知模块';

      scope.$watch('appNotices', function() {
        generateShowNotice();
      }, true);

      function generateShowNotice() {

        var showItems = [], _unreadNum = 0;
        var items = _.copy(scope.appNotices.notices);
         _.each(items, function(item) {
          if(item.unreadNum === 0 || !item.content){
            return;
          }

          var module = AppConfig.getModuleByName(item.moduleName);
          if(AppConfig.showInNotice(item.moduleName)) {
            if(module) {
              item.moduleClass = module.moduleClass;
              item.text = module.text;
            } else {
              item.moduleClass = unKnowModuleClass;
              item.text = unKnowModuleName;
            }
            showItems.push(item);
            _unreadNum = _unreadNum + item.unreadNum;
          }

        });
        scope.notices = showItems;
        scope.appNotices.unreadNum = _unreadNum;
      }

      scope.toModule = function(notice) {
        var module = AppConfig.getModuleByName(notice.moduleName);
        if (!module) {
          $toast.showShortCenter('该模块尚未开发，请在PC端查看！');
        }

        if (module.state instanceof Function) {
          module.state();
        } else {
          $state.go(module.state);
        }
      };
    }
  };
});
