import _regeneratorRuntime from 'babel-runtime/regenerator';

var _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; };

function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; }

function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }

import React, { forwardRef, useRef, useImperativeHandle, useContext, useState, useEffect, Fragment } from 'react';
import InputText from './../InputText';
import Bridge from './../Bridge';
import MapView from './../MapView';
import Context from '../Context/instance.js';

// 函数组件因为没有实例, 所以也没有ref, 必须通过forwardRef回调ref
var InputLocation = forwardRef(function (_ref, ref) {
  var loadingValue = _ref.loadingValue,
      failedValue = _ref.failedValue,
      readOnly = _ref.readOnly,
      autoLocation = _ref.autoLocation,
      onClick = _ref.onClick,
      onChange = _ref.onChange,
      _ref$preview = _ref.preview,
      preview = _ref$preview === undefined ? true : _ref$preview,
      selected = _ref.selected,
      others = _objectWithoutProperties(_ref, ['loadingValue', 'failedValue', 'readOnly', 'autoLocation', 'onClick', 'onChange', 'preview', 'selected']);

  var refEl = useRef(null);
  useImperativeHandle(ref, function () {
    return refEl.current;
  });

  var _useState = useState(false),
      mapShow = _useState[0],
      setMapShow = _useState[1];

  var _useState2 = useState(null),
      mapData = _useState2[0],
      setMapData = _useState2[1];

  var context = useContext(Context) || {};
  var locale = context.locale || {};
  if (!loadingValue || typeof loadingValue !== 'string') {
    loadingValue = locale['location'] || '定位中...';
  }
  if (!failedValue || typeof failedValue !== 'string') {
    failedValue = locale['hint_location_failed'] || '定位失败, 请检查定位权限是否开启';
  }

  useEffect(function () {
    if (autoLocation) {
      location({
        target: refEl.current,
        currentTarget: refEl.current
      });
    }
  }, []);

  var _useState3 = useState('1'),
      status = _useState3[0],
      setStatus = _useState3[1]; // 定位状态, 定位中和定位失败时隐藏text框, 显示定位中或者定位失败的div


  function click(event, value) {
    // 正在定位不允许操作
    if (status === '-1') {
      return;
    }
    // 触发点击事件
    var e = event.nativeEvent;
    if (onClick) {
      onClick(e, value);
    }
    // 只读状态不允许定位
    if (readOnly === true) {
      if (preview && selected && selected.longitude && selected.latitude) {
        // 预览
        setMapData({
          point: [selected.longitude, selected.latitude],
          address: selected.address,
          show: true
        });
        setMapShow(true);
      }
      return;
    }
    // 非只读状态下, 点击错误面板, 允许手动输入位置
    if (readOnly === false && status === '0') {
      setStatus('1');
      return;
    }
    // 如果非只读, 则仅允许点击图标定位
    if (readOnly === false && !e.target.classList.contains('input-location-icon')) {
      return;
    }
    // 定位
    location(e);
  }

  function location(e) {
    var _this = this;

    Bridge.debug = true;
    // 定位中...
    setStatus('-1');
    Bridge.getLocation({
      type: 'gcj02',
      success: function () {
        var _ref2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee(data) {
          var result, address;
          return _regeneratorRuntime.wrap(function _callee$(_context) {
            while (1) {
              switch (_context.prev = _context.next) {
                case 0:
                  if (!data.address) {
                    _context.next = 3;
                    break;
                  }

                  // 赋值
                  if (onChange) {
                    onChange(e, data.address, data);
                    setStatus('1');
                  }
                  return _context.abrupt('return');

                case 3:
                  _context.next = 5;
                  return Bridge.getAddress({ // 只支持gcj02
                    latitude: data.latitude,
                    longitude: data.longitude
                  });

                case 5:
                  result = _context.sent;
                  address = result && result.address ? result.address : '';

                  if (onChange) onChange(e, address, result);
                  if (address) {
                    setStatus('1');
                  } else {
                    setStatus('0');
                  }

                case 9:
                case 'end':
                  return _context.stop();
              }
            }
          }, _callee, _this);
        }));

        return function success(_x) {
          return _ref2.apply(this, arguments);
        };
      }(),
      fail: function fail(res) {
        // 赋值
        if (onChange) onChange(e, '', null);
        setStatus('0');
        // 提示定位失败
        // Bridge.showToast(res.errMsg, {mask: false});
      }
    });
  }

  // 计算class, 防止重要class被覆盖
  var inputClassName = (others.inputAttribute || {}).className || '';
  var riconClassName = (others.riconAttribute || {}).className;
  if (riconClassName === undefined) {
    riconClassName = 'input-location-icon size24';
  }
  // 加载和错误面板, 显示这些面板时将会隐藏文本框, 样式必须与文本框一致
  var statusDOM = null;
  if (status === '-1') {
    statusDOM = React.createElement(
      'div',
      { className: 'input-text ' + inputClassName + ' input-location', style: (others.inputAttribute || {}).style || {} },
      loadingValue
    );
  } else if (status === '0') {
    statusDOM = React.createElement(
      'div',
      { className: 'input-text ' + inputClassName + ' input-location-error', style: (others.inputAttribute || {}).style || {} },
      failedValue
    );
  }
  return React.createElement(
    Fragment,
    null,
    React.createElement(InputText, _extends({
      ref: refEl,
      readOnly: readOnly,
      onClick: click,
      onChange: onChange,
      children: statusDOM
    }, 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
    })),
    mapData && React.createElement(MapView, {
      ak: '3pTjiH1BXLjASHeBmWUuSF83',
      show: mapShow,
      header: mapData.address ? React.createElement(
        'div',
        { className: 'mapview-bar border-b' },
        mapData.address
      ) : null,
      points: [mapData.point],
      portal: context.portal || document.getElementById('root') || document.body,
      onHide: function onHide() {
        return setMapShow(false);
      }
    })
  );
});

export default InputLocation;