<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, useVbenModal } from '@vben/common-ui';

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

// @ts-ignore
import { useVbenVxeGrid } from '#/adapter/vxe-table';
import {
  deleteQuestionCategory,
  questionCategoryTree,
  // @ts-ignore
} from '#/api/exam/question/category';
// @ts-ignore
import { deleteQuestion, questionList } from '#/api/exam/question/question';
// 导入预览组件
// @ts-ignore
import QuestionPreview from '#/components/question';

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

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

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

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

// 选中的章节
const selectedChapter: any = ref({});

// 表单配置
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-question-bank-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获取试题列表
        // 当前选择的章节ID
        const chapterId = selectedChapter.value.id || 0;
        const res: any = await questionList({
          ...formValues,
          categoryId: chapterId,
          pageNum: page.currentPage,
          pageSize: page.pageSize,
        });

        // 确保返回格式正确，使用 items 作为数据键
        return {
          items: res.rows || [],
          total: res.total || 0,
        };
      },
    },
  },
  rowConfig: {
    keyField: 'id',
  },
  toolbarConfig: {
    custom: true,
    refresh: true,
    zoom: true,
  },
};

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

// 点击章节
const handleChapterClick = (node: any) => {
  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) => {
  // ElMessage.info('删除章节功能待实现');
  // 二次确认
  ElMessageBox.confirm('确认删除该章节吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    await deleteQuestionCategory(chapter.id);
    await getChapterTree();
  });
};

// 新增试题
const addQuestion = () => {
  // 跳转到新页面
  router.push('/examManage/questionBank/questionEdit');
};

// 导入试题
// const importQuestions = () => {
//   ElMessage.info('导入试题功能待实现');
// };

// 编辑试题
const editQuestion = (row: any) => {
  // 跳转到编辑页面，并传递试题ID
  router.push(`/examManage/questionBank/questionEdit?id=${row.id}`);
};
const previewQuestions: any = ref([]);
// 预览试题
const previewQuestion = (row: any) => {
  // 打开预览模态框，并传递试题数据
  previewQuestions.value = [row];
  previewModalApi.open();
};

// 删除试题
const deleteQuestionEvent = async (row: any) => {
  // 二次确认
  ElMessageBox.confirm('确认删除该试题吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    await deleteQuestion([row.id]);
    await basicTableApi.reload();
  });
};

// 批量删除试题
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 () => {
    await deleteQuestion(ids);
    await basicTableApi.reload();
  });
};

const [ChapterVbenDrawer, chapterVbenDrawerApi] = useVbenDrawer({
  connectedComponent: ChapterDrawer,
});

// 预览试题模态框
const [PreviewModal, previewModalApi] = useVbenModal({
  // connectedComponent: QuestionPreview,
  title: '预览',
  width: 800,
  height: 600,
  showCancelBtn: false,
  onConfirm: () => {
    previewModalApi.close();
  },
});

const getChapterTree = async () => {
  const data: any = await questionCategoryTree();
  chapterData.value = data.rows || [];
};

// 页面加载时获取数据
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"
                        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="danger"
                    :disabled="
                      !(basicTableApi?.grid?.getCheckboxRecords?.()?.length > 0)
                    "
                    @click="deleteHandle"
                  >
                    批量删除
                  </ElButton>
                  <ElButton type="primary" @click="addQuestion">
                    新增试题
                  </ElButton>
                  <!-- <ElButton type="primary" @click="importQuestions">
                    导入
                  </ElButton> -->
                  <!-- <ElButton type="primary" @click="exportQuestions">
                    导出
                  </ElButton> -->
                </ElSpace>
              </template>
              <template #action="{ row }">
                <div class="action-buttons">
                  <ElButton type="text" size="small" @click="editQuestion(row)">
                    <ElIcon><Edit /></ElIcon>
                    编辑
                  </ElButton>
                  <ElButton
                    type="text"
                    size="small"
                    @click="previewQuestion(row)"
                  >
                    预览
                  </ElButton>
                  <ElButton
                    type="text"
                    size="small"
                    @click="deleteQuestionEvent(row)"
                    class="text-red-500"
                  >
                    <ElIcon><Delete /></ElIcon>
                    删除
                  </ElButton>
                </div>
              </template>
            </BasicTable>
          </div>
        </div>
      </div>
    </div>
    <ChapterVbenDrawer @reload="getChapterTree" />
    <PreviewModal>
      <QuestionPreview :questions="previewQuestions" />
    </PreviewModal>
  </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;
  //gap: 8px;
}

.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;
}
</style>
