var angular = require('angular');
require('jsUtil');
require('../modules');
require('../../../commons/services/fileService');
require('../services/AffixService');

var module = angular.module('flowmodulebase.directives');

/**
 * 查看附件组件
 * <sino-affix record-id="{{official.outId}}" table-name="ARCHIVES_OUT_AFFIX" title="附件"></sino-affix>
 *
 * record-id: 主键ID
 * table-name: table表名
 * title：块标题（附件、参阅件）
 *
 */
module.directive('sinoAffix', function (fileService, AffixService, WarrantService, $ionicLoading, $timeout) {
  return {
    restrict: 'E',
    scope: {
      affixFn: '&'
    },
    templateUrl: 'views/flow/affixModule.tpl.html',
    link: function (scope, element, attrs) {
      scope.affixTitle = attrs.title;
      scope.hidden = true;
      scope.loadError = false;
      attrs.$observe('recordId', function (recordId) {
        if (recordId) {
          loadData(recordId);
        }
      });
      attrs.$observe('affixIds', function (affixIds) {
        if (affixIds) {
          loadData(attrs.recordId);
        }
      });

      function loadData(recordId) {
        AffixService.queryAffix(recordId, attrs.tableName, attrs.affixIds)
          .then(function (affixs) {
            scope.loadError = false;
            if (attrs.affixFn && affixs) {
              return affixs.filter(function (affix) {
                return scope.affixFn({ affix: affix });
              });
            }
            return affixs || [];
          }).then(function (affixs) {
            _.each(affixs, function (affix) {
              affix.title = AffixService.getTitleByFileType(affix.title, affix.type);
            });
            return affixs;
          }).then(function (affixs) {
            if (affixs) {
              scope.affixs = affixs;
              scope.hidden = !(affixs && affixs.length > 0);
            }
          }, function error() {
            scope.loadError = true;
          });
      }

      /**
       * 下载附件和参阅件
       * @param  {Affix} affix
       * @return {[type]}
       */
      scope.downFileClick = function (affix) {
        scope.loading = affix;
        var isOutDeadline = WarrantService.warrantStatus.isOutDeadline;
        if (isOutDeadline && !WarrantService.isInValidity()) {
          $ionicLoading.show({
            template: '试用期已过,请等待5s...'
          });
          $timeout(function () {
            $ionicLoading.hide();
            downFile(affix);
          }, 5000);
        } else {
          downFile(affix);
        }

      };

      function downFile(affix) {
        return AffixService.getTitle(affix.id, affix.title, affix.type).then(function (title) {
          fileService.viewAffix(affix.id, title);
        })['finally'](function () {
          delete scope.loading;
        });
      }

      scope.onRefresh = function () {
        loadData(attrs.recordId);
      }
    }
  };
});
