<template>
  <view class="position-relative radius-l overflow-hidden">
    <map 
      id="map"
      mapId="map"
      class="w-100 height-400"
      :markers="mapLoader.content.value || []"
      :enable-zoom="false"
      :enable-scroll="false"
      :longitude="AppCofig.defaultLonLat[0]"
      :latitude="AppCofig.defaultLonLat[1]"
      :scale="15"
      @click="navTo(
        props.mapPage || '/pages/inhert/map/index', 
        { tab: mapTab }
      )"
    />
    <scroll-view class="map-tags position-absolute" :scroll-x="true">
      <view class="tag-bar d-flex flex-row flex-nowrap">
        <view 
          v-for="item in mapButtons" :key="item.id"
          :class="mapTab == item.id ? 'active' : ''"
          @click="mapTab=item.id"
        >
          <text :class="`iconfont ${item.icon}`" />
          {{ item.title }}
        </view>
      </view>
    </scroll-view>
  </view>
</template>

<script setup lang="ts">
import { useSimpleDataLoader } from '@/common/composeabe/SimpleDataLoader';
import { navTo } from '@/components/utils/PageAction';
import { computed, getCurrentInstance, ref, watch } from 'vue';
import { doLoadDynamicListData } from '../article/data/CommonCategoryDynamicData';
import type { IHomeCommonCategoryBlockMapProps } from '../article/data/CommonCategoryDefine';
import AppCofig from '@/common/config/AppCofig';
import { waitTimeOut } from '@imengyu/imengyu-utils';

const props = defineProps<IHomeCommonCategoryBlockMapProps>();
const instance = getCurrentInstance();
const mapCtx = uni.createMapContext('map', instance);
const mapTab = ref(0);

const mapButtons = computed(() => {
  return props.mapConfigItems
    .filter(item => item.visible !== false)
    .map((item, i) => ({
      ...item,
      id: i,
    }));
})
const mapLoader = useSimpleDataLoader(async () => {
  let list = (await doLoadDynamicListData(
    props.mapConfigItems[mapTab.value].data,
    1, 6, '', [], []
  ))?.list || [];
  const res = list.map((p) => {
    return {
      title: p.title || p.name,
      id: p.id,
      longitude: Number(p.longitude),
      latitude: Number(p.latitude),
      iconPath: p.thumbnail,
      width: 40,
      height: 40,
    };
  });
  await waitTimeOut(200);
  mapCtx.includePoints({
    points: res.map(p => {
      if (!p.longitude || !p.latitude) {
        p.longitude = AppCofig.defaultLonLat[0];
        p.latitude = AppCofig.defaultLonLat[1];
      }
      return {
        latitude: p.latitude,
        longitude: p.longitude,
      }
    }),
    padding: [20, 20, 20, 20],
  });
  return res;
}, true, undefined, true);

watch(mapTab, () => mapLoader.loadData(undefined, true));

</script>