var angular = require('angular'),
  _ = require('jsUtil');
require('../modules');
require('../../../commons/services/LocalCache');

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

module.factory('OptionService', function($http, $q, LocalCache) {
  var getterFn = function(key) {
    var optionName = key.substring(10);
    return $http.get('/common/option/' + optionName)
      .then(function(response) {
        return response.data;
      });
  };
  var haveSettedKeys = [];

  var OptionService = {
    get: function(optionName) {
      var optionNames = _.isArray(optionName)? optionName : _.toArray(arguments);
      var promises = _.map(optionNames, function(optionName) {
        var key = '$$options.' + optionName;
        if (_.indexOf(haveSettedKeys, key) === -1) {
          LocalCache.setGetter(key, getterFn);
          haveSettedKeys.push(key);
        }

        return LocalCache.get(key);
      });

      return $q.all(promises);
    },
    /**
     * 获取发文字号
     * @param  {String} outType 发文类型
     * @param  {String} year 发文年限
     * @param  {String} codeDeptId 发文字号ID
     * @return {Promise}         发文字号对象
     * url/common/option/ filecode/?year=2014&codeDeptId=001001
     */
    queryFileCode: function(outType, year, codeDeptId, isSj) {
      var _url = !isSj || _.isEmpty(isSj) ? '/archive/out/fileCode/' : '/common/option/fileCode/';
      var url = _url + outType + (_.isUndefined(year)?'':'?year=' + year) + (_.isUndefined(codeDeptId)?'':'&codeDeptId='+codeDeptId);
      return $http.get(url, {
        timeout: 15000
      }).then(function(response) {
        return response.data;
      });
    },

    queryFileCodeGjj: function(tableName, year) {
      return $http.get('/common/option/fileCode/' + tableName + '?year=' + year, {
        timeout: 15000
      }).then(function(response) {
        return response.data;
      });
    },
    queryFileCodeGjjSi: function(tableName, year, codeDeptId) {
      return $http.get('/common/option/fileCode/' + tableName + '?year=' + year + '&codeDeptId=' + codeDeptId, {
        timeout: 15000
      }).then(function(response) {
        return response.data;
      });
    }
  };

  return OptionService;
});
