'use strict';

exports.__esModule = true;

var _regenerator = require('babel-runtime/regenerator');

var _regenerator2 = _interopRequireDefault(_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; };

var _react = require('react');

var _react2 = _interopRequireDefault(_react);

var _InputText = require('./../InputText');

var _InputText2 = _interopRequireDefault(_InputText);

var _Bridge = require('./../Bridge');

var _Bridge2 = _interopRequireDefault(_Bridge);

var _instance = require('../Context/instance.js');

var _instance2 = _interopRequireDefault(_instance);

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

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

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

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

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


  function click(event, value) {
    var _this = this;

    // 正在定位不允许操作
    if (status === '-1') {
      return;
    }
    // 非只读状态下, 点击错误面板, 允许手动输入位置
    if (!readOnly && status === '0') {
      setStatus('1');
      return;
    }

    var e = event.nativeEvent;
    if (onClick) onClick(e, value);
    // 如果非只读, 则仅允许点击图标定位
    if (!readOnly && !e.target.classList.contains('input-location-icon')) {
      return;
    }
    // 定位中...
    setStatus('-1');
    _Bridge2.default.getLocation({
      type: 'gcj02',
      success: function () {
        var _ref2 = _asyncToGenerator( /*#__PURE__*/_regenerator2.default.mark(function _callee(data) {
          var result, address;
          return _regenerator2.default.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 _Bridge2.default.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) {
    riconClassName = 'input-location-icon size24';
  }
  // 加载和错误面板, 显示这些面板时将会隐藏文本框, 样式必须与文本框一致
  var statusDOM = null;
  if (status === '-1') {
    statusDOM = _react2.default.createElement(
      'div',
      { className: 'input-text ' + inputClassName + ' input-location', style: (others.inputAttribute || {}).style || {} },
      loadingValue
    );
  } else if (status === '0') {
    statusDOM = _react2.default.createElement(
      'div',
      { className: 'input-text ' + inputClassName + ' input-location-error', style: (others.inputAttribute || {}).style || {} },
      failedValue
    );
  }
  return _react2.default.createElement(_InputText2.default, _extends({
    ref: ref,
    readOnly: readOnly,
    onClick: click,
    onChange: onChange,
    children: statusDOM
  }, others, {
    riconAttribute: Object.assign({}, others.riconAttribute, { className: '' + (status === '-1' ? riconClassName + ' input-location-icon-active' : riconClassName) }),
    inputAttribute: Object.assign({}, others.inputAttribute, { className: statusDOM ? 'hide-important ' + inputClassName : inputClassName }) // 定位中和定位失败时隐藏text框, 显示定位中或者定位失败的div
  }));
});

exports.default = InputLocation;
module.exports = exports['default'];