<script lang="ts" setup>
// @ts-ignore
import type { VbenFormProps } from '@vben/common-ui';

// @ts-ignore
import type { VxeGridProps } from '#/adapter/vxe-table';

import { onMounted, ref } from 'vue';
import { useRouter } from 'vue-router';

// @ts-ignore
import { Page, useVbenDrawer } from '@vben/common-ui';

import {
  CopyDocument,
  DArrowLeft,
  Delete,
  Download,
  Edit,
  Expand,
  Plus,
} from '@element-plus/icons-vue';

// @ts-ignore
import { useVbenVxeGrid } from '#/adapter/vxe-table';
import {
  deletePaperCategory,
  PaperCategoryTree,
  // @ts-ignore
} from '#/api/exam/paper/category';
// @ts-ignore
import { paperList } from '#/api/exam/paper/paper';
// @ts-ignore

import { queryFormSchema, tableColumns } from './config-data';
// @ts-ignore
import chapterDrawer from './cpn/chapter/drawer.vue';

// 路由实例
const router = useRouter();
// const route = useRoute();
// 菜单折叠状态
const isCollapse = ref(false);

// 章节数据
const chapterData = ref([]);

// 选中的章节
const selectedChapter = ref({
  id: '',
  label: '',
});

// 表单配置
const formOptions: VbenFormProps = {
  commonConfig: {
    labelWidth: 80,
    componentProps: {
      allowClear: true,
    },
  },
  schema: queryFormSchema(),
  wrapperClass: 'grid-cols-1 md:grid-cols-2 lg:grid-cols-4',
};

// 表格配置
const gridOptions: VxeGridProps = {
  checkboxConfig: {
    highlight: true,
    reserve: true,
    trigger: 'default',
  },
  columns: tableColumns,
  size: 'medium',
  // 固定表格高度，避免高度不断增加
  height: 800,
  // 确保表格有唯一ID
  id: 'unique-exam-paper-table',
  // 分页配置
  pagerConfig: {
    pageSize: 20,
    currentPage: 1,
    pageSizes: [10, 20, 50, 100],
  },
  proxyConfig: {
    enabled: true,
    autoLoad: true,
    page: {
      currentKey: 'currentPage',
      sizeKey: 'pageSize',
    },
    ajax: {
      query: async ({ page }, formValues = {}) => {
        // 当前选择的章节ID
        const categoryId = selectedChapter.value.id || 0;
        const data: any = await paperList({
          categoryId,
          ...formValues,
          pageNum: page.currentPage,
          pageSize: page.pageSize,
        });
        // 确保返回格式正确，使用 items 作为数据键
        return {
          items: data.rows,
          total: data.total,
        };
      },
    },
  },
  rowConfig: {
    keyField: 'id',
  },
  toolbarConfig: {
    custom: true,
    refresh: true,
    zoom: true,
  },
};

// 使用表格
const [BasicTable, basicTableApi] = useVbenVxeGrid({
  formOptions,
  gridOptions,
});

// 试卷抽屉组件引用
const paperDrawerRef = ref(null);

// 章节抽屉组件
const [ChapterVbenDrawer, chapterVbenDrawerApi] = useVbenDrawer({
  connectedComponent: chapterDrawer,
});

// 点击章节
const handleChapterClick = (node) => {
  selectedChapter.value = {
    id: node.id,
    label: node.label,
  };
  // 触发表格刷新，模拟获取对应章节的试卷
  basicTableApi.reload();
};

// 添加章节
const addChapter = (chapter: any = {}) => {
  chapterVbenDrawerApi.setData({ ...chapter, isUpdate: false }).open();
};

// 编辑章节
const editChapter = (chapter: any) => {
  chapterVbenDrawerApi.setData({ ...chapter, isUpdate: true }).open();
};

// 删除章节
const deleteChapter = (chapter: any) => {
  ElMessageBox.confirm('确认删除该章节吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    await deletePaperCategory(chapter.id);
    await getChapterTree();
  });
};

// 获取章节树
const getChapterTree = async () => {
  const data: any = await PaperCategoryTree();
  chapterData.value = data.rows || [];
};

// 新增试卷
const addExam = () => {
  // 打开抽屉
  paperDrawerRef.value.openDrawer();
};

// 添加时间
const addTime = () => {
  ElMessage.info('添加时间功能待实现');
};

