import _regeneratorRuntime from 'babel-runtime/regenerator';
import _asyncToGenerator from 'babel-runtime/helpers/asyncToGenerator';
import _classCallCheck from 'babel-runtime/helpers/classCallCheck';
import _createClass from 'babel-runtime/helpers/createClass';
import _extends from 'babel-runtime/helpers/extends';
/**
 * @文件说明: Services.GeoExport - GeoExport服务
 * @创建人: pjtools@vip.qq.com
 * @创建时间: 2020-03-27 20:39:35
 */

import assign from 'lodash/assign';
import { isBooleanFlase, isEmpty, fetchGetJson } from '../../../_util/methods-util';
import { defaultServicesSourceOptions, defaultServicesLayerOptions, getServicesLayerSource, getServicesBaseLayer } from './index';

var defaultServicesOptions = {
  // 图层名标识，多个以,逗号分割
  layerName: null,
  // 图片格式，可选值：[ image/png | image/jpeg | image/gif ]
  format: null,
  // 是否支持透明
  transparent: true,
  // 图片DPI
  dpi: null
};

/**
 * 解析GeoExport类型的服务地址获取图层服务数据信息
 */
var fetchGeoExportCapabilities = function fetchGeoExportCapabilities(own, url, options) {
  var isProxyUrl = isBooleanFlase(options.proxy) ? false : true;

  return new Promise(function (resolve, reject) {
    var capabilitiesUrl = '' + url.replace(/\/export/, '') + (url.indexOf('?') === -1 ? '?' : '&') + 'f=json';
    isProxyUrl && (capabilitiesUrl = '' + own.proxyURL + capabilitiesUrl);

    // 请求图层数据信息
    var errorMsg = 'GeoExport\u670D\u52A1\u5730\u5740[ ' + url + ' ]\u6570\u636E\u89E3\u6790\u5931\u8D25.';
    fetchGetJson(capabilitiesUrl).then(function (capabilities) {
      var opts = {};
      try {
        // 图层标识
        var layers = {};
        var layersName = [];
        capabilities.layers.map(function (item) {
          layers[item.id] = {
            id: item.id,
            name: item.name
          };
          layersName.push(item.id);
        });
        opts.layers = layers;
        opts.layersName = layersName;
        opts.layerName = !isEmpty(options.layerName) ? /show:|hide:|include:|exclude:/i.test(options.layerName) ? options.layerName : 'show:' + options.layerName : 'show:' + layersName.join(',');
        // 图片格式
        opts.formats = capabilities.supportedImageFormatTypes.split(',');
        opts.format = !isEmpty(options.format) && opts.formats.indexOf(options.format) !== -1 ? options.format : 'PNG';
        // SRS
        var defaultSRS = capabilities.spatialReference.wkid;
        opts.srs = !isEmpty(options.srs) ? options.srs.indexOf(':') !== -1 ? options.srs.split(':')[1] : options.srs : defaultSRS;
        // 矩形范围
        opts.tileBBox = [[Number(capabilities.fullExtent.xmin), Number(capabilities.fullExtent.ymin)], [Number(capabilities.fullExtent.xmax), Number(capabilities.fullExtent.ymax)]];
        opts.initialExtent = [[Number(capabilities.initialExtent.xmin), Number(capabilities.initialExtent.ymin)], [Number(capabilities.initialExtent.xmax), Number(capabilities.initialExtent.ymax)]];
        // 透明度
        opts.transparent = isBooleanFlase(options.transparent) ? false : true;
        opts.units = capabilities.units;
        opts.isTile = true;
      } catch (e) {
        console.error(errorMsg);
        reject();
      }
      resolve(opts);
    })['catch'](function () {
      console.error(errorMsg);
      reject();
    });
  });
};

/**
 * 解析GeoExport类型的服务地址获取图层样式信息
 */
var fetchGeoExportLayerStyles = function fetchGeoExportLayerStyles(own, id, url, layerOptions, options) {
  var isProxyUrl = isBooleanFlase(options.proxy) ? false : true;
  // 构建数据源
  var source = getServicesLayerSource(options);
  // 拼接数据源的ArcgisExport服务地址
  var params = {};
  params.LAYERS = layerOptions.layerName;
  params.BBOX = '{bbox-epsg-3857}';
  params.FORMAT = layerOptions.format;
  params.DPI = !isEmpty(options.dpi) ? options.dpi : 96;
  var tileSize = options.tileSize || source.defaultTileSize;
  params.SIZE = [tileSize, tileSize].join(',');
  params.TRANSPARENT = layerOptions.transparent;
  params.F = 'image';
  var exportUrl = url;
  var urlParams = '';
  Object.keys(params).map(function (key, idx) {
    if (idx !== 0) {
      urlParams += '&';
    }
    urlParams += encodeURIComponent(key) + '=' + params[key];
  });
  if (exportUrl.indexOf('?') !== -1) {
    var urlSplit = exportUrl.split('?');
    exportUrl = urlSplit[0];
    urlParams = '&' + urlSplit[1];
  }
  exportUrl.indexOf('/export') === -1 && (exportUrl += '/export');
  urlParams && (exportUrl = exportUrl + '?' + urlParams);
  isProxyUrl && (exportUrl = '' + own.proxyURL + exportUrl);
  // 设定服务源
  source.tileSize = options.tileSize || source.defaultTileSize;
  source.tiles = [exportUrl];
  // 构建图层
  var layer = getServicesBaseLayer(options);
  layer.id = id;
  layer.source = source;
  layer.metadata = assign({}, layer.metadata, _extends({
    serviceType: 'GeoExport',
    serviceName: options.name || ''
  }, layerOptions));
  return layer;
};

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

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

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


  _createClass(GeoExport, [{
    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;
        return _regeneratorRuntime.wrap(function _callee$(_context) {
          while (1) {
            switch (_context.prev = _context.next) {
              case 0:
                opts = assign(this.options, options);
                // 获取服务信息

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

              case 3:
                layerOptions = _context.sent;
                return _context.abrupt('return', fetchGeoExportLayerStyles(this, id, url, layerOptions, _extends({}, opts, { name: name })));

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

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

      return getLayer;
    }()
  }]);

  return GeoExport;
}();

export default GeoExport;