<script lang="ts" setup>
import { computed, onMounted, ref } from 'vue';
import { useRoute, useRouter } from 'vue-router';

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

import {
  Clock,
  DArrowLeft,
  Delete,
  Edit,
  Expand,
  HomeFilled,
  MoreFilled,
  Notification,
  Plus,
  Upload,
  Warning,
} from '@element-plus/icons-vue';
import {
  ElAvatar,
  ElButton,
  ElDialog,
  ElDropdown,
  ElDropdownItem,
  ElDropdownMenu,
  ElIcon,
  ElInput,
  ElMessage,
  ElOption,
  ElSelect,
  ElTabPane,
  ElTabs,
  ElTree,
  ElUpload,
} from 'element-plus';

import { addComment, querycomment } from '#/api/knowledge/comment';
import {
  addKnowledgeContent,
  deleteKnowledgeContent,
  editKnowledgeContent,
  getKnowledgeContentDetail,
  queryKnowledgeContentlist,
} from '#/api/knowledge/content';
import {
  addrecord,
  queryPublishRecordlist,
  queryrecord,
} from '#/api/knowledge/record';
import { getSingleImageUploadConfig } from '#/components/upload/config';

import addEditDialog from './addEditDialog.vue';

import '#/assets/iconfonts/font/iconfont.css';

const userStore = useUserStore();
const userId = userStore.userInfo?.userId;
// 路由实例
const router = useRouter();
const route = useRoute();
const { classId, classname, classicon } = route.params;
console.log(route.params);

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

// 活跃标签页
const activeTab = ref('comments');

// 章节数据
const chapterData = ref([]) as any;
const chapterDataloading = ref(false);
const comments = ref([]) as any;
const uploadRef = ref(null) as any;
const commentsloading = ref(true);
const centerloading = ref(false);
const isEdit = ref(false);
const ChapterId = ref(null);
// 查询章节数据
const chapterDatafn = async () => {
  chapterDataloading.value = true;
  try {
    const res = await queryKnowledgeContentlist(classId);
    if (res.code === 200) {
      console.log('章节数据', res.data);

      chapterData.value = res.data || [];
      handleChapterClick({ id: chapterData.value[0]?.id });
    }
  } catch (error) {
    console.log(error);
  } finally {
    chapterDataloading.value = false;
  }
};
// 查询评论数据
const querycommentfn = async () => {
  commentsloading.value = true;
  try {
    const res = await querycomment({
      targetId: classId,
      targetType: 'knowledge',
    });
    if (res.code === 200) {
      comments.value = res.data || [];
    }
  } catch (error) {
    console.log(error);
  } finally {
    commentsloading.value = false;
  }
};
// 添加记录
const addrecordfn = async () => {
  commentsloading.value = true;
  try {
    await addrecord({ contentId: classId });
  } catch (error) {
    console.log(error);
  } finally {
    commentsloading.value = false;
  }
};
const queryrecordfn = async () => {
  commentsloading.value = true;
  try {
    const res = await queryrecord({ contentId: classId, userId });
    viewRecords.value = res?.rows || [];
  } catch (error) {
    console.log(error);
  } finally {
    commentsloading.value = false;
  }
};
onMounted(() => {
  chapterDatafn();
  querycommentfn();
  addrecordfn();
  queryrecordfn();
});
// 选中的章节
const selectedChapter = ref({}) as any;

// 查看记录
const viewRecords = ref([]) as any;

// 操作记录
// const operationRecords = ref([
//   { user: '赵六 (管理员)', time: '2025-12-22 14:30', action: '更新了章节内容' },
//   { user: '张三 (产品部)', time: '2025-12-22 10:30', action: '创建了新章节' },
//   { user: '管理员', time: '2025-12-21 16:45', action: '审核通过' },
// ]);

// 新评论内容
const newComment = ref('');
const commentImages = ref([]) as any;

// 回复相关
const replyingTo = ref(null) as any;
const replyContent = ref('');

// 折叠菜单
const toggleCollapse = () => {
  isCollapse.value = !isCollapse.value;
};

// 提醒弹框
const notificationDialogVisible = ref(false);
const notificationContent = ref('');
const notificationRecipients = ref([]);

// 打开提醒弹框
const openNotificationDialog = () => {
  notificationDialogVisible.value = true;
  notificationContent.value = '';
  notificationRecipients.value = [];
};

// 关闭提醒弹框
const closeNotificationDialog = () => {
  notificationDialogVisible.value = false;
};

// 编辑历史弹框
const editHistoryDialogVisible = ref(false);

// 发送提醒
const sendNotification = () => {
  if (!notificationContent.value.trim()) {
    ElMessage.warning('请输入提醒内容');
    return;
  }

  if (notificationRecipients.value.length === 0) {
    ElMessage.warning('请选择提醒人');
    return;
  }

  // 模拟发送提醒
  ElMessage.success('提醒发送成功');
  closeNotificationDialog();
};

// 全选提醒人
const selectAllRecipients = () => {
  // 模拟全选功能
  notificationRecipients.value = ['user1', 'user2', 'user3', 'user4', 'user5'];
};

