'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});

var _regenerator = require('babel-runtime/regenerator');

var _regenerator2 = _interopRequireDefault(_regenerator);

var _asyncToGenerator2 = require('babel-runtime/helpers/asyncToGenerator');

var _asyncToGenerator3 = _interopRequireDefault(_asyncToGenerator2);

var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');

var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);

var _createClass2 = require('babel-runtime/helpers/createClass');

var _createClass3 = _interopRequireDefault(_createClass2);

var _extends2 = require('babel-runtime/helpers/extends');

var _extends3 = _interopRequireDefault(_extends2);

var _toConsumableArray2 = require('babel-runtime/helpers/toConsumableArray');

var _toConsumableArray3 = _interopRequireDefault(_toConsumableArray2);

var _assign = require('lodash/assign');

var _assign2 = _interopRequireDefault(_assign);

var _methodsUtil = require('../../../_util/methods-util');

var _index = require('./index');

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }

var defaultServicesOptions = {
  // 版本号
  version: null,
  // 图层名标识
  layerName: null,
  // 矢量瓦片格式，可选值：[ protobuf | image/png | image/jpeg ]
  format: 'protobuf',
  // 图层矩阵集名
  layerMatrixSet: null,
  // 图层样式名
  styleName: null
};

/**
 * 解析VTS类型的服务地址获取图层服务数据信息
 */
/**
 * @文件说明: Services.VTS 吉奥VTS矢量瓦片服务
 * @创建人: pjtools@vip.qq.com
 * @创建时间: 2020-03-24 16:18:34
 */

var fetchVTSCapabilities = function fetchVTSCapabilities(own, url, options) {
  var GeoGlobe = own.exports.GeoGlobe;

  var isProxyUrl = (0, _methodsUtil.isBooleanFlase)(options.proxy) ? false : true;

  return new Promise(function (resolve, reject) {
    var capabilitiesUrl = '' + url + (url.indexOf('?') === -1 ? '?' : '&') + 'SERVICE=WMTS&VERSION=1.0.0&REQUEST=GetCapabilities';
    isProxyUrl && (capabilitiesUrl = '' + own.proxyURL + capabilitiesUrl);
    isProxyUrl && (url = '' + own.proxyURL + url);

    var opts = { url: url };
    // 请求图层数据信息
    var errorMsg = '\u77E2\u91CF\u74E6\u7247VTS\u670D\u52A1\u5730\u5740[ ' + url + ' ]\u6570\u636E\u89E3\u6790\u5931\u8D25.';
    GeoGlobe.Request.GET({
      url: capabilitiesUrl,
      success: function success(data) {
        try {
          var capabilities = new GeoGlobe.Format.XML().read(data.responseText);
          if (capabilities) {
            var layers = capabilities.querySelector('Contents').querySelectorAll('Layer');
            var defaultLayer = layers[0];
            // 图层标识
            var defaultLayerName = defaultLayer.querySelector('Identifier').textContent;
            opts.layer = !(0, _methodsUtil.isEmpty)(options.layerName) ? options.layerName : defaultLayerName;
            // 矢量瓦片格式
            var format = defaultLayer.querySelectorAll('Format');
            var formatList = [];
            if (format) {
              format.forEach(function (item) {
                formatList.push(item.textContent);
              });
            }
            opts.format = options.format && formatList.indexOf(options.format) !== -1 ? options.format : 'protobuf';
            opts.formats = formatList;
            // 矩阵集名称
            var matrixSet = capabilities.querySelector('Contents').querySelectorAll('Layer + TileMatrixSet');
            var defaultMatrixSet = matrixSet[0].querySelector('Identifier').textContent;
            opts.matrixSet = !(0, _methodsUtil.isEmpty)(options.layerMatrixSet) ? options.layerMatrixSet : defaultMatrixSet;
            // 图层样式名称
            var styles = defaultLayer.querySelector('Style').querySelectorAll('Identifier');
            var defaultStyleName = styles[0].textContent;
            opts.styleName = !(0, _methodsUtil.isEmpty)(options.styleName) ? options.styleName : defaultStyleName;
            // 版本号
            var version = capabilities.querySelector('ServiceTypeVersion').textContent;
            opts.version = !(0, _methodsUtil.isEmpty)(options.version) ? options.version : version;
            // 矩形范围
            var bounding = defaultLayer.querySelector('BoundingBox');
            var minbound = bounding.querySelector('LowerCorner').textContent.split(' ');
            var maxbound = bounding.querySelector('UpperCorner').textContent.split(' ');
            var defaultBounds = [].concat((0, _toConsumableArray3['default'])(minbound), (0, _toConsumableArray3['default'])(maxbound)).join(',');
            opts.tileBBox = defaultBounds;
            // 瓦片层级信息
            var tileMatrix = matrixSet[0].querySelectorAll('TileMatrix');
            var zoom = [];
            var tileMatrixs = [];
            var tileSize = 256;
            tileMatrix.forEach(function (item, idx) {
              var currentZoom = parseInt(item.querySelector('Identifier').textContent, 10);
              zoom.push(currentZoom);
              tileMatrixs.push({
                identifier: currentZoom,
                scale: Number(item.querySelector('ScaleDenominator').textContent),
                matrixWidth: Number(item.querySelector('MatrixWidth').textContent),
                matrixHeight: Number(item.querySelector('MatrixHeight').textContent)
              });
              if (idx === 0) {
                tileSize = Number(item.querySelector('TileWidth').textContent);
              }
            });
            opts.tileSize = tileSize;
            opts.tileMatrixs = tileMatrixs;
            opts.zoom = zoom;
            opts.minZoom = zoom[0];
            opts.maxZoom = zoom[zoom.length - 1];
          }
        } catch (e) {
          console.error(errorMsg);
          reject();
        }
        resolve(opts);
      },
      failure: function failure() {
        console.error(errorMsg);
        reject();
      }
    });
  });
};

