<template>
  <GoogleMap
    ref="mapRef"
    :center="center"
    :api-key="googleKey"
    mapId="japan_4dkankan"
    :map-type-control="true"
    :disable-default-ui="false"
    :scaleControl="true"
    :scaleControlOptions="{
      position: 22,
    }"
    :language="lang"
    region="JP"
    :zoom="7"
    :minZoom="2"
    map-type-id="roadmap"
    :mapTypeControlOptions="{
      style: 1,
      position: 3,
    }"
    :fullscreenControl="false"
    style="width: 100vw; height: 100vh"
    v-loading="loadingRef"
    :loading-tip="t('common.loadingText')"
  >
    <!-- <template #default="{ ready }"> -->
    <!-- Third pattern: Here you have access to the API and map instance.
      "ready" is a boolean that indicates when the Google Maps script
      has been loaded and the api and map instance are ready to be used -->
    <MarkerCluster>
      <template v-for="location in realLocations" :key="location.num">
        <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>
        <template v-if="delayCluster">
          <AdvancedMarker
            v-if="!location.isPro && location.lat && location.lng"
            :options="{
              position: { lat: location.lat, lng: location.lng },
              title: location.title,
            }"
            @click="handleMarkerClick(location)"
          />
        </template>
      </template>
    </MarkerCluster>
    <CustomControl position="TOP_LEFT">
      <div class="top_left_control">
        <div>
          <template v-if="form.type === 0">
            <ApiSelect
              v-if="!projectId"
              :api="allProjectFetch"
              size="large"
              v-model:value="form.projectValue"
              numberToString
              resultField="list"
              labelField="title"
              valueField="id"
              optionFilterProp="label"
              immediate
              show-search
              allow-clear
              @select="handleAllProSelect"
              style="width: 300px"
              :placeholder="t('layout.map.keywords')"
              :params="{
                type: 0,
                searchKey: form.searchValue,
              }"
            />
            <!-- v-model:value="form.sceneValue" -->
            <ApiSelect
              v-else
              :api="projectFetch"
              size="large"
              numberToString
              resultField="list"
              labelField="title"
              valueField="num"
              optionFilterProp="label"
              immediate
              show-search
              allow-clear
              @select="handleProSelect"
              v-model:value="form.sceneValue"
              style="width: 300px"
              :placeholder="t('layout.map.keywords')"
              :params="{
                type: 0,
                projectId: projectId,
                searchKey: form.searchValue,
              }"
            />
          </template>

          <ApiSelect
            :api="sceneFetch"
            v-if="form.type === 1"
            size="large"
            resultField="list"
            labelField="title"
            valueField="num"
            optionFilterProp="label"
            v-model:value="form.sceneValue"
            immediate
            show-search
            :placeholder="t('layout.map.keywords')"
            allow-clear
            @select="handleSelect"
            style="width: 300px"
            :params="{ type: 1, searchKey: form.searchValue }"
          />
        </div>
        <div v-if="!projectId">
          <Select
            ref="select"
            v-model:value="form.type"
            style="width: 120px"
            size="large"
            @select="handleTypeSelect"
            :placeholder="t('common.chooseText')"
          >
            <SelectOption :value="0">{{ t('layout.map.allProject') }}</SelectOption>
            <SelectOption :value="1">{{ t('layout.map.allScene') }}</SelectOption>
          </Select>
        </div>
      </div>
    </CustomControl>

    <CustomControl position="BOTTOM_CENTER">
      <div class="share-container">
        <Popover trigger="click" v-model:open="shareOpen" class="pop">
          <template #content>
            <div class="share-content">
              <p>{{ t('layout.map.scanShare') }}</p>
              <QrCode :value="qrCodeShareUrl" :width="250" :height="250" />
              <a-button type="link" class="btn" @click="handleCopy">{{
                t('layout.map.copy')
              }}</a-button>
            </div>
          </template>
          <!-- <a-button type="primary">Hover me</a-button> -->
          <div class="custom-btn" @click="handleShare">
            <img :src="shareImage" />
            <span>{{ t('layout.map.share') }}</span>
          </div>
        </Popover>
      </div>
    </CustomControl>
    <!-- </template> -->
  </GoogleMap>
</template>

