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

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

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

import { Page } from '@vben/common-ui';

import {
  CopyDocument,
  DArrowLeft,
  Delete,
  Download,
  Edit,
  Expand,
  Plus,
} from '@element-plus/icons-vue';
import {
  ElButton,
  ElDialog,
  ElIcon,
  ElMessage,
  ElMessageBox,
  ElSpace,
  ElTree,
} from 'element-plus';

import { useVbenVxeGrid } from '#/adapter/vxe-table';

// 导入预览组件
import ExamPreview from './cpn/examPreview.vue';

// 路由实例
const router = useRouter();
const route = useRoute();
const classId = route.params.classId;

// 菜单折叠状态
const isCollapse = ref(false);

// 章节数据
const chapterData = ref([
  {
    id: 1,
    label: '第一章 基础知识',
    children: [
      { id: 2, label: '1.1 概述', saved: true },
      { id: 3, label: '1.2 基本概念', saved: false },
      { id: 4, label: '1.3 核心原理', saved: true },
    ],
  },
  {
    id: 5,
    label: '第二章 进阶知识',
    children: [
      { id: 6, label: '2.1 高级特性', saved: true },
      { id: 7, label: '2.2 最佳实践', saved: true },
    ],
  },
  {
    id: 8,
    label: '第三章 案例分析',
    children: [
      { id: 9, label: '3.1 案例一', saved: false },
      { id: 10, label: '3.2 案例二', saved: true },
    ],
  },
]);

// 选中的章节
const selectedChapter = ref({
  id: '1',
  label: '第一章 基础知识',
});

// 模拟试卷数据
const mockExamData = ref([
  {
    id: 1,
    name: '基础知识测试卷',
    category: '基础知识',
    creator: '管理员',
    totalScore: 100,
    questionCount: 20,
    updateDate: '2024-01-15',
  },
  {
    id: 2,
    name: 'Vue框架测试卷',
    category: '框架知识',
    creator: '教师1',
    totalScore: 120,
    questionCount: 25,
    updateDate: '2024-01-16',
  },
  {
    id: 3,
    name: '前端综合测试卷',
    category: '前端基础',
    creator: '教师2',
    totalScore: 150,
    questionCount: 30,
    updateDate: '2024-01-17',
  },
]);

// 表单配置
const formOptions: VbenFormProps = {
  commonConfig: {
    labelWidth: 80,
    componentProps: {
      allowClear: true,
    },
  },
  schema: [
    {
      component: 'Input',
      fieldName: 'name',
      label: '试卷名称',
      componentProps: {
        placeholder: '请输入试卷名称',
      },
    },
  ],
  wrapperClass: 'grid-cols-1 md:grid-cols-2 lg:grid-cols-4',
};

// 表格配置
const gridOptions: VxeGridProps = {
  checkboxConfig: {
    highlight: true,
    reserve: true,
    trigger: 'default',
  },
  columns: [
    {
      type: 'checkbox',
      width: 80,
    },
    {
      field: 'name',
      title: '试卷名称',
      minWidth: 200,
    },
    {
      field: 'category',
      title: '类别',
      minWidth: 120,
    },
    {
      field: 'creator',
      title: '创建人',
      minWidth: 120,
    },
    {
      field: 'totalScore',
      title: '试卷总分',
      minWidth: 100,
    },
    {
      field: 'questionCount',
      title: '试题总数',
      minWidth: 100,
    },
    {
      field: 'updateDate',
      title: '更新日期',
      minWidth: 120,
    },
    {
      field: 'action',
      fixed: 'right',
      slots: { default: 'action' },
      title: '操作',
      width: 300,
    },
  ],
  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 = {}) => {
        // 模拟API请求
        console.log('查询参数:', formValues, page);

        // 模拟搜索过滤
        let filteredData = [...mockExamData.value];

        if (formValues.name) {
          filteredData = filteredData.filter((item) =>
            item.name.includes(formValues.name),
          );
        }

        // 模拟分页
        const start = (page.currentPage - 1) * page.pageSize;
        const end = start + page.pageSize;
        const paginatedData = filteredData.slice(start, end);
        console.log('分页数据:', paginatedData);

        // 确保返回格式正确，使用 items 作为数据键
        return {
          items: paginatedData,
          total: filteredData.length,
        };
      },
    },
  },
  rowConfig: {
    keyField: 'id',
  },
  toolbarConfig: {
    custom: true,
    refresh: true,
    zoom: true,
  },
};

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

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

// 添加章节
const addChapter = (parentId = null) => {
  ElMessage.info('添加章节功能待实现');
};

// 编辑章节
const editChapter = (node) => {
  ElMessage.info('编辑章节功能待实现');
};

// 删除章节
const deleteChapter = (node) => {
  ElMessage.info('删除章节功能待实现');
};

// 新增试卷
const addExam = () => {
  // 跳转到新页面
  router.push('/examManage/examEdit/0');
};

// 添加时间
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,
    name: row.name,
    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 downloadExam = (row) => {
  ElMessage.info('下载试卷功能待实现');
};

// 页面加载时获取数据
onMounted(() => {
  // 默认选中第一个章节
  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"
                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="addExam"
                        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>
              </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="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="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>

    <!-- 预览弹框 -->
    <ElDialog
      v-model="previewDialogVisible"
      :title="`试卷预览 - ${previewExamData?.name || ''}`"
      width="800px"
      top="5vh"
      :close-on-click-modal="false"
    >
      <ExamPreview
        v-if="previewExamData"
        :questions="previewExamData.questions"
      />
    </ElDialog>
  </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-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>