const editHistoryData = ref([]) as any;
// 当前选中的历史记录
const selectedHistoryRecord = ref();
function formatDayOffset(dateStr: string): string {
  const dt = new Date(dateStr.replace(' ', 'T'));
  const now = new Date();
  const targetDate = new Date(dt.getFullYear(), dt.getMonth(), dt.getDate());
  const currentDate = new Date(
    now.getFullYear(),
    now.getMonth(),
    now.getDate(),
  );
  const diffTime = currentDate.getTime() - targetDate.getTime();
  const diffDays = Math.round(diffTime / (1000 * 60 * 60 * 24));

  if (diffDays === 0) return '今天';
  if (diffDays === 1) return '昨天';
  return `${diffDays} 天前`;
}
const weightOf = (d: string) => {
  if (d === '今天') return 0;
  if (d === '昨天') return 1;
  return Number(d.replace(' 天前', '')) + 1;
};
const formatTime = (d: Date) =>
  d.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' });
const computedEditHistoryData = computed(() => {
  const dayMap = new Map<string, any[]>();
  editHistoryData.value.forEach((item:any) => {
    const day = formatDayOffset(item.createTime);
    if (!dayMap.has(day)) dayMap.set(day, []);
    dayMap.get(day)!.push({
      time: formatTime(new Date(item.createTime.replace(' ', 'T'))),
      user: item.publishBy ?? '系统',
      action: item.action ?? '暂无数据',
      id: item.id,
      title: item.title,
      content: item.content,
      attachmentUrl: item.attachmentUrl,
    });
  });
  return [...dayMap.entries()]
    .sort((a, b) => weightOf(a[0]) - weightOf(b[0]))
    .map(([date, records]) => ({ date, records }));
}) as any;
const queryPublishRecordlistfn = async () => {
  try {
    const res = await queryPublishRecordlist({
      categoryId: classId,
      contentId:ChapterId.value
    });
    editHistoryData.value = res?.rows || [];
  } catch (error) {
    console.log(error);
  }
};

// 打开编辑历史弹框
const openEditHistoryDialog = async () => {
  editHistoryDialogVisible.value = true;
  await queryPublishRecordlistfn();
  // 默认选中第一条记录
  if (
    computedEditHistoryData.value.length > 0 &&
    computedEditHistoryData?.value[0]?.records.length > 0
  ) {
    selectedHistoryRecord.value = computedEditHistoryData.value[0].records[0];
  }
};
const openDelHistoryDialog = async () => {
  try {
    await deleteKnowledgeContent(selectedChapter.value.id);
    await chapterDatafn();
  } catch (error) {
    console.log(error);
  }
};
// 关闭编辑历史弹框
const closeEditHistoryDialog = () => {
  editHistoryDialogVisible.value = false;
};

// 选择历史记录
const selectHistoryRecord = (record: any) => {
  selectedHistoryRecord.value = record;
  console.log(selectedHistoryRecord.value);
  // console.log(selectedHistoryRecordcomp.value);
};

// 点击章节
const handleChapterClick = async (node:any) => {
  centerloading.value = true;
  ChapterId.value = node.id;
  if (!isEdit.value) isEdit.value = true;
  addrecordfn();
  try {
    const res = await getKnowledgeContentDetail(node.id);
    if (res.code === 200) {
      console.log('点击章节', res.data);
      selectedChapter.value = {
        id: res.data.id,
        label: res.data.title,
        content: res.data.content,
        updatedTime: res.data.updateTime,
        attachmentUrl: res.data.attachmentUrl,
      };
    }
  } catch (error) {
    console.log(error);
  } finally {
    centerloading.value = false;
  }
};

// 点击主页
const handleHomeClick = () => {
  selectedChapter.value = {
    id: 'home',
    label: '主页',
    content:
      '这是知识库的主页内容，您可以在这里查看知识库的概述信息和使用指南。',
    updatedTime: '2025-12-22 14:30:00',
    attachmentUrl: [],
  };
};
const addEditDialogVisible = ref(false);
const addiseditTitle = ref('');
const editvaloraddId = ref({});
// 添加章节
const addChapter = (data) => {
  addEditDialogVisible.value = true;
  addiseditTitle.value = '新增章节';
  editvaloraddId.value = {
    categoryId: data.categoryId,
    parentId: data.id,
    status: 2,
  };
};
// 编辑章节
const editChapter = (node) => {
  addEditDialogVisible.value = true;
  addiseditTitle.value = '编辑章节';
  editvaloraddId.value = node;
};

// 删除章节
const deleteChapter = async (node) => {
  try {
    await deleteKnowledgeContent(node.id);
    await chapterDatafn();
  } catch (error) {
    console.log(error);
  }
};

// 提交评论
const submitComment = async () => {
  if (!newComment.value.trim() && commentImages.value.length === 0) {
    ElMessage.warning('请输入评论内容或上传图片');
    return;
  }
  try {
    await addComment({
      targetId: Number(classId),
      targetType: 'knowledge',
      attachments: commentImages.value.map((item) => item.fileName).join(','),
      content: newComment.value,
    });
    newComment.value = '';
    commentImages.value = [];
    querycommentfn();
  } catch {
    ElMessage.error('评论提交失败');
  }
};

// 回复评论
const replyToComment = (commentId: number) => {
  replyingTo.value = commentId;
  replyContent.value = '';
};

