<template>
  <BasicModal
    v-bind="$attrs"
    @register="register"
    :title="t('layout.map.mapSelect')"
    @ok="handleSubmit"
    @cancel="handleCancel"
    :scaleControl="true"
    :width="828"
    :minHeight="500"
    @resize="handleRsize"
    destroyOnClose
    centered
  >
    <GoogleMap
      ref="mapRef"
      :api-key="googleKey"
      mapId="japan_4dkankan"
      :center="center"
      :map-type-control="false"
      :disable-default-ui="true"
      :language="lang"
      region="JP"
      :zoom="7"
      :minZoom="2"
      :scaleControl="true"
      :scaleControlOptions="{
        position: 22,
      }"
      map-type-id="roadmap"
      :mapTypeControlOptions="{
        style: 1,
        position: 3,
      }"
      style="width: 800px; height: 500px"
      @click="handleMapClick"
      v-loading="loadingRef"
      :loading-tip="t('common.loadingText')"
    >
      <CustomControl position="TOP_LEFT">
        <div class="p-20px">
          <a-input id="pac-input" allow-clear />
        </div>
      </CustomControl>

      <AdvancedMarker
        v-show="searchMarkerShow"
        ref="searchMarkerRef"
        :options="{
          position: searchMarker,
          title: searchMarkerTitle,
        }"
      />
    </GoogleMap>
    <div v-if="searchMarker.lng || searchMarker.lat">
      {{ t('layout.map.lat') }} {{ searchMarker.lat }}， {{ t('layout.map.lng') }}
      {{ searchMarker.lng }}</div
    >

    <template #centerFooter> </template>
  </BasicModal>
