import _regeneratorRuntime from "@babel/runtime/regenerator";
var _excluded = ["ak", "show", "portal", "caption", "prevCaption", "autoLocation", "onHide", "onChange", "center", "address", "point", "header", "children"];

function _extends() { _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; }; return _extends.apply(this, arguments); }

function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }

function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }

function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }

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 MapInstance from './MapInstance';
import Context from './../Context/instance.js';
var MapChoose = forwardRef(function (_ref, ref) {
  var ak = _ref.ak,
      _ref$show = _ref.show,
      show = _ref$show === void 0 ? true : _ref$show,
      portal = _ref.portal,
      caption = _ref.caption,
      prevCaption = _ref.prevCaption,
      autoLocation = _ref.autoLocation,
      onHide = _ref.onHide,
      onChange = _ref.onChange,
      _ref$center = _ref.center,
      center = _ref$center === void 0 ? '江苏省,南京市' : _ref$center,
      address = _ref.address,
      point = _ref.point,
      header = _ref.header,
      children = _ref.children,
      others = _objectWithoutPropertiesLoose(_ref, _excluded);

  var _useState = useState(null),
      mapInstance = _useState[0],
      setMapInstance = _useState[1]; // 创建ref, useRef每次都会返回相同的引用, 所以用createRef


  var rootRef = useRef(null);
  var wrapperRef = useRef(null);
  useImperativeHandle(ref, function () {
    return rootRef.current;
  }); // context

  var context = useContext(Context) || {};

  var locale = context.locale || function (remark) {
    return remark || '';
  };

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

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

  var _useState4 = useState(null),
      data = _useState4[0],
      setData = _useState4[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 () {
      // 设置上一页标题
      handleTitle(prevCaption); // 移除实例化对象

      mapInstance.destroy();
    };
  }, []); // eslint-disable-line
  // 隐藏时, 移除标注
  // useEffect(() => {
  //   if (show === false) {
  //     mapInstance.destroy();
  //   }
  // }, [show])
  // 初始化地图

  function initData() {
    if (!window.BMap) {
      // 如果有高德地图, 则加上 || !window.AMap
      setErrMsg(locale('地图库加载失败, 请稍后再试', 'hint_map_failed_load'));
      return;
    }

    console.log('初始化地图' + center);

    if (!wrapperRef.current) {
      setErrMsg(locale('地图容器不存在', 'hint_map_no_container'));
      return;
    }

    mapInstance = new MapInstance();
    setMapInstance(mapInstance); // 拖拽结束回调

    mapInstance.onDragEnd = function (res) {
      if (res) {
        addr = res && res.address ? res.address : '';
        setAddr(addr);
        setData(res);
      } else {
        Bridge.showToast(locale('获取地址失败, 请稍后重试', 'hint_address_failed'), {
          mask: false
        });
      }
    }; // 初始化地图


    mapInstance.initMap(wrapperRef.current, center, function (result) {
      if (typeof result === 'string') {
        setErrMsg(result);
        return;
      } // 自动定位


      if (!point && autoLocation) {
        handleLocation();
      }
    });
  } // 立即定位


  function handleLocation() {
    Bridge.getLocation({
      type: 'gcj02',
      success: function () {
        var _success = _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;
                  }

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

                case 5:
                  // 其它平台, 绘制标记后地址逆向解析, 并回调self.onDragEnd
                  mapInstance.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);
        }));

        function success(_x) {
          return _success.apply(this, arguments);
        }

        return success;
      }(),
      fail: function fail(res) {
        Bridge.showToast(res.errMsg, {
          mask: false
        });
      }
    });
  } // 提交


  function handleSubmit() {
    if (onChange) {
      if (data && data.point && data.point.length === 2) {
        data.longitude = data.point[0];
        data.latitude = data.point[1];
      }

      onChange({
        target: rootRef.current
      }, addr, data);
    }
  } // 绘制标记点


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

  useEffect(function () {
    setAddr(address);
  }, [address]); // eslint-disable-line
  // 显隐

  useEffect(function () {
    if (show) {
      handleTitle(caption);
    } else {
      handleTitle(prevCaption);
    }
  }, [show]); // 中断绘制

  useEffect(function () {
    if (show && mapInstance) {
      if (errMsg) {
        mapInstance.abort = true;
      } else {
        mapInstance.abort = false;
      }
    }
  }, [errMsg]); // 设置标题

  function handleTitle(title) {
    if (!title) return;

    if (typeof title === 'string') {
      Bridge.setTitle({
        title: title
      });
    } else if (typeof title === 'function') {
      title();
    }
  }

  var DOM = /*#__PURE__*/React.createElement(Page, _extends({
    ref: rootRef
  }, others, {
    className: (show ? '' : 'hide') + ((others === null || others === void 0 ? void 0 : others.className) ? ' ' + others.className : '')
  }), header && /*#__PURE__*/React.createElement(Header, null, header), /*#__PURE__*/React.createElement(Container, null, /*#__PURE__*/React.createElement(Wrapper, {
    ref: wrapperRef
  }), onHide && /*#__PURE__*/React.createElement(Close, {
    onClick: onHide
  }), /*#__PURE__*/React.createElement(Location, {
    onClick: handleLocation
  }), children), /*#__PURE__*/React.createElement(Footer, {
    className: "map-footer"
  }, /*#__PURE__*/React.createElement("div", {
    className: "map-footer-content"
  }, /*#__PURE__*/React.createElement("p", {
    className: "map-footer-content-caption"
  }, locale('当前位置', 'current_location')), /*#__PURE__*/React.createElement("p", {
    className: "map-footer-content-sndcaption"
  }, addr)), addr && /*#__PURE__*/React.createElement("span", {
    className: "map-footer-submit",
    onClick: handleSubmit
  }, locale('确定', 'ok'))), errMsg && /*#__PURE__*/React.createElement(Notice, {
    caption: errMsg
  }));

  if (portal) {
    return createPortal(DOM, portal);
  }

  return DOM;
});
export default MapChoose;