<template>
  <z-paging>
    <template #top>
      <navbar/>
      <view class="bg-white px-30rpx py-26rpx">
        <view class="flex items-center h-86rpx px-28rpx bg-#F6F7F9 rounded-20rpx">
          <wd-input v-model="mapSearchKeyword" :no-border="true" :placeholder="t('common.placeholder.pleaseEnter')"
                    custom-class="!w-full !bg-transparent" placeholder-class="text-#9B9CA0 text-28rpx">
            <template #prefix>
              <view class="w-12rpx h-12rpx rounded-50% bg-#F97C34"></view>
            </template>
          </wd-input>
        </view>
      </view>
    </template>
    <view :change:prop="mapRenderjs.searchPlace" :prop="querySearch" class="bg-#f5f5f5">
      <view class="px-22rpx py-20rpx">
        <template v-if="placesLength === 0">
          <view class="center py-100rpx">
            <image class="w-250rpx h-250rpx" src="@img/chef/16033@2x.png"></image>
          </view>
        </template>

        <template v-else>
          <view class="rounded-36rpx bg-white">
            <template v-for="(item,index) in logicStore.placesList" :key="index">
              <view :class="[index === logicStore.placesList.length - 1 ? '' : 'border-bottom']"
                    class="px-22rpx pb-30rpx pt-34rpx"
                    @click="handleClickLocation(item)">
                <view class="text-#000 text-26rpx font-bold">{{ item.displayName }}</view>
                <view class="text-#9B9CA0 text-24rpx flex-center-sb">
                  <view>{{ item.formattedAddress }}</view>
                </view>
              </view>
            </template>
          </view>
        </template>
      </view>
      <view id="map" :change:prop="mapRenderjs.initMap" :prop="mapDataComputed" :user-location="userLocation"
            class="absolute left-0 bottom-0 w-0 h-0"></view>
    </view>
  </z-paging>
</template>
<script lang="ts" setup>
const {t, locale} = useI18n();
import {EventEnum} from "@/constant/enums";
import {useLogicStore} from "@/pages-user/store/logic";
import {useUserStore} from "@/store";

const userStore = useUserStore()
const logicStore = useLogicStore()

const placesLength = computed(() => {
  return logicStore.placesList.length;
});
const userLocation = computed(() => ({
  longitude: userStore.location.longitude,
  latitude: userStore.location.latitude
}));

watch(
    () => logicStore.searchLoading,
    (newValue) => {
      if (newValue) {
        uni.showLoading({
          title: 'Loading...',
          mask: true,
        });
      } else {
        uni.hideLoading();
      }
    },
    {immediate: true}
);

// 地图搜索关键词
const mapSearchKeyword = ref<string>('');
const querySearch = computed(() => {
  return {
    keyword: mapSearchKeyword.value,
  }
})

function handleClickLocation(item: any) {
  console.log('item', item)
  uni.$emit(EventEnum.CHOOSE_ADDRESS, item)
  uni.navigateBack()
}

function navigateTo(url: string) {
  uni.navigateTo({
    url: url,
  });
}

onLoad((options: any) => {
})
onShow(() => {
})

const mapDataComputed = computed(() => {
  return {
    language: locale.value,
    lng: userStore.location.longitude || 174.7633,
    lat: userStore.location.latitude || -36.8485,
  }
})
</script>
<script lang="ts">
import {useLogicStore} from "@/pages-user/store/logic";

export default {
  data() {
    return {
      logicStore: useLogicStore(),
    }
  },
  created() {
    this.logicStore.clearPlacesList()
  },
  methods: {
    async handleShowPlaces(places: any) {
      console.log(places, '接收到的搜索结果')
      if (places && places.length > 0) {
        this.logicStore.setPlacesList(places);
      }
    },
    showMapNotLoadedTip() {
      uni.showToast({
        title: 'Map is not loaded yet, please wait',
        icon: 'none'
      });
    },
    setSearchLoading(isLoading: boolean) {
      // this.logicStore.searchLoading = isLoading;
    },
    showSearchTimeoutTip() {
      uni.showToast({
        title: 'Search timeout, please try again',
        icon: 'none'
      });
    }
  },
}
</script>
<script lang="renderjs" module="mapRenderjs">
import {Loader} from "@googlemaps/js-api-loader"
import * as R from 'ramda'
import Config from '@/config'
import {debounce} from "throttle-debounce";

