<template>
  <div class="flex flex-col overflow-visible">
    <FindTabs v-if="discoveryTabs.length" v-model="activeIndex" :tabs="discoveryTabs" @change="handleTabChange" />

    <div class="discovery-scroll" @touchstart="emitScrollTouchStart" @touchmove="emitScrollTouch"
      @scroll="emitScrollTouch">
      <CardSwiper v-if="discoveryCards.length" :list="discoveryCards" @didSelectItem="handleCardClick" />

      <QuickQuestions v-if="discoveryQuickQuestions.length" :list="discoveryQuickQuestions"
        @didSelectItem="handleQuickQuestionClick" />

    </div>
  </div>
</template>

<script setup>
import { onMounted, ref } from "vue";
import { emitter } from '@/utils/events'
import { useRouter } from "vue-router";
import { SEND_MESSAGE_CONTENT_TEXT, SEND_MESSAGE_COMMAND_TYPE, SWITCH_TO_COMPANION_TAB } from "@/constants/constant";
import { getAccessToken } from "@/constants/token";
import { homeTabsData, getNearbyTags, homeTabContentData, homeQuickQuestionData } from "@/api/home";
import { useAppStore, useLocationStore } from "@/store";
import { JumpType } from "@/constants/ChatModel";

import FindTabs from "./components/FindTabs/index.vue";
import CardSwiper from "./components/CardSwiper/index.vue";
import QuickQuestions from "./components/QuickQuestions/index.vue";

const router = useRouter()
const appStore = useAppStore();
const locationStore = useLocationStore();
// 从个渠道获取如二维码
const sceneId = appStore.sceneId || "";

const activeIndex = ref(0);
const discoveryTabs = ref([]);
const discoveryCards = ref([]);
const discoveryQuickQuestions = ref([]);
const emit = defineEmits(["scroll-touch-start", "scroll-touch"]);

const emitScrollTouchStart = () => {
  emit("scroll-touch-start");
};

const emitScrollTouch = () => {
  emit("scroll-touch");
};

// tabs 切换事件
const handleTabChange = ({ tab, idx }) => {
  activeIndex.value = idx;
  queryDiscoveryData(tab.id);
}

// 请求发现页tab数据
const queryTabsList = async () => {
  const res = await homeTabsData();
  if (res.code === 0) {
    // 处理tab数据
    const tabList = res.data.map((item) => ({
      id: item.id,
      label: item.tagName,
    }));
    // 设置tab数据
    discoveryTabs.value = tabList;
    // 根据sceneId查询对应tab数据
    findTabByIdWithActiveTabIndex(sceneId);
  }
}
// 根据id查询tab并设置activeIndex
const findTabByIdWithActiveTabIndex = (tabsId) => {
  // 查询是否有id参数
  const activeTabIndex = discoveryTabs.value.findIndex((tab) => tab.id === tabsId);
  // 如果有则优先展示对应tab数据，没有则展示第一个tab数据
  if (activeTabIndex > -1) {
    activeIndex.value = activeTabIndex;
    queryDiscoveryData(tabsId);
  } else {
    if (discoveryTabs.value.length > 0) {
      activeIndex.value = 0;
      queryDiscoveryData(discoveryTabs.value[0].id);
    }
  }
}

// 统一请求发现页数据
const queryDiscoveryData = async (tabId) => {
  queryDiscoveryCards(tabId);
  queryQuickQuestionData(tabId);
};

// 请求发现页卡片数据
const queryDiscoveryCards = async (tabId) => {
  const res = await homeTabContentData({ tagId: tabId });
  if (res.code === 0) {
    discoveryCards.value = configDataList(res.data);
  }
}

// 请求快速问题列表数据
const queryQuickQuestionData = async (tabId) => {
  const res = await homeQuickQuestionData({ tagId: tabId });
  if (res.code === 0) {
    discoveryQuickQuestions.value = configDataList(res.data);
  }
}

// 统一处理接口返回数据结构
const configDataList = (data) => {
  return data.map((item) => ({
    id: item.id,
    title: item.tabContent.mainTitle,
    subTitle: item.tabContent.subTitle,
    tag: item.tabContent.tag,
    coverImage: item.tabContent.coverImage,
    tabContentId: item.tabContent.id,
    jumpContent: item.tabContent.jumpContent,
    jumpDesc: item.tabContent.jumpDesc,
    jumpType: item.tabContent.jumpType,/// 跳转类型: 0商品 1提示词 2链接 3组件指令
  }));
}

// 卡片点击事件
const handleCardClick = (item) => {
  handleClick(item);
};

// 快速问题点击事件
const handleQuickQuestionClick = (item) => {
  handleClick(item);
};

const handleClick = async (item) => {
  console.log(`执行点击事件: ${item.jumpType}，参数：${JSON.stringify(item.jumpContent)}`);
  // 商品
  if (item.jumpType === JumpType.commodity) {
    router.push({ name: 'goods', query: { commodityId: item.jumpContent } })
  }

  // 提示词
  else if (item.jumpType === JumpType.prompt) {
    emitter.emit(SEND_MESSAGE_CONTENT_TEXT, item.jumpContent);
  }
  // 链接
  else if (item.jumpType === JumpType.link) {
    if (item.jumpContent) {
      const token = getAccessToken();
      router.push({ name: item.jumpContent, query: { token: token } })
    }
  }
  // 组件指令
  else if (item.jumpType === JumpType.command) {
    emitter.emit(SEND_MESSAGE_COMMAND_TYPE, { type: item.jumpContent, title: item.jumpDesc });
  }
}

// 获取附近标签数据
const getNearbyTagsData = async () => {
  const res = await getNearbyTags();
  if (res.code === 0) {
    const nearbyTagId = res.data;
    findTabByIdWithActiveTabIndex(nearbyTagId);
  }
}

// 组件挂载后请求数据
onMounted(() => {
  queryTabsList();
});

</script>