// 提交回复
const submitReply = async (commentId: number) => {
  if (!replyContent.value.trim()) {
    ElMessage.warning('请输入回复内容');
    return;
  }
  try {
    await addComment({
      parentId: commentId,
      targetId: Number(classId),
      targetType: 'knowledge',
      content: replyContent.value,
    });
    querycommentfn();
    replyingTo.value = null;
    replyContent.value = '';
  } catch {
    ElMessage.error('评论提交失败');
  }
};

// 取消回复
const cancelReply = () => {
  replyingTo.value = null;
  replyContent.value = '';
};

// 格式化时间为相对时间
const formatRelativeTime = (dateString: any) => {
  const date = new Date(dateString);
  const now = new Date();
  const diff = now.getTime() - date.getTime();

  const minutes = Math.floor(diff / 60_000);
  const hours = Math.floor(diff / 3_600_000);
  const days = Math.floor(diff / 86_400_000);

  if (minutes < 60) {
    return `${minutes}分钟前`;
  } else if (hours < 24) {
    return `${hours}小时前`;
  } else {
    return `${days}天前`;
  }
};
// 上传图片成功
const handleUploadSuccess = (file: any) => {
  if (file.code === 200) {
    commentImages.value.push({
      fileName: file.data.fileName,
      url: file.data.url,
    });
  }
};
// 移除上传的图片
const removeImage = (index: number) => {
  commentImages.value = [];
  uploadRef?.value?.clearFiles();
};
const navigateToEdit = (id: number) => {
  router.push(`/knowledge/detail/edit/${id}/${ChapterId.value}`);
};
const addMenu = () => {
  addEditDialogVisible.value = true;
  addiseditTitle.value = '新增章节';
  editvaloraddId.value = {
    categoryId: classId,
    parentId: 0,
    status: 2,
  };
};
// 递归查找节点路径
const findNodePath = (
  data: any[],
  targetId: number,
  path: any[] = [],
): any[] | null => {
  for (let i = 0; i < data.length; i++) {
    const node = data[i];
    const currentPath = [...path, { data, index: i }];
    if (node.id === targetId) {
      return currentPath;
    }
    if (node.children && node.children.length > 0) {
      const result = findNodePath(node.children, targetId, currentPath);
      if (result) {
        return result;
      }
    }
  }
  return null;
};
// 新增和修改目录对话框
const addoreditclick = (val: any) => {
  const nodePath = findNodePath(chapterData.value, val.editvaloraddId?.id);
  if (nodePath && nodePath.length > 0) {
    console.log('编辑');
    editKnowledgeContent({
      categoryId: val.editvaloraddId?.categoryId,
      parentId: val.editvaloraddId?.parentId,
      id: val.editvaloraddId?.id,
      status: val.editvaloraddId?.status,
      title: val.title,
    })
      .then(() => {
        chapterDatafn();
      })
      .finally(() => {
        addEditDialogVisible.value = false;
      });
  } else {
    console.log('新增');
    addKnowledgeContent({
      categoryId: val.editvaloraddId?.categoryId,
      parentId: val.editvaloraddId?.parentId,
      status: val.editvaloraddId?.status,
      title: val?.title,
    })
      .then(() => {
        chapterDatafn();
      })
      .finally(() => {
        addEditDialogVisible.value = false;
      });
  }
};
const imageExt = new Set(['bmp', 'gif', 'jpeg', 'jpg', 'png', 'svg', 'webp']);
const isImage = (url: string) => {
  if (!url) return false;
  try {
    const cleanUrl = url.split('?')[0];
    const ext = cleanUrl.split('.').pop()?.toLowerCase() ?? '';
    return imageExt.has(ext);
  } catch {
    return false;
  }
};
const fileName = (url: string) =>
  url.split('?')[0]?.split('/')?.pop() ?? 'file';
/* 非图片列表 */
const nonImageList = computed(() => {
  const urls = Array.isArray(selectedChapter.value.attachmentUrl)
    ? selectedChapter.value.attachmentUrl
    : selectedChapter.value.attachmentUrl
      ? [selectedChapter.value.attachmentUrl]
      : [];
  const result = urls.filter((u) => !isImage(u));
  return result;
});
</script>

