<template>
  <ie-page>
    <ie-navbar title="刷题" />
    <uv-tabs :list="subjectList" key-name="subjectName" @click="handleChangeTab" :scrollable="true"></uv-tabs>
    <view class="h-16 bg-back"></view>
    <view class="px-40">
      <knowledgeTree :tree-data="treeData" @start-practice="handleStartPractice" />
    </view>
  </ie-page>
</template>

<script lang="ts" setup>
import { useTransferPage } from '@/hooks/useTransferPage';
import { getSubjectList, getKnowledgeList } from '@/api/modules/study';
import knowledgeTree from '@/pagesStudy/components/knowledge-tree.vue';
import * as Study from '@/types/study';
import { EnumExamMode } from '@/common/enum';
const { prevData, transferTo } = useTransferPage();
const universityId = computed(() => prevData.value.universityId);
const currentSubjectIndex = ref<number>(-1);
const currentSubjectId = computed(() => {
  if (subjectList.value.length > 0 && currentSubjectIndex.value >= 0) {
    return subjectList.value[currentSubjectIndex.value].subjectId;
  }
  return null;
});
const subjectList = ref<Study.Subject[]>([]);
const treeData = ref<Study.KnowledgeNode[]>([]);
const handleChangeTab = (item: any) => {
  console.log(item)
  currentSubjectIndex.value = item.index;
}

const loadKnowledgeList = async () => {
  if (!currentSubjectId.value) {
    return;
  }
  try {
    const { data } = await getKnowledgeList({
      subjectId: currentSubjectId.value,
      directed: prevData.value.directed
    });
    treeData.value = data as Study.KnowledgeNode[];
  } catch (error) {
    console.log(error);
  }
}

const handleStartPractice = (node: Study.KnowledgeNode) => {
  transferTo('/pagesStudy/pages/start-exam/start-exam', {
    data: {
      name: node.name,
      mode: EnumExamMode.PRACTICE,
      paperType: 'Practice',
      relateId: node.id
    }
  });
}

watch(() => currentSubjectIndex.value, () => {
  loadKnowledgeList();
}, {
  immediate: true
});

const loadData = async () => {
  try {
    const { data } = await getSubjectList({
      universityId: universityId.value
    });
    subjectList.value = data.map(item => ({ subjectId: item.subjectId, subjectName: item.subjectName }));
    currentSubjectIndex.value = 0;
  } catch (error) { }
}
onLoad(() => {
  loadData();
});
</script>

<style></style>
