'use strict';

exports.__esModule = true;

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

var _regenerator2 = _interopRequireDefault(_regenerator);

var _react = require('react');

var _react2 = _interopRequireDefault(_react);

var _reactDom = require('react-dom');

var _MapUtil = require('./../MapUtil');

var _MapUtil2 = _interopRequireDefault(_MapUtil);

var _Page = require('./../Page');

var _Page2 = _interopRequireDefault(_Page);

var _Header = require('./../Header');

var _Header2 = _interopRequireDefault(_Header);

var _Container = require('./../Container');

var _Container2 = _interopRequireDefault(_Container);

var _Footer = require('./../Footer');

var _Footer2 = _interopRequireDefault(_Footer);

var _Notice = require('./../Notice');

var _Notice2 = _interopRequireDefault(_Notice);

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

var _Bridge2 = _interopRequireDefault(_Bridge);

var _Wrapper = require('./Wrapper');

var _Wrapper2 = _interopRequireDefault(_Wrapper);

var _Close = require('./Close');

var _Close2 = _interopRequireDefault(_Close);

var _Location = require('./Location');

var _Location2 = _interopRequireDefault(_Location);

var _helper = require('./helper');

var _helper2 = _interopRequireDefault(_helper);

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

var MapChoose = (0, _react.forwardRef)(function (_ref, ref) {
  var ak = _ref.ak,
      _ref$show = _ref.show,
      show = _ref$show === undefined ? true : _ref$show,
      portal = _ref.portal,
      caption = _ref.caption,
      autoLocation = _ref.autoLocation,
      onHide = _ref.onHide,
      onChange = _ref.onChange,
      _ref$center = _ref.center,
      center = _ref$center === undefined ? '江苏省,南京市' : _ref$center,
      address = _ref.address,
      point = _ref.point,
      header = _ref.header,
      children = _ref.children;

  // 创建ref, useRef每次都会返回相同的引用, 所以用createRef
  var refEl = (0, _react.useRef)(null);
  var refWrapperEl = (0, _react.useRef)(null);
  (0, _react.useImperativeHandle)(ref, function () {
    return refEl.current;
  });
  // context
  var context = (0, _react.useContext)(_instance2.default) || {};
  var locale = context.locale || function (key) {
    return key || '';
  };

  var _useState = (0, _react.useState)(''),
      errMsg = _useState[0],
      setErrMsg = _useState[1];

  var _useState2 = (0, _react.useState)(address || ''),
      addr = _useState2[0],
      setAddr = _useState2[1];

  var _useState3 = (0, _react.useState)(null),
      data = _useState3[0],
      setData = _useState3[1];

  (0, _react.useEffect)(function () {
    if (!window.BMap && !ak) {
      setErrMsg(locale('请传入百度地图ak', 'hint_map_ak'));
      return;
    }
    _MapUtil2.default.load({
      ak: ak,
      success: function success() {
        initData();
      },
      fail: function fail() {
        setErrMsg(locale('地图库加载失败, 请稍后再试', 'hint_map_failed_load'));
      }
    });
    // 移除组件时注销
    return function () {
      _helper2.default.destroy();
    };
  }, []); // eslint-disable-line

  // 隐藏时, 移除标注
  // useEffect(() => {
  //   if (show === false) {
  //     helper.destroy();
  //   }
  // }, [show])

  // 初始化地图
  function initData() {
    if (!window.BMap) {
      // 如果有高德地图, 则加上 || !window.AMap
      setErrMsg(locale('地图库加载失败, 请稍后再试', 'hint_map_failed_load'));
      return;
    }
    console.log('初始化地图' + center);
    if (!refWrapperEl.current) {
      setErrMsg(locale('地图容器不存在', 'hint_map_no_container'));
      return;
    }
    // 拖拽结束回调
    _helper2.default.onDragEnd = function (res) {
      addr = res && res.address ? res.address : '';
      setAddr(addr);
      setData(res);
    };
    // 初始化地图
    _helper2.default.initMap(refWrapperEl.current, center, function (result) {
      if (typeof result === 'string') {
        setErrMsg(result);
        return;
      }
      // 自动定位
      if (!point && autoLocation) {
        locationHandler();
      }
    });
  }

  // 立即定位
  function locationHandler() {
    var _this = this;

    _Bridge2.default.debug = true;
    _Bridge2.default.getLocation({
      type: 'gcj02',
      success: function () {
        var _ref2 = _asyncToGenerator( /*#__PURE__*/_regenerator2.default.mark(function _callee(data) {
          return _regenerator2.default.wrap(function _callee$(_context) {
            while (1) {
              switch (_context.prev = _context.next) {
                case 0:
                  if (!data.address) {
                    _context.next = 5;
                    break;
                  }

                  _helper2.default.drawMarker([data.longitude, data.latitude]);
                  setAddr(addr);
                  setData(data);
                  return _context.abrupt('return');

                case 5:
                  // 其它平台, 绘制标记后地址逆向解析, 并回调self.onDragEnd
                  _helper2.default.initMarker([data.longitude, data.latitude], function (result) {
                    addr = result && result.address ? result.address : '';
                    setAddr(addr);
                    setData(result);
                  });

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

        return function success(_x) {
          return _ref2.apply(this, arguments);
        };
      }(),
      fail: function fail(res) {
        _Bridge2.default.showToast(res.errMsg, { mask: false });
      }
    });
  }

  // 提交
  function submitHandler() {
    if (onChange) {
      onChange({ target: refEl.current }, addr, data);
    }
  }

  // 绘制标记点
  (0, _react.useEffect)(function () {
    if (point && point.length === 2 && show) {
      if (!address) {
        console.log('初始化标记');
        _helper2.default.initMarker(point, function (result) {
          addr = result && result.address ? result.address : '';
          setAddr(addr);
          setData(result);
        });
      } else {
        console.log('更新标记');
        _helper2.default.drawMarker(point);
      }
    }
  }, [point]); // eslint-disable-line

  // 更新地址
  (0, _react.useEffect)(function () {
    setAddr(address);
  }, [address]); // eslint-disable-line

  // 标题
  (0, _react.useEffect)(function () {
    if (caption && show) {
      _Bridge2.default.setTitle(caption);
    }
  }, [caption]);

  // 中断绘制
  (0, _react.useEffect)(function () {
    if (show) {
      if (errMsg) {
        _helper2.default.abort = true;
      } else {
        _helper2.default.abort = false;
      }
    }
  }, [errMsg]);

  var DOM = _react2.default.createElement(
    _Page2.default,
    { ref: refEl, className: show ? '' : 'hide' },
    header && _react2.default.createElement(
      _Header2.default,
      null,
      header
    ),
    _react2.default.createElement(
      _Container2.default,
      null,
      _react2.default.createElement(_Wrapper2.default, { ref: refWrapperEl }),
      onHide && _react2.default.createElement(_Close2.default, { onClick: onHide }),
      _react2.default.createElement(_Location2.default, { onClick: locationHandler }),
      children
    ),
    _react2.default.createElement(
      _Footer2.default,
      { className: 'map-footer' },
      _react2.default.createElement(
        'div',
        { className: 'map-footer-content' },
        _react2.default.createElement(
          'p',
          { className: 'map-footer-content-caption' },
          locale('当前位置', 'current_location')
        ),
        _react2.default.createElement(
          'p',
          { className: 'map-footer-content-sndcaption' },
          addr
        )
      ),
      addr && _react2.default.createElement(
        'span',
        { className: 'map-footer-submit', onClick: submitHandler },
        locale('确定', 'ok')
      )
    ),
    errMsg && _react2.default.createElement(_Notice2.default, { caption: errMsg })
  );
  if (portal) {
    return (0, _reactDom.createPortal)(DOM, portal);
  }
  return DOM;
});

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