<template>
  <Page>
    <div class="knowledge-detail">
      <!-- 顶部导航栏 -->
      <div class="top-nav">
        <div class="nav-left">
          <ElIcon class="nav-icon"><HomeFilled /></ElIcon>
          <span class="nav-separator">|</span>
          <span class="nav-item gray">知识搜索</span>
          <span class="nav-separator">></span>
          <span class="nav-item active">我的文件</span>
        </div>
        <div class="nav-right">
          <ElButton @click="navigateToEdit(classId)" v-if="isEdit">
            编辑
          </ElButton>
          <ElDropdown>
            <ElButton type="text">
              <ElIcon><MoreFilled /></ElIcon>
            </ElButton>
            <template #dropdown>
              <ElDropdownMenu>
                <ElDropdownItem @click="openNotificationDialog">
                  <ElIcon><Notification /></ElIcon> 提醒
                </ElDropdownItem>
                <ElDropdownItem @click="openEditHistoryDialog">
                  <ElIcon><Clock /></ElIcon> 编辑历史
                </ElDropdownItem>
                <ElDropdownItem @click="openDelHistoryDialog">
                  <ElIcon><Delete /></ElIcon> 删除
                </ElDropdownItem>
              </ElDropdownMenu>
            </template>
          </ElDropdown>
        </div>
      </div>

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

          <div class="sidebar-content">
            <!-- 知识库信息 -->
            <div class="knowledge-info">
              <div class="knowledge-icon">
                <span
                  v-if="classicon?.includes('iconfont')"
                  :class="classicon?.split(',')[0] || ''"
                  :style="{
                    color: `#${classicon?.split(',')[1] || ''}`,
                    fontSize: '30px',
                  }"
                ></span>
                <img v-else :src="classicon" alt="" />
              </div>
              <div class="knowledge-title">{{ classname }}</div>
            </div>

            <!-- 主页按钮 -->
            <div class="home-btn" @click="handleHomeClick">
              <ElIcon><HomeFilled /></ElIcon>
              <span :class="{ collapsed: isCollapse }">主页</span>
              <ElIcon style="margin-left: 120px" @click="addMenu">
                <Plus />
              </ElIcon>
            </div>

            <!-- 章节树 -->
            <div class="chapter-tree">
              <ElTree
                :data="chapterData"
                node-key="id"
                :props="{ label: 'title', children: 'children' }"
                default-expand-all
                :expand-on-click-node="false"
                :current-node-key="chapterData[0]?.id"
                highlight-current
                @node-click="handleChapterClick"
              >
                <template #default="{ node, data }">
                  <div class="tree-node-content">
                    <span class="chapter-label" :title="node.label">
                      {{ node.label }}
                      <ElIcon v-if="!data.saved" class="unsaved-icon">
                        <!-- <Notification /> -->
                      </ElIcon>
                    </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>
              </ElTree>
            </div>
          </div>
        </div>

        <!-- 中间内容 -->
        <div class="center-content" v-loading="centerloading">
          <ElIcon
            v-if="isCollapse"
            :size="20"
            class="collapse-control-btn"
            @click="isCollapse = false"
          >
            <Expand />
          </ElIcon>
          <!-- 内容头部 -->
          <div class="content-header">
            <h2 class="content-title">{{ selectedChapter.label }}</h2>
            <div class="content-meta">
              <ElIcon class="meta-icon"><Clock /></ElIcon>
              <span>{{ selectedChapter.updatedTime }}</span>
            </div>
          </div>

          <!-- 内容主体 -->
          <div class="content-body">
            <div class="content-text" v-html="selectedChapter.content"></div>
            <!-- 附件 -->
            <div class="content-attachments">
              <h3>附件</h3>
              <div
                style="
                  display: flex;
                  flex-direction: column;
                  gap: 10px;
                  width: 100%;
                "
              >
                <!-- 图片文件 -->
                <div
                  v-if="
                    Array.isArray(selectedChapter.attachmentUrl) &&
                    selectedChapter.attachmentUrl.length > 0
                  "
                >
                  <!-- <h4>图片文件：</h4> -->
                  <div style="display: flex; gap: 10px; flex-wrap: wrap">
                    <template
                      v-for="url in selectedChapter.attachmentUrl"
                      :key="`${url}-img`"
                    >
                      <img
                        v-if="isImage(url)"
                        style="
                          width: 100px;
                          height: 100px;
                          object-fit: cover;
                          border-radius: 4px;
                        "
                        :src="url"
                        :alt="fileName(url)"
                      />
                    </template>
                    <!-- <div v-if="!selectedChapter.attachmentUrl.some(isImage)" style="color: #999;">
                      没有图片文件
                    </div> -->
                  </div>
                </div>

                <!-- 非图片文件 -->
                <div v-if="nonImageList.length > 0">
                  <!-- <h4>文档文件：</h4> -->
                  <div style="display: flex; flex-direction: column; gap: 5px">
                    <a
                      v-for="url in nonImageList"
                      :key="`${url}-file`"
                      :href="url"
                      download
                      style="
                        padding: 8px 12px;
                        background-color: #f0f0f0;
                        border-radius: 4px;
                        text-decoration: none;
                        color: #333;
                        display: inline-block;
                      "
                    >
                      <ElIcon class="file-icon"><Document /></ElIcon>
                      &nbsp;点击下载 {{ fileName(url) }}
                    </a>
                  </div>
                </div>

                <!-- 无附件情况 -->
                <div
                  v-if="
                    !Array.isArray(selectedChapter.attachmentUrl) ||
                    selectedChapter.attachmentUrl.length === 0
                  "
                  style="color: #999"
                >
                  该章节没有附件
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 右侧边栏 -->
        <div class="right-sidebar">
          <!-- 评论区 -->
          <div class="comment-section">
            <div class="section-title">
              <span>评论</span>
              <el-tooltip class="box-item" effect="dark" placement="top">
                <template #content>
                  如何点评?<br />
                  有认同有建议。遇到特别好的地方不要吝啬你的表扬，遇到问题可参考以下要点进行点评;<br />
                  1 明确指出问题;<br />
                  2 分点详细简述;<br />
                  3 最好配图;<br />
                  4 提出可行性建议;</template
                >
                <el-icon><Warning /></el-icon>
              </el-tooltip>
            </div>

            <!-- 写评论 -->
            <div class="write-comment">
              <!-- 第一行：评价 -->
              <div class="comment-row">
                <div class="row-label">评价：</div>
                <div class="row-content">
                  <ElInput
                    v-model="newComment"
                    placeholder="请填写评论"
                    type="textarea"
                    resize="none"
                    rows="3"
                    maxlength="200"
                    show-word-limit
                  />
                </div>
              </div>

              <!-- 第二行：照片 -->
              <div class="comment-row">
                <div class="row-label">照片：</div>
                <div class="row-content">
                  <div class="photo-area">
                    <div class="photo-preview" v-if="commentImages.length > 0">
                      <img :src="commentImages[0].url" alt="照片" />
                      <ElButton
                        type="text"
                        size="small"
                        class="remove-photo"
                        @click="removeImage"
                      >
                        ×
                      </ElButton>
                    </div>
                  </div>
                  <div class="upload-btn" v-show="commentImages.length === 0">
                    <ElUpload
                      ref="uploadRef"
                      v-bind="getSingleImageUploadConfig()"
                      :show-file-list="false"
                      :on-success="handleUploadSuccess"
                    >
                      <ElIcon><Upload /></ElIcon>
                    </ElUpload>
                  </div>
                </div>
              </div>

              <!-- 提交按钮 -->
              <div class="comment-submit">
                <ElButton type="primary" size="small" @click="submitComment">
                  提交
                </ElButton>
              </div>
            </div>

            <!-- 标签页切换 -->
            <ElTabs
              v-model="activeTab"
              class="right-tabs"
              v-loading="commentsloading"
            >
              <ElTabPane label="评论列表" name="comments">
                <!-- 评论列表 -->
                <div class="comment-list">
                  <div
                    v-for="comment in comments"
                    :key="comment.id"
                    class="comment-item"
                  >
                    <ElAvatar class="comment-avatar">
                      {{ comment?.username.slice(-2) }}
                    </ElAvatar>
                    <div class="comment-content">
                      <!-- 第一行：头像、姓名、岗位 -->
                      <div class="comment-header">
                        <span class="comment-username">{{
                          comment?.username
                        }}</span>
                        <span class="comment-position"
                          >({{ comment?.user?.position }})</span
                        >
                      </div>

                      <!-- 第二行：评论内容 -->
                      <div class="comment-text">{{ comment?.content }}</div>

                      <!-- 评论图片 -->
                      <div
                        class="comment-images"
                        v-if="comment?.attachmentsUrl?.length > 0"
                      >
                        <img
                          v-for="(image, index) in comment?.attachmentsUrl"
                          :key="index"
                          :src="image"
                          alt="评论图片"
                          class="comment-image"
                        />
                      </div>

                      <!-- 第三行：时间和回复按钮 -->
                      <div class="comment-meta">
                        <span class="comment-time">{{
                          formatRelativeTime(comment?.updateTime)
                        }}</span>
                        <ElButton
                          type="text"
                          size="small"
                          @click="replyToComment(comment?.id)"
                          class="reply-btn"
                        >
                          回复
                        </ElButton>
                      </div>

                      <!-- 第四行：历史回复消息 -->
                      <div
                        class="reply-list"
                        v-if="comment?.children?.length > 0"
                      >
                        <div
                          v-for="reply in comment?.children"
                          :key="reply?.id"
                          class="reply-item"
                        >
                          <div class="reply-text">
                            <span class="reply-username"
                              >{{ reply?.username }}：</span
                            >
                            {{ reply?.content }}
                          </div>
                        </div>
                      </div>

                      <!-- 回复输入框 -->
                      <div
                        class="reply-input-wrapper"
                        v-if="replyingTo === comment.id"
                      >
                        <ElInput
                          v-model="replyContent"
                          placeholder="写下您的回复..."
                          resize="none"
                          rows="3"
                          maxlength="200"
                          show-word-limit
                          class="reply-input"
                        />
                        <div class="reply-actions">
                          <ElButton
                            type="primary"
                            size="small"
                            @click="submitReply(comment.id)"
                            class="submit-btn"
                          >
                            提交
                          </ElButton>
                          <ElButton
                            type="default"
                            size="small"
                            @click="cancelReply"
                            class="cancel-btn"
                          >
                            收起
                          </ElButton>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </ElTabPane>

              <ElTabPane label="查看记录" name="views">
                <!-- 查看记录 -->
                <div class="view-records">
                  <div class="record-list">
                    <div
                      v-for="(record, index) in viewRecords"
                      :key="index"
                      class="record-item"
                    >
                      <div class="record-left">
                        <ElAvatar class="record-avatar">
                          {{ record?.userName.slice(-2) }}
                        </ElAvatar>
                        <span class="record-user">{{ record?.userName }}</span>
                      </div>
                      <div
                        class="record-time"
                        style="font-size: 14px; color: #86909c"
                      >
                        {{ record?.updateTime }}
                      </div>
                    </div>
                  </div>
                </div>
              </ElTabPane>
              <!-- 操作记录 -->
              <!-- <ElTabPane label="操作记录" name="operations">
                <div class="operation-records">
                  <div class="record-list">
                    <div
                      v-for="(record, index) in operationRecords"
                      :key="index"
                      class="record-item"
                    >
                      <div class="record-left">
                        <ElAvatar class="record-avatar">
                          {{ record.user.charAt(0) }}
                        </ElAvatar>
                        <div class="record-info">
                          <div class="record-user">{{ record.user }}</div>
                          <div class="record-action">{{ record.action }}</div>
                        </div>
                      </div>
                      <div class="record-time">
                        {{ record.time }}
                      </div>
                    </div>
                  </div>
                </div>
              </ElTabPane> -->
            </ElTabs>
          </div>
        </div>
      </div>
    </div>

    <!-- 提醒弹框 -->
    <ElDialog v-model="notificationDialogVisible" title="提醒" width="500px">
      <div class="notification-dialog">
        <!-- 提醒内容 -->
        <div class="dialog-row">
          <div class="row-label">提醒内容：</div>
          <div class="row-content">
            <ElInput
              v-model="notificationContent"
              placeholder="请填写提醒内容"
              type="textarea"
              resize="none"
              rows="4"
              maxlength="200"
              show-word-limit
            />
          </div>
        </div>

        <!-- 提醒人 -->
        <div class="dialog-row">
          <div class="row-label">提醒人：</div>
          <div class="row-content">
            <ElSelect
              v-model="notificationRecipients"
              multiple
              placeholder="请选择提醒人"
              clearable
              style="width: 100%"
            >
              <ElOption label="张三 (产品部)" value="user1" />
              <ElOption label="李四 (技术部)" value="user2" />
              <ElOption label="王五 (设计部)" value="user3" />
              <ElOption label="赵六 (市场部)" value="user4" />
              <ElOption label="钱七 (运营部)" value="user5" />
            </ElSelect>
            <div class="select-all-btn">
              <ElButton type="text" @click="selectAllRecipients">全选</ElButton>
            </div>
          </div>
        </div>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <ElButton @click="closeNotificationDialog">取消</ElButton>
          <ElButton type="primary" @click="sendNotification">确定</ElButton>
        </div>
      </template>
    </ElDialog>

    <!-- 编辑历史弹框 -->
    <ElDialog
      v-model="editHistoryDialogVisible"
      title="编辑历史"
      width="900px"
      height="600px"
    >
      <div class="edit-history-dialog">
        <!-- 左侧时间轴 -->
        <div class="history-timeline">
          <div
            v-for="(day, index) in computedEditHistoryData"
            :key="index"
            class="history-day"
          >
            <div class="day-title">{{ day.date }}</div>
            <div
              v-for="record in day.records"
              :key="record.id"
              class="history-record"
              :class="{ active: selectedHistoryRecord?.id === record.id }"
              @click="() => selectHistoryRecord(record)"
            >
              <div class="record-time">{{ record.time }}</div>
              <div class="record-info">
                <div class="record-user">{{ record.user }}</div>
                <div class="record-action">{{ record.action }}</div>
              </div>
            </div>
          </div>
        </div>

        <!-- 右侧内容 -->
        <div class="history-content">
          <div v-html="selectedHistoryRecord?.content"></div>
        </div>
      </div>
    </ElDialog>

    <addEditDialog
      v-model:add-edit-dialog-visible="addEditDialogVisible"
      :addisedit-title="addiseditTitle"
      :editvaloradd-id="editvaloraddId"
      @addoreditclick="addoreditclick"
    />
  </Page>
