<template>
  <view class="d-flex flex-col bg-base">
    
    <u-tabs 
      :list="tabs" 
      :current="tabCurrentIndex"
      lineWidth="30"
      lineColor="#d9492e"
      :activeStyle="{
        color: '#000',
        fontWeight: 'bold',
        transform: 'scale(1.05)'
      }"
      :inactiveStyle="{
        color: '#606266',
        transform: 'scale(1)'
      }"
      :scrollable="true"
      class="top-tab"
      @click="onTabClick"
    />
    <view class="d-flex flex-col p-2">
      <uni-search-bar 
        v-model="searchValue"
        radius="100" 
        bgColor="#fff" 
        placeholder="搜索地图数据库" 
        clearButton="auto" 
        cancelButton="none"
        @confirm="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 '@/common/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 { useTabControl } from '@/common/composeabe/TabControl';

const { 
  tabCurrentIndex ,
  tabs,
  onTabClick
} = useTabControl({
  tabs: [
    {
      name: '非遗项目'
    },
    {
      name: '非遗传习所'
    },
    {
      name: '文物古迹'
    },
    {
      name: '传统村落'
    },
    {
      name: '闽南文化景区'
    },
  ],
  onTabChange() {
    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 list;
  switch (tabCurrentIndex.value) {
    default:
    case 0:
      list = (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)).list;
      break;
    case 1:
      list = (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)).list;
      break;
    case 2:
      list = (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)).list;
      break;
    case 3:
      list = (await VillageApi.getVallageList()).filter(p => 
        (!searchValue.value || p.villageName.indexOf(searchValue.value) > -1)
      );
      break;
    case 4:
      list = (await ScenicSpotContent.getContentList(new GetContentListParams().setSelfValues({
        keywords: searchValue.value,
      }), page, pageSize)).list
      break;
  }
  
  const 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 || AppCofig.defaultImage,
      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: res.map(p => ({
      latitude: p.latitude,
      longitude: p.longitude,
    })),
    padding: [20, 20, 20, 20],
  });
  mapCtx.addMarkers({
    clear: true,
    markers: res, 
  })
  return res;
}, 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) {
    default:
    case 0: navTo('/pages/article/details', { id }); break;
    case 1: navTo('/pages/inhert/intangible/details', { id }); break;
    case 2: navTo('/pages/inhert/artifact/details', { id }); break;
    case 3: navTo('/pages/inhert/village/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) - 1;
  listLoader.loadData(undefined, true);
})
</script>