<template>
  <GoogleMap
    ref="mapRef"
    :center="center"
    :api-key="googleKey"
    mapId="japan_4dkankan"
    :map-type-control="true"
    :disable-default-ui="false"
    :fullscreenControl="false"
    :language="lang"
    region="JP"
    :zoom="7"
    :scaleControl="true"
    :scaleControlOptions="{
      position: 22,
    }"
    map-type-id="roadmap"
    :mapTypeControlOptions="{
      style: 1,
      position: 3,
    }"
    style="width: 100vw; height: 100vh"
    @click="handleMapClick"
    v-loading="loadingRef"
    :loading-tip="t('common.loadingText')"
  >
    <MarkerCluster>
      <template v-for="(location, i) in locations" :key="i">
        <CustomMarker
          v-if="location.isPro"
          :options="{
            position: { lat: location.lat, lng: location.lng },
            title: location.title,
            anchorPoint: 'TOP_CENTER',
          }"
          @click="handleMarkerClick(location)"
        >
          <div class="custom-marker">{{ location.title }}</div>
        </CustomMarker>
        <AdvancedMarker
          v-else
          :options="{
            position: { lat: location.lat, lng: location.lng },
            title: location.title,
          }"
          @click="handleMarkerClick(location)"
        />
      </template>
      <!-- <AdvancedMarker
        v-for="(location, i) in locations"
        :key="i"
        :options="{
          position: { lat: location.lat, lng: location.lng },
          title: location.title,
        }"
        @click="handleMarkerClick(location)"
      /> -->
    </MarkerCluster>

    <!-- <CustomControl position="TOP_LEFT">
      <div class="top_left_control">
        <div>
          <ApiSelect
            :api="projectFetch"
            size="large"
            numberToString
            resultField="list"
            labelField="title"
            valueField="id"
            optionFilterProp="label"
            v-model:value="form.projectValue"
            immediate
            show-search
            allow-clear
            v-if="form.type === 0"
            @select="handleSelect"
            style="width: 300px"
            :params="{
              type: 0,
              ciphertext: ciphertext,
              projectId: projectId,
              searchKey: form.searchValue,
            }"
          />
          <ApiSelect
            :api="sceneFetch"
            v-if="form.type === 1"
            size="large"
            resultField="list"
            labelField="title"
            valueField="num"
            optionFilterProp="label"
            immediate
            show-search
            allow-clear
            @select="handleSelect"
            style="width: 300px"
            :params="{ type: 1, searchKey: form.searchValue }"
          />
        </div>
        <div>
          <Select
            ref="select"
            v-model:value="form.type"
            style="width: 120px"
            size="large"
            @select="handleTypeSelect"
            :placeholder="t('common.chooseText')"
          >
            <SelectOption :value="0">全部项目</SelectOption>
            <SelectOption :value="1">全部场景</SelectOption>
          </Select>
        </div>
      </div>
    </CustomControl> -->
    <!-- 
    <CustomControl position="BOTTOM_CENTER">
      <div class="share-container" >
        <Popover trigger="click" v-model:open="shareOpen">
          <template #content>
            <div class="share-content">
              <p>扫码分享</p>
              <QrCode :value="qrCodeShareUrl" :width="250" :height="250" />
              <a-button text @click="handleCopy">复制链接</a-button>
            </div>
          </template>
          <a-button class="custom-btn" @click="handleShare">分享</a-button>
        </Popover>
      </div>
    </CustomControl> -->
  </GoogleMap>
</template>