</template>

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

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

.nav-left {
  display: flex;
  gap: 8px;
  align-items: center;
}

.nav-icon {
  font-size: 18px;
  color: #1890ff;
}

.nav-separator {
  color: #e8e8e8;
}

.nav-item {
  font-size: 14px;
  cursor: pointer;
  transition: color 0.3s;

  &.gray {
    color: #999;
  }

  &.active {
    font-weight: 500;
    color: #000;
  }

  &:hover {
    color: #1890ff;
  }
}

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

.left-sidebar.collapsed .collapse-btn {
  right: -15px;
}

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

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

.knowledge-info {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  margin-bottom: 12px;
}

.knowledge-icon {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 48px;
  height: 48px;
  margin-bottom: 10px;
  // background-color: #1890ff;
  border-radius: 8px;
}

.icon-large {
  font-size: 32px;
  color: #fff;
}

.knowledge-title {
  font-size: 16px;
  font-weight: 500;
  text-align: center;
  transition: opacity 0.3s;

  &.collapsed {
    height: 0;
    margin: 0;
    overflow: hidden;
    opacity: 0;
  }
}

.home-btn {
  display: flex;
  gap: 8px;
  align-items: center;
  padding: 10px;
  margin-bottom: 20px;
  cursor: pointer;
  background-color: #e8f3ff;
  border-radius: 6px;
  transition: background-color 0.3s;

  span {
    transition: opacity 0.3s;
  }

  &.collapsed {
    span {
      width: 0;
      overflow: hidden;
      opacity: 0;
    }
  }

  &:hover {
    background-color: #e0f2fe;
  }
}

