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

/**
 * 解析GeoExport类型的服务地址获取图层服务数据信息
 */
/**
 * @文件说明: Services.GeoExport - GeoExport服务
 * @创建人: pjtools@vip.qq.com
 * @创建时间: 2020-03-27 20:39:35
 */

var fetchGeoExportCapabilities = function fetchGeoExportCapabilities(own, url, options) {
  var isProxyUrl = (0, _methodsUtil.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.';
    (0, _methodsUtil.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 = !(0, _methodsUtil.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 = !(0, _methodsUtil.isEmpty)(options.format) && opts.formats.indexOf(options.format) !== -1 ? options.format : 'PNG';
        // SRS
        var defaultSRS = capabilities.spatialReference.wkid;
        opts.srs = !(0, _methodsUtil.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 = (0, _methodsUtil.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 = (0, _methodsUtil.isBooleanFlase)(options.proxy) ? false : true;
  // 构建数据源
  var source = (0, _index.getServicesLayerSource)(options);
  // 拼接数据源的ArcgisExport服务地址
  var params = {};
  params.LAYERS = layerOptions.layerName;
  params.BBOX = '{bbox-epsg-3857}';
  params.FORMAT = layerOptions.format;
  params.DPI = !(0, _methodsUtil.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 = (0, _index.getServicesBaseLayer)(options);
  layer.id = id;
  layer.source = source;
  layer.metadata = (0, _assign2['default'])({}, layer.metadata, (0, _extends3['default'])({
    serviceType: 'GeoExport',
    serviceName: options.name || ''
  }, layerOptions));
  return layer;
};

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

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

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


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

              case 3:
                layerOptions = _context.sent;
                return _context.abrupt('return', fetchGeoExportLayerStyles(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 GeoExport;
}();

exports['default'] = GeoExport;