// 删除试卷
const deleteExam = (row) => {
  ElMessage.info('删除试卷功能待实现');
};

// 批量删除试卷
const deleteHandle = () => {
  const checkRecords = basicTableApi.grid.getCheckboxRecords();
  const ids = checkRecords.map((item: any) => item.id);
  if (ids.length <= 0) {
    return;
  }

  ElMessageBox.confirm(`确认删除选中的${ids.length}条数据吗?`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    // 模拟批量删除操作
    console.log('批量删除试卷:', ids);
    await basicTableApi.reload();
  });
};

// 编辑试卷
const editExam = (row) => {
  // 跳转到编辑页面，并传递试卷ID
  router.push(`/examManage/examEdit/${row.id}`);
};

// 预览弹框状态
const previewDialogVisible = ref(false);
const previewExamData = ref(null);

// 预览试卷
const previewExam = (row) => {
  // 模拟试卷数据，实际项目中应该通过API获取
  previewExamData.value = {
    id: row.id,
    paperName: row.paperName,
    questions: [
      {
        id: 1,
        type: 1,
        title: '以下哪个是Vue的核心特性？',
        score: 5,
        options: [
          { id: 1, text: '响应式数据绑定', isCorrect: true },
          { id: 2, text: '命令式编程', isCorrect: false },
          { id: 3, text: '双向数据流', isCorrect: false },
          { id: 4, text: '静态模板', isCorrect: false },
        ],
        correctAnswer: 'A',
      },
      {
        id: 2,
        type: 2,
        title: 'Vue组件的生命周期钩子中，哪个在组件挂载后调用？',
        score: 5,
        options: [
          { id: 1, text: 'beforeCreate', isCorrect: false },
          { id: 2, text: 'created', isCorrect: false },
          { id: 3, text: 'mounted', isCorrect: true },
          { id: 4, text: 'beforeMount', isCorrect: false },
        ],
        correctAnswer: 'C',
      },
      {
        id: 3,
        type: 3,
        title: 'Vuex是Vue的状态管理库。',
        score: 2,
        options: [
          { id: 1, text: '正确', isCorrect: true },
          { id: 2, text: '错误', isCorrect: false },
        ],
        correctAnswer: '正确',
      },
      {
        id: 4,
        type: 1,
        title: 'Vue中，哪个指令用于条件渲染？',
        score: 5,
        options: [
          { id: 1, text: 'v-for', isCorrect: false },
          { id: 2, text: 'v-if', isCorrect: true },
          { id: 3, text: 'v-bind', isCorrect: false },
          { id: 4, text: 'v-on', isCorrect: false },
        ],
        correctAnswer: 'B',
      },
      {
        id: 5,
        type: 2,
        title: '以下哪些是Vue的内置指令？（多选）',
        score: 8,
        options: [
          { id: 1, text: 'v-model', isCorrect: true },
          { id: 2, text: 'v-show', isCorrect: true },
          { id: 3, text: 'v-class', isCorrect: false },
          { id: 4, text: 'v-style', isCorrect: false },
        ],
        correctAnswer: 'A,B',
      },
      {
        id: 6,
        type: 3,
        title: 'Vue 3兼容Vue 2的所有语法。',
        score: 2,
        options: [
          { id: 1, text: '正确', isCorrect: false },
          { id: 2, text: '错误', isCorrect: true },
        ],
        correctAnswer: '错误',
      },
      {
        id: 7,
        type: 4,
        title: 'Vue中，______是用于在组件之间传递数据的属性。',
        score: 3,
        correctAnswer: 'props',
      },
      {
        id: 8,
        type: 5,
        title: '请简述Vue的响应式原理。',
        score: 10,
        correctAnswer:
          'Vue的响应式原理基于Object.defineProperty()方法，通过对数据对象的属性进行getter和setter的劫持，实现数据变化时自动更新视图。当数据被访问时触发getter，当数据被修改时触发setter，setter会通知依赖收集器更新相关的视图。',
      },
      {
        id: 9,
        type: 1,
        title: 'Vue Router的模式中，哪种需要后端配置支持？',
        score: 5,
        options: [
          { id: 1, text: 'hash', isCorrect: false },
          { id: 2, text: 'history', isCorrect: true },
          { id: 3, text: 'abstract', isCorrect: false },
          { id: 4, text: 'memory', isCorrect: false },
        ],
        correctAnswer: 'B',
      },
      {
        id: 10,
        type: 2,
        title: 'Vue 3中新增的Composition API包括哪些？（多选）',
        score: 8,
        options: [
          { id: 1, text: 'setup()', isCorrect: true },
          { id: 2, text: 'ref()', isCorrect: true },
          { id: 3, text: 'reactive()', isCorrect: true },
          { id: 4, text: 'watchEffect()', isCorrect: true },
        ],
        correctAnswer: 'A,B,C,D',
      },
    ],
  };
  previewDialogVisible.value = true;
};