.chapter-search {
  margin-bottom: 20px;
  transition: opacity 0.3s;

  &.collapsed {
    height: 0;
    margin: 0;
    overflow: hidden;
    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 {
  position: absolute;
  right: 0;
  display: none;
  gap: 4px;
}

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

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

.unsaved-icon {
  margin-left: 4px;
  color: #ff9800;
}

.chapter-label {
  display: inline-block;
  max-width: 80px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  vertical-align: middle;
}

/* 中间内容区 */
.center-content {
  position: relative;
  flex: 1;
  padding: 20px;
  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;
}

.content-header {
  margin-bottom: 20px;
  margin-left: 20px;
}

.content-title {
  margin-bottom: 8px;
  font-size: 24px;
  font-weight: 500;
}

.content-meta {
  display: flex;
  gap: 4px;
  align-items: center;
  font-size: 12px;
  color: #999;
}

.content-body {
  line-height: 1.8;
}

.content-text {
  margin-bottom: 30px;
  font-size: 14px;
}

.content-attachments {
  padding-top: 20px;
  border-top: 1px solid #e8e8e8;
}

/* 右侧边栏 */
.right-sidebar {
  display: flex;
  flex-direction: column;
  gap: 20px;
  width: 320px;
}

.comment-section {
  display: flex;
  flex-direction: column;
  gap: 20px;
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgb(0 0 0 / 10%);
}

.section-title {
  display: flex;
  gap: 8px;
  align-items: center;
  padding-left: 12px;
  margin-bottom: 20px;
  font-size: 16px;
  font-weight: 500;
  color: #000;
  border-left: 3px solid #1890ff;
}

.write-comment {
  display: flex;
  flex-direction: column;
  gap: 15px;
  max-height: 300px;
  padding-right: 5px;
  margin-bottom: 20px;
  overflow-y: auto;
}

.write-comment::-webkit-scrollbar {
  width: 6px;
}

.write-comment::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.write-comment::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.write-comment::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

.comment-row {
  display: flex;
  gap: 10px;
  align-items: flex-start;
}

.row-label {
  flex-shrink: 0;
  width: 60px;
  padding-top: 6px;
  font-size: 14px;
  font-weight: 500;
  color: #000;
  text-align: right;
}

.row-content {
  display: flex;
  flex: 1;
  flex-direction: column;
  gap: 10px;
}

.photo-area {
  display: flex;
  gap: 15px;
  align-items: center;
}

.photo-preview,
.photo-placeholder {
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 80px;
  height: 80px;
  background-color: #fafafa;
  border: 1px solid #e8e8e8;
  border-radius: 4px;
}

.photo-preview img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 4px;
}

.remove-photo {
  position: absolute;
  top: -8px;
  right: -8px;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 20px;
  height: 20px;
  padding: 0;
  font-size: 14px;
  line-height: 1;
  color: #fff;
  background-color: rgb(0 0 0 / 50%);
  border-radius: 50%;
}

.comment-submit {
  display: flex;
  justify-content: flex-start;
  margin-top: 10px;
}

.comment-submit .el-button {
  padding: 8px 16px;
  margin-left: 20px;
  font-size: 14px;
}

.upload-btn {
  display: flex;
  align-items: center;
}

.comment-list {
  display: flex;
  flex-direction: column;
  gap: 25px;
  /* max-height: 400px; */

  /* overflow-y: auto; */
}

.comment-item {
  display: flex;
  gap: 12px;
  padding-bottom: 15px;
}

.comment-avatar {
  width: 36px;
  height: 36px;
  margin-top: 2px;
  color: #fff;
  background-color: #1890ff;
}

.comment-content {
  display: flex;
  flex: 1;
  flex-direction: column;
  gap: 8px;
}

/* 第一行：头像、姓名、岗位 */
.comment-header {
  display: flex;
  gap: 8px;
  align-items: center;
  font-size: 14px;
}

.comment-username {
  font-weight: 500;
  color: #000;
}

.comment-position {
  font-size: 12px;
  color: #666;
}

/* 第二行：评论内容 */
.comment-text {
  font-size: 14px;
  line-height: 1.5;
  color: #666;
}

.comment-images {
  display: flex;
  gap: 8px;
  margin-bottom: 5px;
}

.comment-image {
  width: 80px;
  height: 80px;
  object-fit: cover;
  border-radius: 4px;
}

/* 第三行：时间和回复按钮 */
.comment-meta {
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 12px;
  color: #999;
}

.reply-btn {
  padding: 0 !important;
  margin: 0 !important;
  font-size: 12px !important;
  color: #1890ff !important;
}

/* 第四行：历史回复消息 */
.reply-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.reply-item {
  padding: 10px;
  font-size: 14px;
  color: #666;
  background-color: #f5f5f5;
  border-radius: 4px;
}

.reply-text {
  display: block;
  line-height: 1.4;
}

.reply-text .reply-username {
  margin-right: 5px;
  font-weight: 500;
  color: #000;
}

/* 回复输入框 */
.reply-input-wrapper {
  padding: 15px;
  margin-top: 12px;
  background-color: #fafafa;
  border: 1px solid #e8e8e8;
  border-radius: 4px;
}

.reply-input {
  margin-bottom: 10px;
  border-radius: 4px;
}

.reply-actions {
  display: flex;
  gap: 10px;
  justify-content: flex-start;
}

.submit-btn {
  color: #fff;
  background-color: #1890ff;
  border-color: #1890ff;
}

.cancel-btn {
  color: #606266;
  background-color: #fff;
  border-color: #dcdfe6;
}

/* 编辑历史弹框样式 */
.edit-history-dialog {
  display: flex;
  gap: 20px;
  width: 100%;
  height: calc(100vh - 300px);
  padding: 10px;
}

/* 左侧时间轴 */
.history-timeline {
  width: 250px;
  height: 100%;
  padding: 10px;
  overflow-y: auto;
  background-color: #fff;
  border-radius: 8px;
}

.history-day {
  margin-bottom: 20px;
}

.day-title {
  margin-bottom: 10px;
  font-size: 16px;
  font-weight: 500;
  color: #303133;
}

.history-record {
  display: flex;
  gap: 10px;
  padding: 10px;
  cursor: pointer;
  background-color: #fff;
  border-radius: 6px;
  transition: all 0.3s ease;
}

.record-time {
  flex-shrink: 0;
  // width: 60px;
  padding-top: 2px;
  font-size: 12px;
  font-weight: 500;
  color: #86909c;
  text-align: left;
}

.record-info {
  flex: 1;
  min-width: 0;
}

.record-user {
  margin-bottom: 2px;
  font-size: 13px;
  color: #606266;
}

.record-action {
  font-size: 13px;
  color: #909399;
}

.history-record:hover {
  background-color: #e6e8eb;
}

.history-record.active {
  // border-left: 3px solid #1890ff;
  color: #1890ff;
  background-color: #e8f3ff;
}

.record-time {
  margin-bottom: 2px;
  font-size: 14px;
  font-weight: 500;
  color: #303133;
}

.record-user {
  margin-bottom: 2px;
  font-size: 13px;
  color: #606266;
}

.record-action {
  font-size: 13px;
  color: #909399;
}

/* 右侧内容 */
.history-content {
  flex: 1;
  height: 100%;
  padding: 20px;
  overflow-y: auto;
  background-color: #fff;
  border-radius: 8px;
}

.content-title {
  margin-bottom: 20px;
  font-size: 24px;
  font-weight: 500;
  color: #303133;
}

.content-section {
  margin-bottom: 30px;
}

.section-title {
  margin-bottom: 10px;
  font-size: 18px;
  font-weight: 500;
  color: #303133;
}

.section-content {
  font-size: 14px;
  line-height: 1.8;
  color: #606266;
  white-space: pre-wrap;
}

.content-attachments {
  padding-top: 20px;
  margin-top: 30px;
  border-top: 1px solid #e8e8e8;
}

.attachments-title {
  margin-bottom: 10px;
  font-size: 16px;
  font-weight: 500;
  color: #303133;
}

/* 滚动条样式 */
.history-timeline::-webkit-scrollbar,
.history-content::-webkit-scrollbar {
  width: 6px;
  height: 6px;
}

.history-timeline::-webkit-scrollbar-track,
.history-content::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.history-timeline::-webkit-scrollbar-thumb,
.history-content::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.history-timeline::-webkit-scrollbar-thumb:hover,
.history-content::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

/* 标签页样式 */
.right-tabs {
  flex: 1;
  max-height: 400px;
  padding-right: 5px;
  overflow-y: auto;
  :deep(.el-tabs__header) {
    position: sticky;
    top: 0;
    z-index: 1000;
    background-color: #fff;
    margin: 0;
  }
  :deep(.el-tabs__content) {
    overflow-y: auto;
    padding-right: 5px;
    padding-top: 12px;
    padding-bottom: 12px;
  }
}

.right-tabs::-webkit-scrollbar {
  width: 6px;
}

.right-tabs::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.right-tabs::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.right-tabs::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

/* 查看记录和操作记录 */
.view-records,
.operation-records {
  padding: 0;
  background-color: transparent;
  border-radius: 0;
  box-shadow: none;
}

.record-list {
  display: flex;
  flex-direction: column;
  gap: 20px;

  /* max-height: 200px; */

  /* overflow-y: auto; */
}

.record-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
  font-size: 14px;
}

