'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.fetchWMSLayerStyles = exports.getWMSCapabilities = exports.defaultServicesOptions = undefined;

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 _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 = exports.defaultServicesOptions = {
  // 版本号，可选值：[ 1.1.1 | 1.3.0 ]
  version: null,
  // 图层名标识，多个以,逗号分割
  layerName: null,
  // 图层样式名
  styleName: null,
  // 图片格式，可选值：[ image/png | image/jpeg | image/gif ]
  format: null,
  // 空间坐标系统
  srs: null,
  // 是否支持透明
  transparent: true
};

/**
 * 解析标准WMS类型服务Capabilities信息
 */
/**
 * @文件说明: Services.WMS - WMS服务
 * @创建人: pjtools@vip.qq.com
 * @创建时间: 2020-03-26 14:13:06
 */

var getWMSCapabilities = exports.getWMSCapabilities = function getWMSCapabilities(capabilities, root, options, GeoGlobe) {
  try {
    var opts = {};
    // 获取版本号
    var version = capabilities.querySelector(root).getAttribute('version');
    if (version === '1.3.0') {
      capabilities = new GeoGlobe.Format.WMSCapabilities.v1_3_0().read(capabilities);
    } else {
      capabilities = new GeoGlobe.Format.WMSCapabilities.v1_1_1().read(capabilities);
    }
    opts.version = !(0, _methodsUtil.isEmpty)(options.version) && ['1.1.1', '1.3.0'].indexOf(options.version) ? options.version : version;
    // 图层标识
    var layers = capabilities.capability.layers;
    var defaultLayer = layers[0];
    var layersName = [];
    var wmslayers = {};
    layers.map(function (layer) {
      wmslayers[layer.name] = {
        minScale: layer.minScale ? Number(layer.minScale) : null,
        maxScale: layer.maxScale ? Number(layer.maxScale) : null,
        styles: layer.styles && layer.styles[0] && layer.styles[0].name || ''
      };
      layersName.push(layer.name);
    });
    opts.layers = wmslayers;
    opts.layersName = layersName;
    opts.layerName = !(0, _methodsUtil.isEmpty)(options.layerName) ? options.layerName : layersName.join(',');
    // 图片格式
    opts.formats = defaultLayer.formats;
    opts.format = !(0, _methodsUtil.isEmpty)(options.format) && opts.formats.indexOf(options.format) !== -1 ? options.format : 'image/png';
    // 图层样式名称
    var defaultStyleName = defaultLayer.styles && defaultLayer.styles[0] && defaultLayer.styles[0].name || 'default';
    if (!(0, _methodsUtil.isEmpty)(options.styleName)) {
      opts.styleName = options.styleName;
    } else {
      var stylesName = opts.layerName.split(',').map(function (item) {
        return opts.layers[item] && opts.layers[item].styles || defaultStyleName;
      });
      opts.styleName = stylesName.join(',');
    }
    // SRS
    var srsKeys = Object.keys(defaultLayer.srs) || [];
    var defaultSRS = null;
    var srsList = [];
    for (var i = 0, len = srsKeys.length; i < len; i++) {
      if ((0, _methodsUtil.isBooleanTrue)(defaultLayer.srs[srsKeys[i]]) && srsKeys[i] !== 'CRS:84') {
        defaultSRS = srsKeys[i];
      }
      srsList.push(srsKeys[i]);
    }
    defaultSRS = !defaultSRS ? srsKeys[0] || '' : defaultSRS;
    opts.srs = !(0, _methodsUtil.isEmpty)(options.srs) ? options.srs : defaultSRS;
    opts.srsList = srsList;
    // 矩形范围
    var bbox = {};
    Object.keys(defaultLayer.bbox).map(function (key) {
      var item = defaultLayer.bbox[key].bbox;
      if (key === 'CRS:84' || opts.version !== '1.3.0') {
        bbox[key] = [[Number(item[0]), Number(item[1])], [Number(item[2]), Number(item[3])]];
      } else {
        bbox[key] = [[Number(item[1]), Number(item[0])], [Number(item[3]), Number(item[2])]];
      }
    });
    opts.bbox = bbox;
    opts.tileBBox = bbox[opts.srs];
    // 透明度
    opts.transparent = (0, _methodsUtil.isBooleanFlase)(options.transparent) ? false : true;
    opts.isTile = true;
    return opts;
  } catch (e) {
    return null;
  }
};