// 复制试卷
const copyExam = (row) => {
  ElMessage.info('复制试卷功能待实现');
};
// 生成试卷链接
const generateLink = (row) => {
  ElMessage.info('生成试卷链接功能待实现');
};
// 下载试卷
const downloadExam = (row) => {
  ElMessage.info('下载试卷功能待实现');
};

const addPaper = () => {
  // 跳转到添加试卷页面
  // /examManage/paperManage/edit/:id?
  router.push('/examManage/paperManage/edit');
};

// 页面加载时获取数据
onMounted(() => {
  // 获取试卷分类树形图
  getChapterTree().then(() => {
    // 默认选中第一个章节
    if (chapterData.value.length > 0) {
      handleChapterClick(chapterData.value[0]);
    }
  });
});
</script>

<template>
  <Page :auto-content-height="true">
    <div class="knowledge-detail">
      <!-- 主体内容区 -->
      <div class="main-content">
        <!-- 左侧目录 -->
        <div class="left-sidebar" :class="{ collapsed: isCollapse }">
          <!-- 折叠按钮 -->
          <div class="collapse-btn" @click="isCollapse = true">
            <ElIcon><DArrowLeft /></ElIcon>
          </div>

          <div class="sidebar-content">
            <!-- 章节树 -->
            <div class="chapter-tree">
              <ElTree
                :data="chapterData"
                node-key="id"
                :props="{ label: 'name' }"
                default-expand-all
                :expand-on-click-node="false"
                @node-click="handleChapterClick"
              >
                <template #default="{ node, data }">
                  <div class="tree-node-content">
                    <span>{{ node.label }}</span>
                    <div class="tree-node-actions">
                      <ElButton
                        type="text"
                        size="small"
                        circle
                        @click.stop="addChapter(data)"
                        title="添加章节"
                      >
                        <ElIcon><Plus /></ElIcon>
                      </ElButton>
                      <ElButton
                        type="text"
                        size="small"
                        circle
                        @click.stop="editChapter(data)"
                        title="编辑章节"
                      >
                        <ElIcon><Edit /></ElIcon>
                      </ElButton>
                      <ElButton
                        type="text"
                        size="small"
                        circle
                        @click.stop="deleteChapter(data)"
                        title="删除章节"
                      >
                        <ElIcon><Delete /></ElIcon>
                      </ElButton>
                    </div>
                  </div>
                </template>
                <template #empty>
                  <div class="tree-empty">
                    <span class="el-tree__empty-text">暂无分类</span>
                    <ElButton
                      type="primary"
                      class="mt-10 w-full"
                      @click="addChapter()"
                    >
                      <ElIcon><Plus /></ElIcon> 添加分类
                    </ElButton>
                  </div>
                </template>
              </ElTree>
            </div>
          </div>
        </div>

        <!-- 中间内容 -->
        <div class="center-content">
          <ElIcon
            v-if="isCollapse"
            :size="20"
            class="collapse-control-btn"
            @click="isCollapse = false"
          >
            <Expand />
          </ElIcon>

          <!-- 试卷列表区域 -->
          <div class="question-list">
            <!-- 试卷列表 -->
            <BasicTable table-title="试卷管理列表">
              <template #toolbar-tools>
                <ElSpace>
                  <ElButton type="primary" @click="addPaper">
                    新增试题
                  </ElButton>
                  <ElButton
                    type="danger"
                    :disabled="
                      !(basicTableApi?.grid?.getCheckboxRecords?.()?.length > 0)
                    "
                    @click="deleteHandle"
                  >
                    批量删除
                  </ElButton>
                  <ElButton type="primary" @click="addExam">
                    发布考试
                  </ElButton>
                </ElSpace>
              </template>
              <template #action="{ row }">
                <div class="action-buttons">
                  <ElButton
                    type="text"
                    size="small"
                    @click="previewExam(row)"
                    style="margin-left: 0px"
                  >
                    预览
                  </ElButton>
                  <ElButton
                    type="text"
                    size="small"
                    @click="copyExam(row)"
                    style="margin-left: 0px"
                  >
                    <ElIcon><CopyDocument /></ElIcon>
                    复制
                  </ElButton>
                  <ElButton
                    type="text"
                    size="small"
                    @click="generateLink(row)"
                    style="margin-left: 0px"
                  >
                    <ElIcon><Link /></ElIcon>
                    生成链接
                  </ElButton>

                  <ElButton
                    type="text"
                    size="small"
                    @click="downloadExam(row)"
                    style="margin-left: 0px"
                  >
                    <ElIcon><Download /></ElIcon>
                    下载
                  </ElButton>
                  <ElButton
                    type="text"
                    size="small"
                    @click="editExam(row)"
                    style="margin-left: 0px"
                  >
                    <ElIcon><Edit /></ElIcon>
                    编辑
                  </ElButton>
                  <ElButton
                    type="text"
                    size="small"
                    @click="deleteExam(row)"
                    class="text-red-500"
                    style="margin-left: 0px"
                  >
                    <ElIcon><Delete /></ElIcon>
                    删除
                  </ElButton>
                </div>
              </template>
            </BasicTable>
          </div>
        </div>
      </div>
    </div>

    <!-- 试卷抽屉组件 -->
    <PaperDrawer ref="paperDrawerRef" />
    <!-- 章节抽屉组件 -->
    <ChapterVbenDrawer @reload="getChapterTree" />
  </Page>