.record-left {
  display: flex;
  flex: 1;
  gap: 10px;
  align-items: center;
}

.record-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.record-avatar {
  width: 32px;
  height: 32px;
  color: #fff;
  background-color: #1890ff;
}

.record-user {
  font-size: 14px;
  font-weight: 500;
  color: #000;
}

.record-time {
  font-size: 14px;
  color: #000;
  text-align: right;
}

.record-action {
  margin-top: 2px;
  font-size: 13px;
  color: #666;
}

/* 提醒弹框样式 */
.notification-content {
  .form-item {
    margin-bottom: 20px;
  }

  .form-label {
    margin-bottom: 8px;
    font-size: 14px;
    font-weight: 500;
    color: #000;
  }

  .recipient-section {
    display: flex;
    gap: 10px;
    align-items: center;
  }
}

/* 提醒弹框样式 */
.notification-dialog {
  .dialog-row {
    display: flex;
    gap: 12px;
    align-items: flex-start;
    margin-bottom: 16px;
  }

  .row-label {
    flex-shrink: 0;
    width: 70px;
    padding-top: 8px;
    font-size: 14px;
    font-weight: 500;
    color: #303133;
    text-align: right;
  }

  .row-content {
    flex: 1;
    width: 0;
  }

  .select-all-btn {
    margin-top: 8px;
    text-align: right;
  }

  .dialog-footer {
    display: flex;
    gap: 12px;
    justify-content: flex-end;
  }
}

/* 回复相关样式 */
.reply-input-wrapper {
  padding: 15px;
  margin-top: 12px;
  background-color: #fafafa;
  border: 1px solid #e8e8e8;
  border-radius: 4px;
}

.reply-input {
  margin-bottom: 10px;
  border-radius: 4px;
}

.reply-actions {
  display: flex;
  gap: 10px;
  justify-content: flex-start;
}

.submit-btn {
  color: #fff;
  background-color: #1890ff;
  border-color: #1890ff;
}

.cancel-btn {
  color: #606266;
  background-color: #fff;
  border-color: #dcdfe6;
}
</style>
