import { IconAirPlain } from "@/assets/icons";
import { useEditor } from "@/modules/editor";
import { defineComponent, onMounted, ref, watch } from "vue";
import { string } from "vue-types";
import { useCompData } from ".";
import { View } from "../View";
// import AMapLoader from "@amap/amap-jsapi-loader";

declare const AMap: any;

export const Component = defineComponent({
  props: {
    compId: string().isRequired,
  },
  setup(props) {
    const { controls, store } = useEditor();

    const mapContainerRef = ref();

    const comp = useCompData(props.compId);
    const { value } = comp;

    // const AMap = ref();
    const map = ref();
    const marker = ref();

    function initMap() {
      // AMapLoader.load({
      //   key: "389e81c4c61fd6dff4ab8f742af82e5f", // 申请好的Web端开发者Key，首次调用 load 时必填
      //   version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
      //   plugins: ["AMap.Scale", "AMap.ToolBar", "AMap.MouseTool"], // 需要使用的的插件列表，如比例尺'AMap.Scale'等
      //   Loca: {
      //     version: "2.0.0",
      //   },
      // })
      //   .then((res) => {
      // AMap.value = res;
      map.value = new AMap.Map(mapContainerRef.value, {
        // viewMode: "3D",
        zoom: 11,
        center: value.addressInfo.lnglat,
      });

      AMap.plugin(["AMap.ToolBar"], () => {
        marker.value = new AMap.Marker({
          position: value.addressInfo.lnglat,
        });
        map.value.add(marker.value);

        const toolbar = new AMap.ToolBar({ position: "LT" }); // 缩放工具条实例化
        map.value.addControl(toolbar);
      });
      // })
      // .catch((e: any) => {
      //   console.log("error", e);
      // });
    }

    function updateMap() {
      marker.value.setPosition(value.addressInfo.lnglat);
      map.value.add(marker.value);
      map.value.setZoomAndCenter(11, value.addressInfo.lnglat);
    }

    function openMap() {
      if (store.isEditMode) return;
      const options = {
        latitude: value.addressInfo.lnglat[1], // 纬度，浮点数，范围为90 ~ -90
        longitude: value.addressInfo.lnglat[0], // 经度，浮点数，范围为180 ~ -180。
        name: value.addressInfo.address, // 位置名
        address: value.addressInfo.address, // 地址详情说明
      };
      controls.wxCtrl.openMap(options);
    }

    watch(
      () => [value.addressInfo],
      () => updateMap()
    );

    onMounted(() => {
      initMap();
    });

    return () => (
      <View compId={props.compId}>
        <div
          ref={mapContainerRef}
          class="w-1/1"
          style={{
            height: "calc(100% - 44px)",
          }}
        ></div>
        <div
          class="absolute right-20px bottom-50px rounded-1/2 w-40px h-40px flex items-center justify-center bg-[#0085fe]"
          onClick={openMap}
        >
          <IconAirPlain class="text-20px" />
        </div>
        <div class="text-14px text-[#666] py-15px text-center bg-light-50">
          {value.addressInfo.address}
        </div>
      </View>
    );
  },
});