/**
 * 解析VTS类型的服务地址获取图层样式信息
 */
var fetchVTSLayerStyles = function fetchVTSLayerStyles(own, id, url, layerOptions, options) {
  var isProxyUrl = (0, _methodsUtil.isBooleanFlase)(options.proxy) ? false : true;

  return new Promise(function (resolve, reject) {
    var stylesUrl = '' + url + (url.indexOf('?') === -1 ? '?' : '&') + 'REQUEST=GetStyle&SERVICE=WMTS&VERSION=1.0.0&STYLENAME=' + layerOptions.styleName;
    isProxyUrl && (stylesUrl = '' + own.proxyURL + stylesUrl);

    (0, _methodsUtil.fetchGetJson)(stylesUrl).then(function (data) {
      // 构建数据源
      var source = (0, _index.getServicesLayerSource)(options);
      source.id = id;
      source.type = 'vector';
      // 拼接数据源的矢量瓦片服务地址
      var params = {};
      params.service = 'WMTS';
      params.request = 'GetTile';
      layerOptions.version && (params.VERSION = layerOptions.version);
      layerOptions.layer && (params.LAYER = layerOptions.layer);
      layerOptions.matrixSet && (params.TILEMATRIXSET = layerOptions.matrixSet);
      layerOptions.format && (params.FORMAT = layerOptions.format);
      params.TILEMATRIX = '{z}';
      params.TILEROW = '{y}';
      params.TILECOL = '{x}';
      if (layerOptions.tileSize) {
        params.WIDTH = layerOptions.tileSize;
        params.HEIGHT = layerOptions.tileSize;
      }
      var vectorUrl = '';
      Object.keys(params).map(function (key, idx) {
        if (idx !== 0) {
          vectorUrl += '&';
        }
        vectorUrl += encodeURIComponent(key) + '=' + params[key];
      });
      vectorUrl = '' + url + (url.indexOf('?') === -1 ? '?' : '&') + vectorUrl;
      isProxyUrl && (vectorUrl = '' + own.proxyURL + vectorUrl);
      // 设定服务源
      source.tiles = [vectorUrl];
      source.tileSize = options.tileSize || layerOptions.tileSize || source.defaultTileSize;
      // Metadata信息
      var metadata = (0, _extends3['default'])({}, layerOptions);
      metadata.layerName = layerOptions.layer;
      metadata.url = url;
      metadata.vtsStyleName = data.name || '';
      metadata.sprite = data.sprite ? '' + (isProxyUrl ? own.proxyURL : '') + data.sprite : '';
      metadata.glyphs = data.glyphs ? '' + (isProxyUrl ? own.proxyURL : '') + data.glyphs : '';
      metadata.serviceType = 'VTS';
      metadata.serviceName = options.name || '';
      metadata['vts:group'] = id;
      options.metadata && (metadata['layer:meta'] = options.metadata);
      if (metadata.tileBBox) {
        var bbox = metadata.tileBBox.split(',');
        metadata.tileBBox = [[Number(bbox[0]), Number(bbox[1])], [Number(bbox[2]), Number(bbox[3])]];
      }
      // 图层
      var vtsLayers = data.styleData || data.layers || [];
      var layers = vtsLayers.map(function (layer) {
        layer.metadata = metadata;
        if (layer.type !== 'background') {
          layer.source = id;
        }
        layer.metadata.visibility = layer.layout.visibility && layer.layout.visibility === 'none' ? 'none' : 'visible';
        return layer;
      });

      resolve({
        id: id,
        type: 'VTS',
        layers: layers,
        source: source
      });
    })['catch'](function () {
      console.error('\u77E2\u91CF\u74E6\u7247VTS\u670D\u52A1\u5730\u5740[' + url + ']\u6570\u636E\u89E3\u6790\u5931\u8D25.');
      reject();
    });
  });
};

