import _regeneratorRuntime from 'babel-runtime/regenerator';
import _asyncToGenerator from 'babel-runtime/helpers/asyncToGenerator';
import _extends from 'babel-runtime/helpers/extends';
import _classCallCheck from 'babel-runtime/helpers/classCallCheck';
import _createClass from 'babel-runtime/helpers/createClass';
/**
 * @文件说明: Services.ArcgisWMS - Arcgis WMS服务
 * @创建人: pjtools@vip.qq.com
 * @创建时间: 2020-03-26 21:47:23
 */

import assign from 'lodash/assign';
import { isBooleanFlase } from '../../../_util/methods-util';
import { defaultServicesSourceOptions, defaultServicesLayerOptions } from './index';
import { defaultServicesOptions, getWMSCapabilities, fetchWMSLayerStyles } from './wms';

/**
 * 解析Arcgis WMS类型的服务地址获取图层服务数据信息
 */
var fetchWMSCapabilities = function fetchWMSCapabilities(own, url, options) {
  var GeoGlobe = own.exports.GeoGlobe;

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

  return new Promise(function (resolve, reject) {
    var urlParams = '';
    var capabilitiesUrl = url;
    if (url.indexOf('?') !== -1) {
      var urlSplit = url.split('?');
      capabilitiesUrl = urlSplit[0];
      urlParams = urlSplit[1];
    }
    capabilitiesUrl.indexOf('/WMSServer') === -1 && (capabilitiesUrl += '/WMSServer');
    capabilitiesUrl.indexOf('/rest/services') !== -1 && (capabilitiesUrl = capabilitiesUrl.replace(/\/rest\/services/g, '/services'));
    urlParams && (capabilitiesUrl += '?' + urlParams);
    capabilitiesUrl = '' + capabilitiesUrl + (capabilitiesUrl.indexOf('?') === -1 ? '?' : '&') + 'SERVICE=WMS&REQUEST=GetCapabilities';
    isProxyUrl && (capabilitiesUrl = '' + own.proxyURL + capabilitiesUrl);

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

var ArcgisWMS = function () {
  function ArcgisWMS(iMapApi) {
    _classCallCheck(this, ArcgisWMS);

    this.iMapApi = iMapApi;
    this.exports = iMapApi && iMapApi.exports ? iMapApi.exports : {};
    this.proxyURL = iMapApi.proxyURL || '';
    this.options = _extends({}, defaultServicesSourceOptions, defaultServicesLayerOptions, defaultServicesOptions);
  }

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


  _createClass(ArcgisWMS, [{
    key: 'getLayer',
    value: function () {
      var _ref = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.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, layer, isProxyUrl, urlParams, wmsUrl, urlSplit;
        return _regeneratorRuntime.wrap(function _callee$(_context) {
          while (1) {
            switch (_context.prev = _context.next) {
              case 0:
                opts = assign(this.options, options);
                // 获取服务信息

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

              case 3:
                layerOptions = _context.sent;

                // 获取Arcgis WMS图层
                layer = fetchWMSLayerStyles(this, id, url, layerOptions, _extends({}, opts, { name: name }));

                layer.metadata.serviceType = 'ArcgisWMS';
                // 计算Arcgis WMS的数据源地址
                isProxyUrl = isBooleanFlase(opts.proxy) ? false : true;
                urlParams = '';
                wmsUrl = layer.source.tiles[0];

                isProxyUrl && (wmsUrl = wmsUrl.replace(this.proxyURL, ''));
                if (wmsUrl.indexOf('?') !== -1) {
                  urlSplit = wmsUrl.split('?');

                  wmsUrl = urlSplit[0];
                  urlParams = urlSplit[1];
                }
                wmsUrl.indexOf('/WMSServer') === -1 && (wmsUrl += '/WMSServer');
                wmsUrl.indexOf('/rest/services') !== -1 && (wmsUrl = wmsUrl.replace(/\/rest\/services/g, '/services'));
                urlParams && (wmsUrl += '?' + urlParams);
                isProxyUrl && (wmsUrl = '' + this.proxyURL + wmsUrl);
                layer.source.tiles = [wmsUrl];
                layer.metadata.template = wmsUrl;
                return _context.abrupt('return', layer);

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

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

      return getLayer;
    }()
  }]);

  return ArcgisWMS;
}();

export default ArcgisWMS;