let map = null
let mapLoaded = false; // 地图加载完成标志
// @ts-ignore
export default {
  data() {
    return {
      region: "US",
      lan: 'en',
      google: null,
      canvas: null,
      center: null,
      dotLottie: null,
      marker: null,
      markerViewList: [],
      AdvancedMarkerElement: null,
      lng: -77.0365,
      lat: 38.8977,
      userLocation: {
        longitude: 0,
        latitude: 0
      }
    }
  },
  props: {
    userLocation: Object
  },
  mounted() {
    console.log('mounted mapRenderjs')
    mapLoaded = false; // 重置地图加载完成标志
    // !map&&this.initMap()
    this.searchPlace = debounce(200, this.searchPlace)
  },
  methods: {
    initMap({lng, lat, language}) {
      console.log('initMap', lng, lat)
      console.log('当前系统语言', language)

      this.lan = language === 'zh-Hans' ? 'zh-CN' : 'en'
      this.region = language === 'zh-Hans' ? 'CN' : 'US'
      this.lng = language === 'zh-Hans' ? 116.4074 : -77.0365
      this.lat = language === 'zh-Hans' ? 39.9042 : 38.8977
      console.log('当前系统语言', this.lan)
      console.log('当前系统区域', this.region)

      this.$nextTick(() => {
        const loader = new Loader({
          apiKey: Config.googleMapKey,
          version: "weekly",
          region: this.region, // 设置为美国
          language: this.lan,
        });


        loader.load().then(async (google) => {
          const {Map} = await google.maps.importLibrary("maps")
          this.google = google
          console.log('google', google.maps)
          // 地图相关配置
          // 指定自定义地图样式的 ID。
          // center: 地图初始中心点的经纬度（lat, lng）。
          // zoom: 地图初始缩放级别。
          // fullscreenControl: 是否显示全屏按钮（false 表示不显示）。
          // cameraControl: 是否显示相机控制（false 表示不显示）。
          // disableDefaultUI: 是否禁用所有默认 UI 控件（true 表示全部禁用）。
          // gestureHandling: 设置手势操作方式（"greedy" 表示允许所有手势操作）
          const mapOptions = {
            mapId: 'ff2268c265ce7a40',
            center: {
              lat: this.lat,
              lng: this.lng,
            },
            zoom: 12,
            fullscreenControl: false,
            cameraControl: false,
            disableDefaultUI: true,
            gestureHandling: "greedy",
          };

          map = new Map(document.getElementById("map"), mapOptions);
          mapLoaded = true; // 地图加载完成
        });
      })
    },
    async searchPlace({keyword}) {
      console.log('搜索关键词', keyword);
      console.log('搜索关键词', !keyword);
      console.log('map', !map);
      console.log('google', !this.google);
      if (!keyword) {
        this.$ownerInstance.callMethod('handleShowPlaces', [])
      }
      if (!mapLoaded && keyword) {
        console.log('地图未加载完成，无法搜索');
        this.$ownerInstance.callMethod('showMapNotLoadedTip');
        return;
      }
      if (!map || !this.google || !keyword) {
        return
      }
      this.$ownerInstance.callMethod('setSearchLoading', true);
      let timeoutId;
      try {
        // 设置搜索超时
        const timeoutPromise = new Promise((_, reject) => {
          timeoutId = setTimeout(() => {
            if (this && this.$ownerInstance) {
              this.$ownerInstance.callMethod('setSearchLoading', false);
            }
            reject(new Error('Search timeout'));
          }, 10000); // 10 秒超时
        });

        const {Place, SearchByTextRankPreference} = await this.google.maps.importLibrary("places");
        const request = {
          textQuery: keyword,
          fields: ['id', 'displayName', 'location', 'formattedAddress', 'addressComponents'],
          locationBias: {lat: this.lat, lng: this.lng},
          language: this.lan,
          maxResultCount: 20,
          region: this.region,
          rankPreference: SearchByTextRankPreference.RELEVANCE
        };

        const searchPromise = Place.searchByText(request);
        const {places} = await Promise.race([searchPromise, timeoutPromise]);
        console.log('地图搜索结果', places, SearchByTextRankPreference);
        this.$ownerInstance.callMethod('handleShowPlaces', places);
      } catch (e) {
        console.log('搜索错误原因', e);
        if (e.message === 'Search timeout') {
          this.$ownerInstance.callMethod('showSearchTimeoutTip');
        }
        this.$ownerInstance.callMethod('handleShowPlaces', []);
      } finally {
        clearTimeout(timeoutId);
        this.$ownerInstance.callMethod('setSearchLoading', false); // 通知主组件搜索结束
      }
    }
  },
}
</script>
<style>
page {
  background-color: #f5f5f5;
}
</style>
<style lang="scss" scoped>

</style>
