var angular = require('angular');
var _ = require('jsUtil');
require('../modules');
require('../services/OptionService');

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

module.directive('sinoFilecodeSelect', function(OptionService) {
  return {
    restrict: 'E',
    replace: true,
    require: '?ngModel',
    template: '<select ng-options="item.value as item.text for item in options" ng-change="onChange()"><option value="">请选择</option></select>',
    scope: {
      year: '@',
      codeDeptId: '@',
      filecodeFn: '&',
      outType: '@',
      type: '@',
      flowType: '@'
    },
    link: function(scope, element, attrs, ngModelCtrl) {
      var modelValue;
      scope.$watch('year + "_" + codeDeptId', function() {
        var outType = !_.isEmpty(scope.outType) ? scope.outType: 'ARCHIVES_OUT_ZX';
        var isSj = !_.isEmpty(scope.outType) ? true: false;
        if(scope.type === 'gjj' && scope.year) {
          if(scope.flowType === 'F_02') {
            var codeDeptId = scope.codeDeptId.substring(0, 6);
            OptionService.queryFileCodeGjjSi(outType, scope.year, codeDeptId)
              .then(function(options){
                scope.options = options;
              });
          } else {
            OptionService.queryFileCodeGjj(outType, scope.year)
              .then(function(options){
                scope.options = options;
              });
          }

        } else {
          if(scope.year && scope.codeDeptId) {
            OptionService.queryFileCode(outType, scope.year, scope.codeDeptId, isSj)
              .then(function(options){
                scope.options = options;
              });
          }
        }

      });

      scope.onChange = function() {
        modelValue = ngModelCtrl.$modelValue;
        var option;
        for (var i = 0, len = scope.options.length; i < len; i++) {
          option = scope.options[i];
          if (option.value === modelValue) {
            scope.fileCode = option.text + '〔' + scope.year + '〕';
          }
        }
        scope.filecodeFn({fileCode: scope.fileCode});
      };

    }
  };
});