<script lang="ts" setup>
  // import { SearchOutlined } from '@ant-design/icons-vue';
  import { ref, onMounted, watch, computed, watchEffect, h } from 'vue';
  import {
    GoogleMap,
    AdvancedMarker,
    MarkerCluster,
    CustomMarker,
    // InfoWindow,
    CustomControl,
  } from 'vue3-google-map';
  import { useRouteQuery } from '@vueuse/router';
  import { Select, SelectOption, Popover } from 'ant-design-vue';
  import ApiSelect from '/@/components/Form/src/components/ApiSelect.vue';
  import { useRouter } from 'vue-router';
  const loadingRef = ref(true);
  import { useI18n } from '/@/hooks/web/useI18n';
  import { AllGpsApi, CreateShareMapApi } from '/@/api/mapOpt/list';
  import { QrCode } from '/@/components/Qrcode/index';
  import { useCopyToClipboard } from '/@/hooks/web/useCopyToClipboard';
  import { useMessage } from '/@/hooks/web/useMessage';
  import shareImage from '/@/assets/images/share.png';
  import Ping from 'ping.js';
  // import { useAppStore } from '/@/store/modules/app';

  // const { setPageLoading } = useAppStore();
  // setPageLoading(false);
  const { t } = useI18n();
  const router = useRouter();
  import { useLocaleStore } from '/@/store/modules/locale';
  const googleKey = computed(() => import.meta.env.VITE_GOOGLE_KEY);
  const center = { lat: 35.717, lng: 139.731 };
  const { createMessage, createConfirm } = useMessage();
  // const options = ref([]);
  // const pinOptions = { background: '#FBBC04' };
  const shareOpen = ref(false);
  const qrCodeShareUrl = ref('');
  const { clipboardRef, isSuccessRef } = useCopyToClipboard(qrCodeShareUrl.value);
  const localeStore = useLocaleStore();
  const isJA = computed(() => localeStore.getLocale === 'ja');
  const lang = useRouteQuery('lang', isJA.value ? 'ja' : 'zh');
  const projectId = useRouteQuery('projectId');
  const allProjectData = ref<any[]>([]);
  const allSceneData = ref<any[]>([]);
  let deylayTimer;
  const type = useRouteQuery('type', 0);
  const form = ref<{
    searchValue: undefined | string;
    projectValue: undefined | string;
    sceneValue: null | string;
    type: number;
  }>({
    searchValue: undefined,
    projectValue: undefined,
    sceneValue: null,
    type: 0,
  });

  const mapRef = ref();
  const delayCluster = ref(false);
  const locations = ref<
    {
      lat: string;
      lng: string;
      title: string;
      webSite: string;
      num?: string;
      id?: number;
    }[]
  >([]);
  const realLocations = ref<
    {
      lat: string;
      lng: string;
      title: string;
      webSite: string;
      num?: string;
      id?: number;
    }[]
  >([]);
  // 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 (lo.value.length > 0) {
        deylayTimer && clearTimeout(deylayTimer);
        deylayTimer = setTimeout(() => {
          realLocations.value = locations.value;
          console.warn('delayCluster');
          delayCluster.value = true;
          mapFitBounds(mapRef, locations.value);
        }, 600);
      } else {
        // locations.value = [];
        realLocations.value = [];
        setDefaultCenter();
      }
    },
    {
      deep: true,
      immediate: true,
    },
  );

  onMounted(async () => {
    var p = new Ping();
    p.ping('http://google.com', function (err, _) {
      // Also display error if err is returned.
      if (err) {
        console.error('error loading resource');
        createConfirm({
          iconType: 'warning',
          title: () => h('span', t('sys.app.logoutTip')),
          content: () => h('span', t('layout.map.mapOfflineService')),
          onOk: async () => {},
        });
        // data = data + ' ' + err;
      }
      // document.getElementById('ping-google').innerHTML = data;
    });

    watchEffect(() => {
      console.log(projectId.value);
      if (projectId.value) {
        form.value.projectValue = String(projectId.value);
      }
      if (type.value) {
        form.value.type = Number(type.value);
      }
    });
  });

  function reloadWithParams() {
    console.log('reloadWithParams');
    const routeData = router.resolve({ name: 'Map', query: { type: form.value.type } });
    location.replace(routeData.href);
    location.reload();
  }

  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 handleSelect = (num: any) => {
    const select = allSceneData.value.find((item) => item?.num === num);
    if (select) {
      console.log('handleSelect', num);
      // const selectMarker = getMarkerData([select]);
      locations.value = [select];
      const { lat, lng } = select;
      setCenter(Number(lat), Number(lng));
    }
  };
  const handleAllProSelect = (id: any) => {
    const select = allProjectData.value.find((item) => {
      return item?.id === Number(id);
    });
    if (select) {
      // const { lat, lng } = select;
      createMessage.destroy();
      console.log('handleProSelect', select);
      if (select?.sceneList.length > 0) {
        const selectMarker = getMarkerData(select?.sceneList);
        console.log('handleProSelect', select?.sceneList, selectMarker);
        locations.value = getMarkerData(select?.sceneList);
      } else {
        locations.value = [];
        setDefaultCenter();
        createMessage.open({
          type: 'warning',
          content: t('layout.map.searchEmptyProjectTip'),
          duration: 2000,
          style: {
            marginTop: '10vh',
          },
        });
        setTimeout(createMessage.destroy, 2000);
      }
    }
  };
  const handleProSelect = (num: string) => {
    const select = allProjectData.value.find((item) => {
      return item?.num === num;
    });
    form.value.sceneValue = num;
    if (select) {
      // const { lat, lng } = select;
      createMessage.destroy();
      locations.value = [select];
      const { lat, lng } = select;
      setCenter(Number(lat), Number(lng));
    }
  };

  const setCenter = (lat: number, lng: number, zoom = 14) => {
    if (mapRef.value) {
      // debugger;
      // console.log('mapRef.value', mapRef.value);
      mapRef.value.map?.setCenter({ lat, lng });
      mapRef.value.map?.setZoom(zoom);
    }
  };

  const setDefaultCenter = () => {
    if (mapRef.value) {
      // debugger;
      // console.log('mapRef.value', mapRef.value);
      mapRef.value.map?.setCenter(center);
      mapRef.value.map?.setZoom(7);
    }
  };

  const handleShare = async () => {
    // createMessage.warning(`测试提示：当前分享类型:${form.value.type}`);
    console.log('from', form.value);
    const res = await CreateShareMapApi(
      form.value.type,
      form.value.projectValue,
      form.value.sceneValue,
    );

    const lang = isJA.value ? 'ja' : 'zh-CN';
    const routeData = router.resolve({
      name: 'MapShare',
      query: { ciphertext: res.ciphertext, type: form.value.type, lang: lang },
    });
    const url = location.protocol + '//' + location.hostname + '/' + routeData.href;

    qrCodeShareUrl.value = url;
    console.log(`分享后LINK--${form.value.type}`, qrCodeShareUrl.value);
  };
  const getProjectMarkerData = (data) => {
    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 = item.lat ? Number(item.lat) : null;
        mapper.lng = item.lon ? Number(item.lon) : null;
        mapper.title = item.title;
        item.num && (mapper.num = item.num);
        item.id && (mapper.id = item.id);
        mapper.webSite = item.webSite;
        return mapper;
      });
    console.log('list', list);
    // if (list.length === 0) {
    //   const project = getMarkerData(data);
    //   project.forEach((pro: any) => {
    //     pro.isPro = true;
    //   });
    //   console.log('project', project);
    //   return project;
    // } else {
    //   return list;
    // }
    return list;
  };
  const getMarkerData = (data) => {
    return data.map((item) => {
      const mapper = {} as any;
      mapper.lat = item.lat ? Number(item.lat) : null;
      mapper.lng = item.lon ? Number(item.lon) : null;
      mapper.title = item.title;
      item.num && (mapper.num = item.num);
      item.id && (mapper.id = item.id);
      mapper.webSite = item.webSite;
      return mapper;
    });
  };
  const allProjectFetch = async (params) => {
    const res = await AllGpsApi(params);
    allProjectData.value = res;
    return res;
  };
  const projectFetch = async (params) => {
    const res = await AllGpsApi(params);
    const data = getProjectMarkerData(res);
    if (!form.value.sceneValue) {
      console.log('项目的marker', data.length);
      locations.value = data;
      allProjectData.value = data;
    }
    return data;
  };
  const sceneFetch = async (params) => {
    const res = await AllGpsApi(params);
    const data = getMarkerData(res);
    allSceneData.value = data;

    if (!form.value.sceneValue) {
      // search 和 地图模式下
      createMessage.destroy();
      console.log('sceneFetch', data.length);
      locations.value = data;
    }
    return res;
  };

  const handleTypeSelect = () => {
    reloadWithParams();
  };

  const handleCopy = () => {
    clipboardRef.value = qrCodeShareUrl.value;
    if (isSuccessRef.value) {
      createMessage.success(t('routes.scenes.copyInfi.ok'));
    }
  };
</script>
<style lang="less" scoped>
  // @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;
    color: white;
    .btn {
      color: rgba(0, 200, 175, 1);
    }
  }
  .custom-btn {
    width: 80px;
    height: 80px;
    background: rgba(26, 26, 26, 0.8);
    border-radius: 50%;
    color: white;
    display: flex;
    flex-direction: column;
    justify-content: center;
    gap: 5px 0;
    align-items: center;
    cursor: pointer;
  }
  :global(.ant-popover-inner) {
    background: rgba(26, 26, 26, 0.8);
  }
  :global(.ant-popover-arrow-content) {
    background: rgba(26, 26, 26, 0.8);
  }
</style>