/**
 * 解析WMS类型的服务地址获取图层服务数据信息
 */
var fetchWMSCapabilities = function fetchWMSCapabilities(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=WMS&REQUEST=GetCapabilities';
    isProxyUrl && (capabilitiesUrl = '' + own.proxyURL + capabilitiesUrl);

    // 请求图层数据信息
    var errorMsg = 'WMS\u670D\u52A1\u5730\u5740[ ' + url + ' ]\u6570\u636E\u89E3\u6790\u5931\u8D25.';
    GeoGlobe.Request.GET({
      url: capabilitiesUrl,
      success: function success(data) {
        var opts = {};
        try {
          // 获取WMS服务的Capabilities信息
          var capabilities = !data.responseXML || !data.responseXML.documentElement ? data.responseText : data.responseXML;
          var wmsOpts = getWMSCapabilities(capabilities, 'WMT_MS_Capabilities', options, GeoGlobe);
          if (wmsOpts) {
            opts = (0, _assign2['default'])({}, opts, wmsOpts);
          } else {
            console.error(errorMsg);
            reject();
          }
        } catch (e) {
          console.error(errorMsg);
          reject();
        }
        resolve(opts);
      },
      failure: function failure() {
        console.error(errorMsg);
        reject();
      }
    });
  });
};

/**
 * 解析WMS类型的服务地址获取图层样式信息
 */
var fetchWMSLayerStyles = exports.fetchWMSLayerStyles = function fetchWMSLayerStyles(own, id, url, layerOptions, options) {
  var isProxyUrl = (0, _methodsUtil.isBooleanFlase)(options.proxy) ? false : true;
  // 构建数据源
  var source = (0, _index.getServicesLayerSource)(options);
  // 拼接数据源的WMS服务地址
  var params = {};
  params.SERVICE = 'WMS';
  params.REQUEST = 'GetMap';
  params.VERSION = layerOptions.version;
  params.LAYERS = layerOptions.layerName;
  params.STYLES = layerOptions.styleName;
  params.FORMAT = layerOptions.format;
  params.BBOX = '{bbox-epsg-3857}';
  params.WIDTH = options.tileSize || source.defaultTileSize;
  params.HEIGHT = options.tileSize || source.defaultTileSize;
  params[layerOptions.version === '1.3.0' ? 'CRS' : 'SRS'] = layerOptions.srs;
  params.TRANSPARENT = layerOptions.transparent;
  var wmsUrl = '';
  Object.keys(params).map(function (key, idx) {
    if (idx !== 0) {
      wmsUrl += '&';
    }
    wmsUrl += encodeURIComponent(key) + '=' + params[key];
  });
  wmsUrl = '' + url + (url.indexOf('?') === -1 ? '?' : '&') + wmsUrl;
  isProxyUrl && (wmsUrl = '' + own.proxyURL + wmsUrl);
  // 设定服务源
  source.tileSize = options.tileSize || source.defaultTileSize;
  source.tiles = [wmsUrl];
  // 构建图层
  var layer = (0, _index.getServicesBaseLayer)(options);
  layer.id = id;
  layer.source = source;
  layer.metadata = (0, _assign2['default'])({}, layer.metadata, (0, _extends3['default'])({
    serviceType: 'WMS',
    serviceName: options.name || '',
    template: wmsUrl
  }, layerOptions));
  return layer;
};

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

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

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


  (0, _createClass3['default'])(WMS, [{
    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 fetchWMSCapabilities(this, url, opts);

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

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

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

      return getLayer;
    }()
  }]);
  return WMS;
}();

exports['default'] = WMS;