<template>
  <ie-page>
    <z-paging ref="pagingRef" v-model="treeData" :loading-more-enabled="false" :auto="false" @query="loadKnowledgeList">
      <template #top>
        <ie-navbar :title="pageTitle" />
        <view class="px-30 py-16 bg-back">
          <view class="flex items-center justify-end gap-x-4" @click="handleViewHistory">
            <uv-icon name="clock" size="16" color="#31A0FC"></uv-icon>
            <text class="text-28 text-primary">查看记录</text>
            <uv-icon name="arrow-right" size="16" color="#31A0FC"></uv-icon>
          </view>
        </view>
      </template>
      <view class="px-40">
        <knowledgeTree :tree-data="treeData" @start-practice="handleStartPractice" />
      </view>
    </z-paging>
  </ie-page>
</template>

<script lang="ts" setup>
import IePage from '@/components/ie-page/ie-page.vue';
import { useTransferPage } from '@/hooks/useTransferPage';
import { getTextbooksKnowledgeList } from '@/api/modules/study';
import knowledgeTree from '@/pagesStudy/components/knowledge-tree.vue';
import * as Study from '@/types/study';
import { EnumPaperType, EnumUserRole } from '@/common/enum';
import { useUserStore } from '@/store/userStore';
import { useAuth } from '@/hooks/useAuth';

const { prevData, transferTo } = useTransferPage();
const userStore = useUserStore();
const pagingRef = ref();
const { checkVipPermission } = useAuth();

const pageTitle = computed(() => {
  return '教材同步练习';
});

const treeData = ref<Study.KnowledgeNode[]>([]);

const handleViewHistory = () => {
  transferTo('/pagesStudy/pages/textbooks-practice-history/textbooks-practice-history', {
    data: {}
  });
}

const loadKnowledgeList = async (page: number, size: number) => {
  try {
    uni.$ie.showLoading();
    const { data } = await getTextbooksKnowledgeList();
    treeData.value = data as Study.KnowledgeNode[];
    pagingRef.value.complete(data);
  } catch (error) {
    console.log(error);
    pagingRef.value.complete(false);
  } finally {
    uni.$ie.hideLoading();
  }
}

const handleStartPractice = async (node: Study.KnowledgeNode) => {
  const hasAuth = checkVipPermission();
  if (hasAuth) {
    transferTo('/pagesStudy/pages/exam-start/exam-start', {
      data: {
        name: '教材同步练习-' + node.name,
        paperType: EnumPaperType.COURSE,
        practiceInfo: {
          name: node.name,
          relateId: node.id
        },
      }
    });
  }
}

onShow(() => {
  nextTick(() => {
    // 下拉刷新数据
    pagingRef.value?.refresh();
  });
});
</script>

<style></style>