</template>

<style lang="scss" scoped>
.knowledge-detail {
  display: flex;
  flex-direction: column;
  height: calc(100vh - 122px);
}

/* 顶部导航 */
.top-nav {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  padding: 16px 20px;
  margin-bottom: 10px;
  background-color: #fff;
  border-bottom: 1px solid #e8e8e8;
}

.nav-right {
  display: flex;
  gap: 12px;
}

/* 主体内容区 */
.main-content {
  display: flex;
  flex: 1;
  gap: 10px;
}

/* 左侧边栏 */
.left-sidebar {
  position: relative;
  width: 250px;
  overflow: hidden;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgb(0 0 0 / 10%);
  transition: all 0.3s ease;
}

.left-sidebar.collapsed {
  width: 0;
  padding: 0;
  margin: 0;
}

.collapse-btn {
  width: 24px;
  height: 24px;
  padding: 15px;
  line-height: 24px;
  text-align: center;
  cursor: pointer;
}

.sidebar-content {
  padding: 15px;
  transition: opacity 0.3s ease;
}

.left-sidebar.collapsed .sidebar-content {
  pointer-events: none;
  opacity: 0;
}

.chapter-tree {
  max-height: calc(100vh - 300px);
  overflow-y: auto;
}

.tree-empty {
  display: contents;
  // flex-direction: column;
  align-items: center;
  // justify-content: center;
  padding: 20px 20px;
  text-align: center;
  min-height: 300px;
}

.tree-empty .el-tree__empty-text {
  margin-top: 0px;
  font-size: 16px;
  color: #909399;
}

.tree-empty .el-button {
  margin-top: 100px;
  width: 200px;
  margin-bottom: 0px;
}

.tree-node-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
}

.tree-node-actions {
  display: none;
  gap: 4px;
}

.tree-node-content:hover .tree-node-actions {
  display: flex;
}

.tree-node-actions button {
  margin-left: 0 !important;
}

/* 中间内容区 */
.center-content {
  position: relative;
  flex: 1;
  overflow-y: auto;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgb(0 0 0 / 10%);
}

.collapse-control-btn {
  position: absolute;
  top: 15px;
  left: 10px;
  z-index: 10;
  padding: 4px;
  margin-right: 10px;
  font-size: 20px;
  color: #666;
  cursor: pointer;
  border-radius: 4px;
  transition: color 0.3s;
}

.collapse-control-btn:hover {
  color: #1890ff;
  background-color: #f0f9ff;
}

.question-list-title {
  margin-bottom: 20px;
  font-size: 18px;
  font-weight: 500;
  color: #303133;
}

.action-buttons {
  display: flex;
}
</style>