</template>
<script lang="ts">
  import { computed, defineComponent, onDeactivated, ref, unref, watch } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';

  import { useI18n } from '/@/hooks/web/useI18n';
  import {
    GoogleMap,
    AdvancedMarker,
    // MarkerCluster,
    // // InfoWindow,
    CustomControl,
  } from 'vue3-google-map';
  import { useLocaleStore } from '/@/store/modules/locale';

  const { t } = useI18n();

  const localeStore = useLocaleStore();
  export default defineComponent({
    components: { BasicModal, GoogleMap, CustomControl, AdvancedMarker },
    props: {
      open: Boolean,
      currentLatLng: {
        type: Object as PropType<{
          lat: number;
          lng: number;
        }>,
      },
    },
    emits: ['register', 'success', 'update'],
    setup(props, { emit }) {
      // const { createMessage } = useMessage();
      // const sceneNum = ref('');
      const location = ref('');
      const loadingRef = ref(true);
      const center = { lat: 35.717, lng: 139.731 };
      const mapRef = ref();
      const searchMarker = ref({ lat: 0, lng: 0 });
      const searchMarkerShow = ref(false);
      const searchMarkerTitle = ref('');
      const searchMarkerRef = ref();
      const isCanClick = ref(false);
      const googleKey = computed(() => import.meta.env.VITE_GOOGLE_KEY);

      const lang = computed(() => localeStore.getLocale);

      const [register, { closeModal }] = useModalInner((_) => {
        console.warn('useModalInner-entry');
        // resetMapview();
        // data && onDataReceive(data);
      });
      watch(
        () => [mapRef.value?.ready, props.currentLatLng],
        ([ready, currentLatLng]) => {
          if (!ready) return;
          console.log('ready', ready, unref(currentLatLng));

          loadingRef.value = false;
          const map = mapRef.value.map;
          if (map) {
            const defaultBounds = {
              north: center.lat + 0.1,
              south: center.lat - 0.1,
              east: center.lng + 0.1,
              west: center.lng - 0.1,
            };
            const input = document.getElementById('pac-input') as HTMLInputElement;
            const options = {
              bounds: defaultBounds,
              componentRestrictions: { country: ['jp'] },
              fields: ['address_components', 'geometry', 'icon', 'name'],
              strictBounds: false,
            };
            setTimeout(() => {
              // @ts-ignore
              const autocomplete = new google.maps.places.Autocomplete(input, options);
              // debugger;
              isCanClick.value = true;
              console.log('map', map);
              autocomplete.bindTo('bounds', map);
              autocomplete.addListener('place_changed', () => {
                const place = autocomplete.getPlace();
                if (!place.geometry || !place.geometry.location) {
                  // window.alert("No details available for input: '" + place.name + "'");
                  return;
                }

                // If the place has a geometry, then present it on a map.
                if (place.geometry.viewport) {
                  map.fitBounds(place.geometry.viewport);
                } else {
                  map.setCenter(place.geometry.location);
                  map.setZoom(17);
                }

                searchMarker.value.lat = place.geometry.location.lat();
                searchMarker.value.lng = place.geometry.location.lng();
                console.log('last-get', searchMarker.value);
                searchMarkerShow.value = true;
                if (unref(searchMarkerRef)) {
                  searchMarkerRef.value.marker.position = searchMarker.value;
                }
                const input = document.getElementById('pac-input') as HTMLInputElement;
                searchMarkerTitle.value = input.value;
              });
            }, 600);
          }
          if (currentLatLng?.lat && currentLatLng?.lng) {
            // debugger;
            console.warn('entry');
            setTimeout(() => {
              searchMarker.value.lat = Number(currentLatLng.lat);
              searchMarker.value.lng = Number(currentLatLng.lng);
              console.log('last-get', searchMarker.value);

              searchMarkerShow.value = true;
              if (searchMarkerRef.value) {
                searchMarkerRef.value.marker.position = searchMarker.value;
              }

              map.setCenter(searchMarker.value);
              map.setZoom(17);
            }, 800);
          } else {
            resetMapview();
          }
        },
        {
          deep: true,
        },
      );

      // function onDataReceive(data) {
      //   console.log('Data Received', data);
      //   data &&
      //     setFieldsValue({
      //       ...data,
      //     });

      //   // sceneNum.value = data.num;
      // }

      const resetMapview = () => {
        if (unref(searchMarkerRef).marker) {
          console.warn('resetMapview');
          searchMarkerRef.value.marker.position = { lat: 0, lng: 0 };
        }
        searchMarkerShow.value = false;
        searchMarker.value = { lat: 0, lng: 0 };
        mapRef.value?.map?.setCenter(center);
        mapRef.value?.map?.setZoom(7);
        const input = document.getElementById('pac-input') as HTMLInputElement;
        if (input) {
          input.value = '';
        }
      };
      const handleMapClick = async (event) => {
        if (!isCanClick.value) {
          return;
        }
        const { lat, lng } = event.latLng;
        searchMarker.value.lat = lat();
        searchMarker.value.lng = lng();
        console.log('searchMarkerRef', searchMarkerRef.value.marker.position);
        searchMarkerRef.value.marker.position = searchMarker.value;
        searchMarkerTitle.value = '';
      };
      const handleSubmit = async () => {
        if (searchMarker.value.lat || searchMarker.value.lng) {
          emit('update', searchMarker.value);
        }
        resetMapview();
        setTimeout(closeModal, 200);
      };
      const handleCancel = async () => {
        resetMapview();
      };
      const handleRsize = () => {
        console.log('handleRsize');
      };
      onDeactivated(() => {
        console.warn('onDeactivated');
      });
      return {
        t,
        register,
        handleSubmit,
        closeModal,
        location,
        handleMapClick,
        loadingRef,
        lang,
        mapRef,
        center,
        searchMarker,
        handleCancel,
        handleRsize,
        googleKey,
        searchMarkerRef,
        searchMarkerShow,
        searchMarkerTitle,
      };
    },
  });
</script>
<style lang="less" scoped>
  .map-select {
    display: flex;
    flex-direction: row;
    gap: 0 20px;
  }
</style>
