import React, { useEffect, useMemo } from "react";
import Taro from "@tarojs/taro";
import { View, Map } from "@tarojs/components";
import { Icon, Loading } from "@antmjs/vantui";
import { getLocation, h5GetLocation } from "@/utils/authorize";
import iconPath from "@/assets/icons/marker.png";
import style from "./style.module.less";

/**
 * 这里使用2个map, 每个 map 负责不同的场景
 * 如果使用 1 个map, 通过属性去控制, 微信暂时有 bug 比如 showLocation 就有bug
 */
export default (props) => {
  const { readOnly, location, onChange } = props;

  console.log("-----map---readOnly---", readOnly, location);

  // const id = React.useMemo(
  //   () => `map-${Math.random().toString(36).substring(2, 10)}`,
  //   []
  // );
  // const idReadOnly = React.useMemo(
  //   () => `map-${Math.random().toString(36).substring(2, 10)}`,
  //   []
  // );
  const mapCtxRef = React.useRef();

  useEffect(() => {
    let map, marker;
    if (!mapCtxRef.current) {
      if (location) {
        console.log(location);
        console.log(DEFAULT_POS);
        const [lng, lat] = (location || DEFAULT_POS).split(",");
        console.log(lng, lat)
        const center = new TMap.LatLng(parseFloat(lat), parseFloat(lng));
        map = new TMap.Map("container", {
          rotation: 20, //设置地图旋转角度
          pitch: 30, //设置俯仰角度（0~45）
          zoom: 20, //设置地图缩放级别
          center: center, //设置地图中心点坐标
        });

        const isRemove = [
          {
            id: "demo",
            styleId: "marker",
            position: center,
            properties: {
              title: "marker",
            },
          },
        ];
        marker = new TMap.MultiMarker({
          id: "marker-layer",
          map: map,
          geometries: isRemove,
        });
      }

      mapCtxRef.current = map;
    } else {
      map = mapCtxRef.current;
    }

    if (map && marker) {
      console.log("-------------------------");
      console.log(marker);
      console.log(map);
      getMarker(map, marker);
    }
  }, [location]);

  const getMarker = (map, marker) => {
    if (readOnly) return;

    map.on("click", (evt) => {
      marker.setGeometries([
        {
          position: evt.latLng,
        },
      ]);
      const { lng, lat } = evt.latLng;
      onChange([lng, lat].join(","));
    });
  };

  const fixedLocation = () => {
    return new Promise((resolve) => {
      Taro.showLoading({
        title: "加载中",
      });
      return h5GetLocation()
        .then((res) => {
          Taro.hideLoading();
          resolve(res.data.result);
        })
        .catch((err) => {
          console.error(err);
          Taro.hideLoading();
          Taro.showToast({
            title: "定位失败",
            icon: "none",
          });
        });
    });
  };

  React.useEffect(() => {
    if (!readOnly) {
      // getContext();

      // 获取定位
      fixedLocation().then((res) => {
        const { lng, lat } = res.location;
        onChange([lng, lat].join(","));
      });
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [readOnly]); //getContext

  return <div id="container"></div>;
};
