"use strict";

function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.registerEventLayer = exports.registerEventGeometry = exports.paramSerialiser = exports.onConvertFrom = exports.mapChangeForm = exports.lonLatSearch = exports.formChangeMap = exports.addressSearch = void 0;
var _http = _interopRequireDefault(require("../../_util/http"));
var _this = void 0;
function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; }
function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; }
function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
function _slicedToArray(r, e) { return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest(); }
function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } }
function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; }
function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t["return"] && (u = t["return"](), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }
function _arrayWithHoles(r) { if (Array.isArray(r)) return r; }
var TIMEOUT;

/**
 * 地图点位与输入框联动
 * @param map 地图实例
 * @param feature 数据图层
 * @param form 表单实例
 * @param lonField 表单经度字段
 * @param latField 表单纬度字段
 * @param addrField 表单地址字段
 */
var mapChangeForm = exports.mapChangeForm = function mapChangeForm(_ref) {
  var feature = _ref.feature,
    form = _ref.form,
    _ref$lonField = _ref.lonField,
    lonField = _ref$lonField === void 0 ? 'longitude' : _ref$lonField,
    _ref$latField = _ref.latField,
    latField = _ref$latField === void 0 ? 'latitude' : _ref$latField,
    _ref$addrField = _ref.addrField,
    addrField = _ref$addrField === void 0 ? 'address' : _ref$addrField;
  if (TIMEOUT) {
    window.clearTimeout(TIMEOUT);
  }
  TIMEOUT = window.setTimeout(function () {
    var longitude, latitude;
    if (form) {
      var _form$props;
      var _ref2 = ((_form$props = form.props) === null || _form$props === void 0 ? void 0 : _form$props.form) || form,
        setFieldsValue = _ref2.setFieldsValue;
      var val = {};
      [lonField, latField, addrField].map(function (v) {
        if (v) {
          val[v] = null;
        }
      });

      // 获取经纬度
      if (feature) {
        var geometry = feature.getGeometry();
        var _geometry$getCoordina = geometry.getCoordinates(),
          _geometry$getCoordina2 = _slicedToArray(_geometry$getCoordina, 2),
          x = _geometry$getCoordina2[0],
          y = _geometry$getCoordina2[1];
        if (x && y) {
          longitude = Number(x).toFixed(6);
          latitude = Number(y).toFixed(6);
          val = _defineProperty(_defineProperty({}, lonField, longitude), latField, latitude);
          setFieldsValue(val);
          var reqList = [];

          // 判断是否存在地址
          if (addrField) {
            var req = lonLatSearch({
              lon: x,
              lat: y
            }).then(function (data) {
              return data === null || data === void 0 ? void 0 : data.formatted_address;
            })["catch"](function () {
              return '';
            });
            reqList.push(req);
          }
          Promise.all(reqList).then(function (data) {
            setFieldsValue(_defineProperty({}, addrField, data[0]));
          });
        }
      } else {
        setFieldsValue(val);
      }
    }
  }, 1000);
};

/**
 * 输入框与地图点位联动
 * @param map 地图实例
 * @param source 图层实例
 * @param form 表单实例
 * @param lonField 表单经度字段
 * @param latField 表单纬度字段
 * @param addrField 表单地址字段
 * @param areaField 表单所属镇街字段
 */
var formChangeMap = exports.formChangeMap = function formChangeMap(_ref3) {
  var map = _ref3.map,
    source = _ref3.source,
    form = _ref3.form,
    _ref3$lonField = _ref3.lonField,
    lonField = _ref3$lonField === void 0 ? 'longitude' : _ref3$lonField,
    _ref3$latField = _ref3.latField,
    latField = _ref3$latField === void 0 ? 'latitude' : _ref3$latField,
    _ref3$addrField = _ref3.addrField,
    addrField = _ref3$addrField === void 0 ? 'address' : _ref3$addrField;
  if (TIMEOUT) {
    window.clearTimeout(TIMEOUT);
  }
  TIMEOUT = window.setTimeout(function () {
    var x, y;
    if (form) {
      var _form$props2;
      var _ref4 = ((_form$props2 = form.props) === null || _form$props2 === void 0 ? void 0 : _form$props2.form) || form,
        getFieldsValue = _ref4.getFieldsValue,
        setFieldsValue = _ref4.setFieldsValue;
      var formVal = getFieldsValue();
      x = formVal[lonField];
      y = formVal[latField];
      if (x && y) {
        var reqList = [];
        if (addrField) {
          var req = lonLatSearch({
            lon: x,
            lat: y
          }).then(function (data) {
            return data === null || data === void 0 ? void 0 : data.formatted_address;
          })["catch"](function () {
            return '';
          });
          reqList.push(req);
        }
        Promise.all(reqList).then(function (data) {
          setFieldsValue(_defineProperty({}, addrField, data[0]));
        });
      }
    }
    if (source) {
      source.clear();
      if (x && y) {
        _this.addPoint({
          map: map,
          source: source,
          data: [x, y]
        });
      }
    }
  }, 1000);
};