var VTS = function () {
  function VTS(iMapApi) {
    (0, _classCallCheck3['default'])(this, VTS);

    this.iMapApi = iMapApi;
    this.exports = iMapApi && iMapApi.exports ? iMapApi.exports : {};
    this.proxyURL = iMapApi.proxyURL || '';
    this.options = (0, _extends3['default'])({}, _index.defaultServicesSourceOptions, _index.defaultServicesLayerOptions, defaultServicesOptions);
  }

  /**
   * 获取解析XYZTile服务的图层对象
   * @param {String} id 图层Id名称
   * @param {String} name 图层Name名
   * @param {String} url 服务地址
   * @param {Object} options 解析服务的参数选项
   */


  (0, _createClass3['default'])(VTS, [{
    key: 'getLayer',
    value: function () {
      var _ref = (0, _asyncToGenerator3['default'])( /*#__PURE__*/_regenerator2['default'].mark(function _callee(id) {
        var name = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';
        var url = arguments[2];
        var options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
        var opts, layerOptions;
        return _regenerator2['default'].wrap(function _callee$(_context) {
          while (1) {
            switch (_context.prev = _context.next) {
              case 0:
                opts = (0, _assign2['default'])(this.options, options);
                // 获取服务信息

                _context.next = 3;
                return fetchVTSCapabilities(this, url, opts);

              case 3:
                layerOptions = _context.sent;
                _context.next = 6;
                return fetchVTSLayerStyles(this, id, url, layerOptions, (0, _extends3['default'])({}, opts, { name: name }));

              case 6:
                return _context.abrupt('return', _context.sent);

              case 7:
              case 'end':
                return _context.stop();
            }
          }
        }, _callee, this);
      }));

      function getLayer(_x3) {
        return _ref.apply(this, arguments);
      }

      return getLayer;
    }()
  }]);
  return VTS;
}();

exports['default'] = VTS;