import _regeneratorRuntime from 'babel-runtime/regenerator';

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

import React, { forwardRef, useRef, useImperativeHandle, useContext, useState, useEffect } from 'react';
import { createPortal } from 'react-dom';
import MapUtil from './../MapUtil';
import Page from './../Page';
import Header from './../Header';
import Container from './../Container';
import Footer from './../Footer';
import Notice from './../Notice';
import Bridge from './../Bridge';
import Wrapper from './Wrapper';
import Close from './Close';
import Location from './Location';
import helper from './helper';
import Context from './../Context/instance.js';

var MapChoose = 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,
      point = _ref.point,
      header = _ref.header,
      children = _ref.children;

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

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

  var _useState2 = useState(''),
      address = _useState2[0],
      setAddress = _useState2[1];

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

  useEffect(function () {
    if (!window.BMap && !ak) {
      setErrMsg(locale('hint_map_ak') || '请传入百度地图ak');
      return;
    }
    MapUtil.load({
      ak: ak,
      success: function success() {
        initData();
      },
      fail: function fail() {
        setErrMsg(locale('hint_map_failed_load') || '地图库加载失败, 请稍后再试');
      }
    });
    // 移除组件时注销
    return function () {
      helper.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;
    }
    // 拖拽结束回调
    helper.onDragEnd = function (res) {
      address = res && res.address ? res.address : '';
      setAddress(address);
      setData(res);
    };
    // 初始化地图
    helper.initMap(refWrapperEl.current, center, function (result) {
      if (typeof result === 'string') {
        setErrMsg(result);
        return;
      }
      // 自动定位
      if (!point && autoLocation) {
        locationHandler();
      }
    });
  }

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

    Bridge.debug = true;
    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:
                  helper.initMarker([data.longitude, data.latitude]);
                  // 客户端中不需要再getAddress

                  if (!data.address) {
                    _context.next = 5;
                    break;
                  }

                  setAddress(address);
                  setData(data);
                  return _context.abrupt('return');

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

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

                  setAddress(address);
                  setData(result);

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

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

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

  // 绘制标记点
  useEffect(function () {
    if (point && point.length && show) {
      console.log('绘制标记');
      helper.initMarker(point);
    }
  }, [point]); // eslint-disable-line

  // 标题
  useEffect(function () {
    if (caption && show) {
      Bridge.setTitle(caption);
    }
  }, [caption]);

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

  var DOM = React.createElement(
    Page,
    { ref: refEl, className: show ? '' : 'hide' },
    header && React.createElement(
      Header,
      null,
      header
    ),
    React.createElement(
      Container,
      null,
      React.createElement(Wrapper, { ref: refWrapperEl }),
      onHide && React.createElement(Close, { onClick: onHide }),
      React.createElement(Location, { onClick: locationHandler }),
      children
    ),
    React.createElement(
      Footer,
      { className: 'map-footer' },
      React.createElement(
        'div',
        { className: 'map-footer-content' },
        React.createElement(
          'p',
          { className: 'map-footer-content-caption' },
          locale('current_location') || '当前位置'
        ),
        React.createElement(
          'p',
          { className: 'map-footer-content-sndcaption' },
          address || ' '
        )
      ),
      React.createElement(
        'span',
        { className: 'map-footer-submit', onClick: submitHandler },
        locale('ok') || '确定'
      )
    ),
    errMsg && React.createElement(Notice, { caption: errMsg })
  );
  if (portal) {
    return createPortal(DOM, portal);
  }
  return DOM;
});

export default MapChoose;