<template>
  <view class="d-flex flex-col bg-base">
    
    <Tabs
      :tabs="tabs" 
      v-model:currentIndex="tabCurrentIndex"
      :autoScroll="true"
      :autoItemWidth="false"
      :defaultItemWidth="170"
      class="top-tab"
    />
    <view class="d-flex flex-col p-2">
      <SearchBar
        v-model="searchValue"
        placeholder="搜索地图数据库" 
        @search="doSearch"
      />
    </view>
    <view class="d-flex flex-row justify-around p-2 pt-0">
      <SimpleDropDownPicker v-if="tabCurrentIndex == 2" v-model="selectedTag" :columns="categoryData.content.value" />
      <SimpleDropDownPicker v-if="tabCurrentIndex <= 2" v-model="selectedLevel" :columns="levelData.content.value" />
      <SimpleDropDownPicker v-if="tabCurrentIndex <= 2" v-model="selectedRegion" :columns="regionData.content.value" />
    </view>
    <view class="d-flex flex-row flex-wrap justify-between">
      <map 
        id="map"
        class="w-100"
        style="height:80vh"
        :makers="[]"
        :scale="13"
        @markertap="onMarkerTap"
      />
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue';
import { useSimplePageListLoader } from '@/common/composeabe/SimplePageListLoader';
import { navTo } from '@/components/utils/PageAction';
import { useSimpleDataLoader } from '@/common/composeabe/SimpleDataLoader';
import SimpleDropDownPicker from '@/common/components/SimpleDropDownPicker.vue';
import SeminarContent from '@/api/inheritor/SeminarContent';
import CommonContent, { GetContentListParams } from '@/api/CommonContent';
import UnmoveableContent from '@/api/inheritor/UnmoveableContent';
import ProjectsContent from '@/api/inheritor/ProjectsContent';
import { onLoad } from '@dcloudio/uni-app';
import AppCofig from '@/common/config/AppCofig';
import VillageApi from '@/api/inhert/VillageApi';
import ScenicSpotContent from '@/api/fusion/ScenicSpotContent';
import Tabs from '@/components/nav/Tabs.vue';
import SearchBar from '@/components/form/SearchBar.vue';

const tabCurrentIndex = ref(0);
const tabs = [
  {
    id: 0,
    text: '非遗项目'
  },
  {
    id: 1,
    text: '非遗传习所'
  },
  {
    id: 2,
    text: '文物古迹'
  },
  {
    id: 3,
    text: '传统村落'
  },
  {
    id: 4,
    text: '闽南文化景区'
  },
];


watch(tabCurrentIndex, () => {
  listLoader.loadData(undefined, true);
});