// 经纬度转换
var onConvertFrom = exports.onConvertFrom = function onConvertFrom(lng, lat) {
  //定义一些常量
  var PI = 3.1415926535897932384626;
  var a = 6378245.0;
  var ee = 0.00669342162296594323;
  function gcj02towgs84(lng, lat) {
    if (out_of_china(lng, lat)) {
      return [lng, lat];
    } else {
      var dlat = transformlat(lng - 105.0, lat - 35.0);
      var dlng = transformlng(lng - 105.0, lat - 35.0);
      var radlat = lat / 180.0 * PI;
      var magic = Math.sin(radlat);
      magic = 1 - ee * magic * magic;
      var sqrtmagic = Math.sqrt(magic);
      dlat = dlat * 180.0 / (a * (1 - ee) / (magic * sqrtmagic) * PI);
      dlng = dlng * 180.0 / (a / sqrtmagic * Math.cos(radlat) * PI);
      var mglat = lat + dlat;
      var mglng = lng + dlng;
      return [lng * 2 - mglng, lat * 2 - mglat];
    }
  }
  function transformlat(lng, lat) {
    var ret = -100.0 + 2.0 * lng + 3.0 * lat + 0.2 * lat * lat + 0.1 * lng * lat + 0.2 * Math.sqrt(Math.abs(lng));
    ret += (20.0 * Math.sin(6.0 * lng * PI) + 20.0 * Math.sin(2.0 * lng * PI)) * 2.0 / 3.0;
    ret += (20.0 * Math.sin(lat * PI) + 40.0 * Math.sin(lat / 3.0 * PI)) * 2.0 / 3.0;
    ret += (160.0 * Math.sin(lat / 12.0 * PI) + 320 * Math.sin(lat * PI / 30.0)) * 2.0 / 3.0;
    return ret;
  }
  function transformlng(lng, lat) {
    var ret = 300.0 + lng + 2.0 * lat + 0.1 * lng * lng + 0.1 * lng * lat + 0.1 * Math.sqrt(Math.abs(lng));
    ret += (20.0 * Math.sin(6.0 * lng * PI) + 20.0 * Math.sin(2.0 * lng * PI)) * 2.0 / 3.0;
    ret += (20.0 * Math.sin(lng * PI) + 40.0 * Math.sin(lng / 3.0 * PI)) * 2.0 / 3.0;
    ret += (150.0 * Math.sin(lng / 12.0 * PI) + 300.0 * Math.sin(lng / 30.0 * PI)) * 2.0 / 3.0;
    return ret;
  }
  function out_of_china(lng, lat) {
    return lng < 72.004 || lng > 137.8347 || lat < 0.8293 || lat > 55.8271 || false;
  }
  return gcj02towgs84(lng, lat);
};
var addressSearch = exports.addressSearch = function addressSearch(address) {
  var url = "https://restapi.amap.com/v3/geocode/geo?key=2dd5476719ea3378dc06ef93b3d4aba7&city=\u6E56\u5DDE&address=".concat(address);
  return _http["default"].get(url).then(function (resp) {
    return resp.json();
  }).then(function (res) {
    var geocodes = res.geocodes,
      info = res.info,
      status = res.status;
    if (info === 'OK' && status === '1' && geocodes.length) {
      geocodes.map(function (item) {
        var location = item.location;
        if (location) {
          location = location.split(',');
          item.TDT = onConvertFrom(location[0] * 1, location[1] * 1);
        }
      });
    }
    return geocodes;
  });
};
var lonLatSearch = exports.lonLatSearch = function lonLatSearch(_ref5) {
  var lon = _ref5.lon,
    lat = _ref5.lat;
  var url = "//api.tianditu.gov.cn/geocoder?postStr={'lon':".concat(lon, ",'lat':").concat(lat, ",'ver':1}&type=geocode&tk=13b4890427f17c692f9efed46b98db81");
  return _http["default"].get(url).then(function (data) {
    var result = {};
    if (data.status === '0' && data.result) {
      result = data.result;
    }
    return result;
  });
};
var paramSerialiser = exports.paramSerialiser = function paramSerialiser(params) {
  if (!params) return '';
  var urlPart = [];
  for (var k in params) {
    var value = params[k];
    if (value === null || typeof value === 'undefined') continue;
    if (Array.isArray(value)) {
      for (var i = 0, l = value.length; i < l; i++) {
        urlPart.push("".concat(k, "=").concat(value[i]));
      }
    } else {
      urlPart.push("".concat(k, "=").concat(value));
    }
  }
  return urlPart.join('&');
};
var EVENT = ['onClick', 'onDoubleClick', 'onMouseEnter', 'onMouseMove', 'onMouseLeave'];
var registerEventGeometry = exports.registerEventGeometry = function registerEventGeometry(object, props) {
  EVENT.map(function (v) {
    object[v] = function () {
      var options = object.getProperties();
      props[v] && props[v](options);
    };
  });
};
var registerEventLayer = exports.registerEventLayer = function registerEventLayer(object, props) {
  EVENT.map(function (v) {
    object[v] = function (e) {
      props[v] && props[v](e);
    };
  });
};
//# sourceMappingURL=utils.js.map
