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,
      address = _ref.address,
      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 || ''),
      addr = _useState2[0],
      setAddr = _useState2[1];

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

  useEffect(function () {
    if (!window.BMap && !ak) {
      setErrMsg(locale('请传入百度地图ak', 'hint_map_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) {
      addr = res && res.address ? res.address : '';
      setAddr(addr);
      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) {
          return _regeneratorRuntime.wrap(function _callee$(_context) {
            while (1) {
              switch (_context.prev = _context.next) {
                case 0:
                  if (!data.address) {
                    _context.next = 5;
                    break;
                  }

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

                case 5:
                  // 其它平台, 绘制标记后地址逆向解析, 并回调self.onDragEnd
                  helper.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) {
        Bridge.showToast(res.errMsg, { mask: false });
      }
    });
  }

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

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

  // 更新地址
  useEffect(function () {
    setAddr(address);
  }, [address]); // 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' },
          addr
        )
      ),
      addr && 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;