var angular = require('angular');
require('../services/SinoFileService');
require('../../../commons/services/AppConfig');

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

module.directive('sinoFileLink', function(SinoFileService, AppConfig, WarrantService, $ionicLoading, $timeout) {
  return {
    restrict: 'E',
    template: '<button class="{{::buttonClasses}}" ng-click="openFile()">{{::title}}</button>',
    replace: true,
    scope: {
      title: '@',
      fileTitle: '@',
      buttonClasses: '@buttonClass',
      fileName: '=',
      fileType: '=?',
      lastModifiedDate: '=?',
      checkFileType: '@'
    },
    link:function(scope/*, element, attrs*/) {
      if (!scope.buttonClasses) {
        scope.buttonClasses = 'button button-clear button-positive';
      }

      scope.$watch('::fileName', function(fileName) {
        if (fileName) {
          if (scope.checkFileType) {
            SinoFileService.getFileContentByFileName(scope.fileName).then(function(response) {
              scope._fileType = response.fileType;
            });
          }
        }
      });

      function getFileType() {
        return scope.fileType || scope._fileType || 'doc';
      }

      /**
       * 查看原文按钮
       */
      scope.openFile = function() {
        var isOutDeadline = WarrantService.warrantStatus.isOutDeadline;
        if(isOutDeadline && !WarrantService.isInValidity()) {
          $ionicLoading.show({
            template: '试用期已过,请等待5s...'
          });
          $timeout(function() {
            $ionicLoading.hide();
            downFile();
          }, 5000);
        } else {
          downFile();
        }
      };

      function downFile() {
        var isIOS = ionic.Platform.isIOS();
        var url, name;

        url = '/filelist/' + scope.fileName + '/content/doc';
        name = (scope.fileTitle || scope.title) + '.' + getFileType();

        if (scope.fileName) {
          fileService.viewFile(url, name);
        }
      }
    }
  };
});