const mapCtx = uni.createMapContext('map');
const categoryData = useSimpleDataLoader(async () => 
  [{
    id: 0, 
    name: '全部分类'
  }].concat((await CommonContent.getCategoryList(3)).map((item) => ({
    id: item.id,
    name: item.title,
  })))
, true);
const levelData = useSimpleDataLoader(async () => 
  [{
    id: 0, 
    name: '全部级别'
  }].concat((await CommonContent.getCategoryList(2)).map((item) => ({
    id: item.id,
    name: item.title,
  })))
, true);
const regionData = useSimpleDataLoader(async () => 
  [{
    id: 0, 
    name: '全部区域'
  }].concat((await CommonContent.getCategoryList(1)).map((item) => ({
    id: item.id,
    name: item.title,
  })))
, true);
const selectedTag = ref(0);
const selectedLevel = ref(0);
const selectedRegion = ref(0);
const searchValue = ref('');
const listLoader = useSimplePageListLoader(50, async (page, pageSize) => {
  let res;
  switch (tabCurrentIndex.value) {
    default:
    case 0:
      res = (await ProjectsContent.getContentList(new GetContentListParams().setSelfValues({
        level: selectedLevel.value == 0 ? undefined: selectedLevel.value,
        region: selectedRegion.value == 0 ? undefined: selectedRegion.value,
        keywords: searchValue.value,
      }), page, pageSize));
      break;
    case 1:
      res = (await SeminarContent.getContentList(new GetContentListParams().setSelfValues({
        level: selectedLevel.value == 0 ? undefined: selectedLevel.value,
        region: selectedRegion.value == 0 ? undefined: selectedRegion.value,
        keywords: searchValue.value,
      }), page, pageSize));
      break;
    case 2:
      res = (await UnmoveableContent.getContentList(new GetContentListParams().setSelfValues({
        crType: selectedTag.value == 0 ? undefined: selectedTag.value,
        level: selectedLevel.value == 0 ? undefined: selectedLevel.value,
        region: selectedRegion.value == 0 ? undefined: selectedRegion.value,
        keywords: searchValue.value,
      }), page, pageSize));
      break;
    case 3: {
      const list = (await VillageApi.getVallageList()).filter(p => 
        (!searchValue.value || p.villageName.indexOf(searchValue.value) > -1)
      )
      res = { list, total: list.length };
      break;
    }
    case 4:
      res = (await ScenicSpotContent.getContentList(new GetContentListParams().setSelfValues({
        keywords: searchValue.value,
      }), page, pageSize))
      break;
  }
  
  const makers = res.list.map((p) => {
    if (!p.longitude || !p.latitude) {
      p.longitude = AppCofig.defaultLonLat[0] + Math.random() * 0.1 - 0.05;
      p.latitude = AppCofig.defaultLonLat[1] + Math.random() * 0.1 - 0.05;
    }
    return {
      //...p,
      id: p.id,
      longitude: Number(p.longitude),
      latitude: Number(p.latitude),
      iconPath: p.thumbnail || p.image,
      width: 40,
      height: 40,
      joinCluster: true,
      callout: {
        content: p.title,
        color: "#ffffff",
        fontSize: 15,
        borderRadius: 15,
        padding: "10",
        bgColor: "#d9492e",
        display: "ALWAYS",
      },
    }
  })
  mapCtx.includePoints({
    points: makers.map(p => ({
      latitude: p.latitude,
      longitude: p.longitude,
    })),
    padding: [20, 20, 20, 20],
  });
  mapCtx.addMarkers({
    clear: true,
    markers: makers, 
  })
  return { list: makers, total: res.total };
}, true);

watch(selectedLevel, () => {
  listLoader.loadData(undefined, true);
});
watch(selectedRegion, () => {
  listLoader.loadData(undefined, true);
});
watch(selectedTag, () => {
  listLoader.loadData(undefined, true);
});

function doSearch() {
  listLoader.loadData(undefined, true);
}
function onMarkerTap(e: { markerId: number }) {
  goDetails(e.markerId);
}
function goDetails(id: number) {
  switch (tabCurrentIndex.value) {
    case 0:
    case 1: navTo('/pages/article/data/details?pageConfigName=intangible-details', { id }); break;
    case 2: navTo('/pages/article/data/details?pageConfigName=artifact-details', { id }); break;
    case 3: navTo('/pages/inhert/village/details', { id }); break;
    default:
    case 4: navTo('/pages/article/details', { id }); break;
  }
}

onLoad((query) => {
  mapCtx.initMarkerCluster({
    enableDefaultStyle: false,
    zoomOnClick: true,
    gridSize: 60,
  });
  mapCtx.on('markerClusterCreate', (e: { clusters: any[] }) => {
    const customClusters = e.clusters.map((cluster) => {
      const { center, clusterId, markerIds } = cluster;
      return {
        ...center,
        width: 0,
        height: 0,
        clusterId,
        label: {
          content: markerIds.length.toString(), // 聚合点的数量
          fontSize: 16,
          color: '#fff',
          width: 50,
          height: 50,
          bgColor: '#419afcD9', // 背景颜色
          borderRadius: 25,
          textAlign: 'center',
          anchorX: -10,
          anchorY: -35,
        },
      };
    });
    mapCtx.addMarkers({
      markers: customClusters,
      clear: false,
    });
  })
  tabCurrentIndex.value = Number(query?.tab || 0);
  listLoader.loadData(undefined, true);
})
</script>