"use strict";

exports.__esModule = true;
exports["default"] = void 0;

var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator"));

var _react = _interopRequireWildcard(require("react"));

var _InputText = _interopRequireDefault(require("./../InputText"));

var _Bridge = _interopRequireDefault(require("./../Bridge"));

var _locale = _interopRequireDefault(require("./../locale"));

var _Map = _interopRequireDefault(require("./Map"));

var _excluded = ["cacheTime", "timeout", "ak", "editConfig", "message", "preview", "readOnly", "onClick", "onChange", "mapPageProps", "routePath", "value"];

function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }

function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; }

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }

function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }

function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }

function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }

function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }

// 定位超时setTimeout指针
var getLocationTimeout = null; // 地图预览数据

var viewMapData = null;
/* 默认配置 */
// 非只读配置

var editConfigDefault = {
  type: 'location',
  // 背景定位location|选择定位choose
  editable: false,
  // 可修改文字true|不可修改文字false
  autoLocation: false,
  // 自动定位, 选点模式不支持自动定位
  clear: null // 清空回调

}; // 文本框中提示信息配置

var messageDefault = {
  // 定位时文案
  loading: (0, _locale["default"])('定位中...', 'location'),
  // 失败时文案
  failed: (0, _locale["default"])('定位失败, 请检查定位权限是否开启', 'hint_location_failed')
}; // 定位控件