<script lang="ts" setup>
  // import { SearchOutlined } from '@ant-design/icons-vue';
  import { ref, onMounted, watch, computed, watchEffect } from 'vue';
  import {
    GoogleMap,
    AdvancedMarker,
    MarkerCluster,
    CustomMarker,
    // InfoWindow,
    // CustomControl,
  } from 'vue3-google-map';
  import { useRouteQuery } from '@vueuse/router';

  const loadingRef = ref(true);
  import { useI18n } from '/@/hooks/web/useI18n';
  import { GetShareMapApi } from '/@/api/mapOpt/list';
  const { t } = useI18n();

  const googleKey = computed(() => import.meta.env.VITE_GOOGLE_KEY);
  const center = { lat: 35.717, lng: 139.731 };

  const lang = useRouteQuery('lang', '');

  const type = useRouteQuery('type', 0);
  const ciphertext = useRouteQuery('ciphertext');
  const form = ref<{
    searchValue: null | string;
    projectValue: null | string;
    sceneValue: null | string;
    type: number;
  }>({
    searchValue: '',
    projectValue: '',
    sceneValue: null,
    type: 0,
  });

  const mapRef = ref();
  const locations = ref<
    {
      lat: string;
      lng: string;
      title: string;
      webSite: string;
    }[]
  >([]);
  // locations.value = locations.value.concat(all);
  console.log('total', locations.value.length);

  watch(
    () => [mapRef.value?.ready, locations],
    ([ready, lo]) => {
      if (!ready) return;
      console.log('ready', ready, lo.value.length);
      loadingRef.value = false;
      if (ready && lo.value.length > 0) {
        // debugger;
        try {
          mapFitBounds(mapRef, locations.value);
        } catch (error) {}
      }
    },
    {
      deep: true,
    },
  );

  onMounted(async () => {
    watchEffect(async () => {
      if (lang.value) {
        if (lang.value === 'ja') {
          document.title = 'マップを共有';
        } else {
          document.title = '地图分享';
        }
      }
      if (type.value) {
        form.value.type = Number(type.value);
      }
      if (type.value && ciphertext.value) {
        await sceneFetch({
          type: type.value,
          ciphertext: ciphertext.value,
        });
      }
    });
  });

  function mapFitBounds(mapRef, markers) {
    let bounds;
    const api = mapRef.value.api;
    const map = mapRef.value.map;

    bounds = new api.LatLngBounds();
    for (let i = 0; i < markers.length; i++) {
      bounds.extend(markers[i]);
    }
    map.fitBounds(bounds);
    map.panToBounds(bounds);
  }
  const handleMapClick = (event) => {
    const { lat, lng } = event.latLng;
    console.log('event', `{ lat: ${lat()}, lng: ${lng()}}`);
  };

  const handleMarkerClick = (data) => {
    // const { lat, lng } = event.latLng;
    console.log('handleMarkerClick', data);
    data.webSite && window.open(data.webSite);
  };
  const getMarkerData = (data) => {
    if (Number(type.value) === 0) {
      const list = Array.from(data as any as any[])
        .reduce((p: string[], c: { sceneList: any[] }) => p.concat(c['sceneList']), [])
        .map((item) => {
          const mapper = {} as any;
          mapper.lat = Number(item.lat);
          mapper.lng = Number(item.lon);
          mapper.title = item.title;
          item.num && (mapper.num = item.num);
          item.id && (mapper.id = item.id);
          mapper.webSite = item.webSite;
          return mapper;
        });
      if (list.length === 0) {
        return data.map((item) => {
          const mapper = {} as any;
          mapper.isPro = true;
          mapper.lat = Number(item.lat);
          mapper.lng = Number(item.lon);
          mapper.title = item.title;
          mapper.webSite = item.webSite;
          return mapper;
        });
      } else {
        return list;
      }
    } else {
      return data.map((item) => {
        const mapper = {} as any;
        mapper.lat = Number(item.lat);
        mapper.lng = Number(item.lon);
        mapper.title = item.title;
        mapper.webSite = item.webSite;
        return mapper;
      });
    }
  };

  const sceneFetch = async (params) => {
    const res = await GetShareMapApi(params);
    const data = getMarkerData(res);
    console.log('sceneFetch-res', data.length);
    locations.value = data;
    return res;
  };
</script>
<style lang="less">
  // @import './dark.less';
  #map-container {
    width: 100vw;
    height: 100vh;
  }
  .top_left_control {
    padding: 20px;
    display: flex;
    flex-direction: row;
    gap: 25px;
  }
  .share-container {
    padding-bottom: 30px;
  }
  .custom-marker {
    background: rgba(0, 0, 0, 0.6);
    padding: 8px;
    border-radius: 10px;
    color: white;
    position: relative;
    &::before {
      content: ' ';
      top: 100%;
      left: 50%;
      transform: translateX(-50%);
      position: absolute;
      width: 0;
      height: 0;
      border-left: 5px solid transparent;
      border-right: 5px solid transparent;
      border-top: 5px solid rgba(0, 0, 0, 0.6);
    }
  }
  .share-content {
    min-width: 300px;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
  }
</style>