var InputLocation = (0, _react.forwardRef)(function (_ref, ref) {
  var _editConfig4, _editConfig5, _editConfig6, _editConfig7;

  var _ref$cacheTime = _ref.cacheTime,
      cacheTime = _ref$cacheTime === void 0 ? 10000 : _ref$cacheTime,
      timeout = _ref.timeout,
      ak = _ref.ak,
      editConfig = _ref.editConfig,
      message = _ref.message,
      preview = _ref.preview,
      _ref$readOnly = _ref.readOnly,
      readOnly = _ref$readOnly === void 0 ? false : _ref$readOnly,
      onClick = _ref.onClick,
      onChange = _ref.onChange,
      mapPageProps = _ref.mapPageProps,
      _ref$routePath = _ref.routePath,
      routePath = _ref$routePath === void 0 ? 'componentPage=1' : _ref$routePath,
      value = _ref.value,
      others = _objectWithoutPropertiesLoose(_ref, _excluded);

  // 定位状态, -1.定位中 0.定位失败时隐藏text框, 显示定位中或者定位失败的div, 1定位成功显示文本框
  var _useState = (0, _react.useState)('1'),
      status = _useState[0],
      setStatus = _useState[1]; // 地图预览


  var _useState2 = (0, _react.useState)(false),
      viewMapVisible = _useState2[0],
      setViewMapVisible = _useState2[1]; // 因为在click事件内改变数据的可能性, 所以更新句柄, 防止synchronization模式读取创建时的状态


  var onChangeRef = (0, _react.useRef)();
  onChangeRef.current = onChange;
  var onPreviewRef = (0, _react.useRef)();
  onPreviewRef.current = preview;
  /* 默认配置 */
  // 非只读配置

  editConfig = _extends({}, editConfigDefault, editConfig || {}); // 提示信息配置

  if (Object.prototype.toString.call(message) === '[object Object]') {
    for (var msg in messageDefault) {
      if (typeof message[msg] !== 'string') {
        message[msg] = messageDefault[msg];
      }
    }
  } else {
    message = messageDefault;
  } // 返回的dom


  var inputTextRef = (0, _react.useRef)(null);
  (0, _react.useImperativeHandle)(ref, function () {
    return inputTextRef.current;
  }); // 自动定位

  (0, _react.useEffect)(function () {
    var _editConfig;

    if (readOnly) return;
    if (((_editConfig = editConfig) === null || _editConfig === void 0 ? void 0 : _editConfig.autoLocation) !== true) return;
    handleAutoLocation();
  }, [readOnly]); // 自动定位

  function handleAutoLocation() {
    return _handleAutoLocation.apply(this, arguments);
  } // 点击文本框


  function _handleAutoLocation() {
    _handleAutoLocation = _asyncToGenerator( /*#__PURE__*/_regenerator["default"].mark(function _callee2() {
      var _editConfig8;

      var result, address;
      return _regenerator["default"].wrap(function _callee2$(_context2) {
        while (1) {
          switch (_context2.prev = _context2.next) {
            case 0:
              if (!(((_editConfig8 = editConfig) === null || _editConfig8 === void 0 ? void 0 : _editConfig8.autoLocation) !== true)) {
                _context2.next = 2;
                break;
              }

              return _context2.abrupt("return");

            case 2:
              if (!(value && value.latitude && value.longitude)) {
                _context2.next = 17;
                break;
              }

              if (!value.address) {
                _context2.next = 7;
                break;
              }

              // 有地址, 则定位完成
              if (onChangeRef && onChangeRef.current) onChangeRef.current({
                target: inputTextRef.current
              }, value);
              _context2.next = 15;
              break;

            case 7:
              // 无地址, 则需要地址逆解析
              status = '-1';
              setStatus('-1'); // 定位中...

              _context2.next = 11;
              return _Bridge["default"].getAddress({
                // 只支持gcj02
                latitude: value.latitude,
                longitude: value.longitude
              });

            case 11:
              result = _context2.sent;
              address = result && result.address ? result.address : '';
              result.value = address;

              if (address) {
                status = '1';
                setStatus('1'); // 回调onChange

                if (onChangeRef && onChangeRef.current) onChangeRef.current({
                  target: inputTextRef.current
                }, result); // 自动定位设置选择地图的数据

                viewMapData = {
                  point: [result.longitude, result.latitude],
                  address: result.address
                };
              } else {
                status = '0';
                setStatus('0');
              }

            case 15:
              _context2.next = 18;
              break;

            case 17:
              handleLocation({
                target: inputTextRef.current,
                currentTarget: inputTextRef.current
              });

            case 18:
            case "end":
              return _context2.stop();
          }
        }
      }, _callee2);
    }));
    return _handleAutoLocation.apply(this, arguments);
  }

  function handleClick(event, val) {
    var _editConfig2;

    var e = event.nativeEvent; // 正在定位不允许操作

    if (status === '-1') {
      return;
    } // 点击输入


    if (!readOnly && editConfig.editable) {
      if (status === '0') {
        // 非只读状态下, 点击错误面板, 允许手动输入位置
        status = '1';
        setStatus('1');
      }

      return;
    } // 触发点击事件


    if (onClick) {
      onClick(e, val);
    } // 定位按钮


    if (e.target.classList.contains('input-location-icon') && !e.target.classList.contains('input-location-icon-choose')) {
      handleLocation(e);
      return;
    } // 清除按钮


    if (e.target.classList.contains('clearicon')) {
      return;
    } // 预览


    if (readOnly && preview) {
      handlePreview();
      return;
    } // 地图选点


    if (!readOnly && ((_editConfig2 = editConfig) === null || _editConfig2 === void 0 ? void 0 : _editConfig2.type) === 'choose') {
      handlePreview();
      return;
    } // 点击整行定位


    handleLocation(e);
  } // 定位, isAutoLocation表示初始化时自动定位


  function handleLocation(e) {
    // 定位中...
    status = '-1';
    setStatus('-1'); // 定位超时处理

    if (!isNaN(timeout)) {
      if (Number(timeout) < 1000) {
        console.warn('InputLocation: 超时参数timeout不能小于1000毫秒');
      } else {
        if (getLocationTimeout) window.clearTimeout(getLocationTimeout);
        getLocationTimeout = setTimeout(function () {
          if (status === '-1') {
            if (onChangeRef && onChangeRef.current) onChangeRef.current(e, {
              errMsg: "getLocation:fail" + (0, _locale["default"])('定位超时', 'hint_location_timeout') + " Timeout"
            });
            status = '0';
            setStatus('0');
          }
        }, timeout);
      }
    } // 开始定位


    _Bridge["default"].getLocation({
      cacheTime: cacheTime,
      type: 'gcj02',
      success: function () {
        var _success = _asyncToGenerator( /*#__PURE__*/_regenerator["default"].mark(function _callee(data) {
          var result, address;
          return _regenerator["default"].wrap(function _callee$(_context) {
            while (1) {
              switch (_context.prev = _context.next) {
                case 0:
                  if (!(status === '0')) {
                    _context.next = 3;
                    break;
                  }

                  console.log('定位超时, 不再执行成功回调');
                  return _context.abrupt("return");

                case 3:
                  if (!data.address) {
                    _context.next = 6;
                    break;
                  }

                  // 赋值
                  if (onChange) {
                    data.value = data.address;
                    if (onChangeRef && onChangeRef.current) onChangeRef.current(e, data);
                    status = '1';
                    setStatus('1'); // 自动定位设置选择地图的数据

                    viewMapData = {
                      point: [data.longitude, data.latitude],
                      address: data.address
                    };
                  }

                  return _context.abrupt("return");

                case 6:
                  _context.next = 8;
                  return _Bridge["default"].getAddress({
                    // 只支持gcj02
                    latitude: data.latitude,
                    longitude: data.longitude
                  });

                case 8:
                  result = _context.sent;
                  result = _extends({}, data, result);
                  address = result && result.address ? result.address : '';
                  result.value = address;
                  if (onChangeRef && onChangeRef.current) onChangeRef.current(e, result);

                  if (address) {
                    status = '1';
                    setStatus('1'); // 自动定位设置选择地图的数据

                    viewMapData = {
                      point: [data.longitude, data.latitude],
                      address: address
                    };
                  } else {
                    status = '0';
                    setStatus('0');
                  }

                case 14:
                case "end":
                  return _context.stop();
              }
            }
          }, _callee);
        }));

        function success(_x) {
          return _success.apply(this, arguments);
        }

        return success;
      }(),
      fail: function fail(res) {
        // 定位超时后不再执行回调
        if (status === '0') {
          console.log('定位超时, 不再执行失败回调');
          return;
        } // 赋值


        if (onChangeRef && onChangeRef.current) onChangeRef.current(e, res);
        status = '0';
        setStatus('0');
      }
    });
  } // 显示或隐藏预览


  function handlePreview(visible) {
    // event
    var e = {
      target: inputTextRef.current,
      currentTarget: inputTextRef.current,
      visible: visible === false ? false : true
    }; // 预览类型

    if (readOnly) {
      e.type = 'preview';
    } else {
      e.type = 'choose';
    } // 预览回调


    var onPreview = null;

    if (typeof onPreviewRef.current === 'function') {
      onPreview = onPreviewRef.current;
    } // 隐藏预览回调


    if (visible === false) {
      onPreview(e);
      return;
    } // 预览


    if (value && value.longitude && value.latitude) {
      viewMapData = {
        point: [value.longitude, value.latitude],
        address: value.address
      };
      setViewMapVisible(true); // 增加历史记录

      _Bridge["default"].addHistoryBack(function () {
        handleClosePreview();
      }, routePath); // 预览回调


      if (onPreview) {
        onPreview(e, value);
      }
    } // 无法预览
    else {
        // 编辑状态下没有值先定位
        if (!readOnly) {
          handleLocation(e);
          return;
        } // 预览出错


        if (onPreview) {
          onPreview(e, {
            errMsg: "preview:fail" + (0, _locale["default"])('坐标不正确, 预览失败', 'hint_location_preview_fail')
          });
        }
      }
  } // 关闭h5预览


  function handleClosePreview() {
    // 已经返回, 路由却没变
    if (window.location.href.indexOf(routePath) !== -1) {
      window.history.go(-1);
      return;
    } // 隐藏预览


    setViewMapVisible(false); // 预览回调

    handlePreview(false);
  } // 地图选点


  function handleChoose(e, val, data) {
    handleClosePreview();
    var address = data && data.address ? data.address : '';
    data.value = address;
    data.errMsg = 'getLocation:ok';

    if (onChangeRef && onChangeRef.current) {
      onChangeRef.current({
        target: inputTextRef.current
      }, data);
    }
  } // 计算class, 防止重要class被覆盖


  var inputClassName = (others.inputAttribute || {}).className || '';
  var riconClassName = (others.riconAttribute || {}).className;

  if (riconClassName === undefined) {
    var _editConfig3;

    riconClassName = "input-location-icon size24 " + (((_editConfig3 = editConfig) === null || _editConfig3 === void 0 ? void 0 : _editConfig3.type) === 'choose' ? 'input-location-icon-choose' : 'input-location-icon-location');
  } // 加载和错误面板, 显示这些面板时将会隐藏文本框, 样式必须与文本框一致


  var statusDOM = null;

  if (status === '-1') {
    var _message;

    statusDOM = /*#__PURE__*/_react["default"].createElement("div", {
      className: "input-text " + inputClassName + " input-location",
      style: (others.inputAttribute || {}).style || {}
    }, ((_message = message) === null || _message === void 0 ? void 0 : _message.loading) || '');
  } else if (status === '0') {
    statusDOM = /*#__PURE__*/_react["default"].createElement("div", {
      className: "input-text " + inputClassName + " input-location-error",
      style: (others.inputAttribute || {}).style || {}
    }, message.failed);
  } // 文本是否允许修改


  var inputReadOnly = true;

  if (!readOnly && ((_editConfig4 = editConfig) === null || _editConfig4 === void 0 ? void 0 : _editConfig4.editable)) {
    inputReadOnly = false;
  } // 文本框是否允许清空


  var inputClear = false;

  if (!readOnly && ((_editConfig5 = editConfig) === null || _editConfig5 === void 0 ? void 0 : _editConfig5.clear)) {
    inputClear = true;
  }

  return /*#__PURE__*/_react["default"].createElement(_react.Fragment, null, /*#__PURE__*/_react["default"].createElement(_InputText["default"], _extends({
    ref: inputTextRef,
    readOnly: inputReadOnly,
    onClick: handleClick,
    onChange: onChange,
    children: statusDOM,
    value: value && typeof value === 'object' ? value.value || '' : value || '',
    clearReadOnly: inputClear
  }, others, {
    riconAttribute: readOnly ? null : Object.assign({}, others.riconAttribute, {
      className: "" + (status === '-1' ? riconClassName + ' input-location-icon-active' : riconClassName)
    }),
    inputAttribute: Object.assign({}, others.inputAttribute, {
      className: statusDOM ? 'hide-important input-location-success ' + inputClassName : 'input-location-success ' + inputClassName
    }) // 定位中和定位失败时隐藏text框, 显示定位中或者定位失败的div

  })), preview || ((_editConfig6 = editConfig) === null || _editConfig6 === void 0 ? void 0 : _editConfig6.type) === 'choose' ? /*#__PURE__*/_react["default"].createElement(_Map["default"] // 地图选择参数
  , {
    readOnly: readOnly,
    type: ((_editConfig7 = editConfig) === null || _editConfig7 === void 0 ? void 0 : _editConfig7.type) || '',
    onChange: handleChoose // 预览地图参数
    ,
    ak: ak,
    show: viewMapVisible,
    viewMapData: viewMapData,
    onHide: handleClosePreview,
    mapPageProps: mapPageProps
  }) : null);
});
var _default = InputLocation;
exports["default"] = _default;
module.exports = exports.default;