<script lang="ts" setup>
import { ref, onMounted } from 'vue';
import { useRoute } from 'vue-router';
import { Page } from '@vben/common-ui';
import {
  HomeFilled,
  Plus,
  Edit,
  Delete,
  DArrowLeft,
  Expand,
  Notification,
} from '@element-plus/icons-vue';
import {
  ElButton,
  ElIcon,
  ElTree,
  ElMessage,
  ElInput,
  ElUpload,
} from 'element-plus';
import {
  queryKnowledgeContentlist,
  addKnowledgeContent,
  editKnowledgeContent,
  deleteKnowledgeContent,
  getKnowledgeContentDetail,
} from '#/api/knowledge/content';
import TinymceEditor from '#/components/tinymce/src/editor.vue';
import { getFileUploadConfig } from '#/components/upload/config';
// 路由实例
const route = useRoute();
const { classId, ChapterId } = route.params as any;

// 菜单折叠状态
const isCollapse = ref(false);
// 章节数据加载中状态
const chapterDataloading = ref(false);
// 中心内容加载中状态
const centerloading = ref(false);
// 章节数据
const chapterData = ref([]) as any;
// 附件列表
const attachments = ref({}) as any;
const { action, headers } = getFileUploadConfig();
// 查询章节数据
const chapterDatafn = async (ID: any) => {
  chapterDataloading.value = true;
  try {
    const res = await queryKnowledgeContentlist(ID);
    if (res.code === 200) {
      chapterData.value = res.data || [];
    }
  } catch (error) {
    console.log(error);
  } finally {
    chapterDataloading.value = false;
  }
};
onMounted(async () => {
  await chapterDatafn(classId);
  await handleChapterClick({ id: ChapterId });
});

// 选中的章节
const selectedChapter = ref({}) as any;
// 保存草稿
const saveDraft = () => {
  centerloading.value = true;
  editKnowledgeContent({
    categoryId: selectedChapter.value?.categoryId,
    parentId: selectedChapter.value?.parentId,
    id: selectedChapter.value?.id,
    status: 2,
    title: selectedChapter.value?.label,
    content: selectedChapter.value?.content,
    attachment: attachments.value[selectedChapter.value.id]
      .map((item: any) => item.response.data.fileName)
      .join(','),
  })
    .then(() => {
      handleChapterClick({ id: ChapterId });
    })
    .finally(() => {
      centerloading.value = false;
    });
};

// 发布
const publish = () => {
  centerloading.value = true;
  editKnowledgeContent({
    categoryId: selectedChapter.value?.categoryId,
    parentId: selectedChapter.value?.parentId,
    id: selectedChapter.value?.id,
    status: 1,
    title: selectedChapter.value?.label,
    content: selectedChapter.value?.content,
    attachment: attachments.value[selectedChapter.value.id]
      .map((item: any) => item.response.data.fileName)
      .join(','),
  })
    .then(() => {
      handleChapterClick({ id: ChapterId });
    })
    .finally(() => {
      centerloading.value = false;
    });
};

// 处理附件上传
// function handleAttachmentUpload(options: any): Promise<unknown> {
//   return new Promise((resolve) => {
//     // 模拟上传成功处理
//     const fileData = {
//       uid: options.file.uid,
//       name: options.file.name,
//       url: URL.createObjectURL(options.file),
//       status: 'success',
//       raw: options.file,
//     };

//     // 多个文件上传时，url以逗号隔开
//     uploadUrlRef.value = uploadUrlRef.value
//       ? `${uploadUrlRef.value},${fileData.url}`
//       : fileData.url;

//     options.onSuccess(fileData);
//     resolve(fileData);
//   });
// }
// 附件上传成功处理
const handleAttachmentSuccess = (response: any, file: any, fileList: any[]) => {
  console.log('上传成功:', response, file, fileList);
  attachments.value[selectedChapter.value.id] = fileList;
  console.log(fileList);
};
// 移除附件
const handleAttachmentRemove = (file: any, fileList: any[]) => {
  console.log('移除文件:', file, fileList);
  attachments.value[selectedChapter.value.id] = fileList;
};

// 点击章节
const handleChapterClick = async (node: any) => {
  centerloading.value = true;
  selectedChapter.value.content = '';
  try {
    const res = await getKnowledgeContentDetail(node.id);
    if (res.code === 200) {
      selectedChapter.value = {
        id: res.data.id,
        label: res.data.title,
        content: res.data.content,
        updatedTime: res.data.updateTime,
        categoryId: res.data.categoryId,
        parentId: res.data.parentId,
      };
      if (res.data.attachment) {
        attachments.value[res.data.id] = res.data.attachment
          .split(',')
          .map((item, index) => {
            return {
              name: item,
              response: {
                data: {
                  fileName: item,
                },
              },
              status: 'success',
              uid: index + Math.random().toString(36).substring(2),
              raw: item,
            };
          });
        // console.log(res.data.attachment);
      }
    }
  } catch (error) {
    console.log(error);
  } finally {
    centerloading.value = false;
  }
};

// 点击主页
const handleHomeClick = () => {
  selectedChapter.value = {
    id: 'home',
    label: '主页',
    content:
      '这是知识库的主页内容，您可以在这里查看知识库的概述信息和使用指南。',
    updatedTime: '2025-12-22 14:30:00',
  };
};

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

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

// // 删除章节
// const deleteChapter = (node) => {
//   ElMessage.info('删除章节功能待实现');
// };
</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 type="default" @click="saveDraft">保存草稿</ElButton>
          <ElButton type="primary" @click="publish">发布</ElButton>
        </div>
      </div>
      <!-- 主体内容区 -->
      <div class="main-content">
        <!-- 左侧目录 -->
        <div
          class="left-sidebar"
          v-loading="chapterDataloading"
          :class="{ collapsed: isCollapse }"
        >
          <!-- 折叠按钮 -->
          <div class="collapse-btn" @click="isCollapse = true">
            <ElIcon><DArrowLeft /></ElIcon>
          </div>

          <div class="sidebar-content">
            <!-- 知识库信息 -->
            <div class="knowledge-info">
              <div class="knowledge-icon">
                <ElIcon class="icon-large"><HomeFilled /></ElIcon>
              </div>
              <div class="knowledge-title">知识库示例</div>
            </div>

            <!-- 主页按钮 -->
            <div class="home-btn" @click="handleHomeClick">
              <ElIcon><HomeFilled /></ElIcon>
              <span :class="{ collapsed: isCollapse }">主页</span>
            </div>

            <!-- 章节树 -->
            <div class="chapter-tree">
              <ElTree
                :data="chapterData"
                node-key="id"
                :props="{ label: 'title', children: 'children' }"
                default-expand-all
                :current-node-key="ChapterId"
                :expand-on-click-node="false"
                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-form">
            <!-- 第一行：标题 -->
            <div class="form-row">
              <div class="form-item">
                <ElInput
                  v-model="selectedChapter.label"
                  placeholder="请输入标题"
                  class="title-input"
                />
              </div>
            </div>

            <!-- 第二行：富文本编辑器 -->
            <div class="form-row">
              <div class="form-item">
                <TinymceEditor
                  v-model="selectedChapter.content"
                  :height="400"
                />
              </div>
            </div>

            <!-- 第三行：附件上传 -->
            <div class="form-row">
              <div class="form-item">
                <div class="upload-section">
                  <div class="upload-header">
                    <div class="upload-title">上传附件：</div>
                    <ElUpload
                      v-model:file-list="attachments[selectedChapter.id]"
                      accept=".jpg,.jpeg,.png,.gif,.pdf,.doc,.docx,.xls,.xlsx,.ppt,.pptx"
                      :action="action"
                      :headers="headers"
                      list-type="text"
                      show-file-list
                      :auto-upload="true"
                      :drag="false"
                      :limit="5"
                      :multiple="true"
                      :on-remove="handleAttachmentRemove"
                      :on-success="handleAttachmentSuccess"
                    >
                      <div class="upload-btn">
                        <ElIcon><Plus /></ElIcon>
                        <span>添加附件</span>
                      </div>
                    </ElUpload>
                    <div class="upload-note">不超过5M</div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </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: 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%;
}
.chapter-label {
  display: inline-block;
  max-width: 80px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  vertical-align: middle;
}
.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;
}

/* 中间内容区 */
.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%);
}

/* 表单行样式 */
.form-row {
  margin-bottom: 15px;
}

/* 上传区域样式 */
.upload-section {
  width: 100%;
}

.upload-header {
  display: flex;
  gap: 12px;
  align-items: center;
  margin-bottom: 15px;
}

.upload-title {
  font-weight: 500;
  white-space: nowrap;
}

.upload-btn {
  display: inline-flex;
  gap: 4px;
  align-items: center;
  padding: 6px 12px;
  margin-top: 10px;
  font-size: 14px;
  color: #606266;
  cursor: pointer;
  background-color: #fff;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  transition: all 0.3s;

  &:hover {
    color: #409eff;
    border-color: #409eff;
  }
}

.upload-note {
  font-size: 12px;
  color: #909399;
  white-space: nowrap;
}

/* 附件列表样式 */
.el-upload-list {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 10px;
  margin-top: 15px;
}

.el-upload-list__item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 8px 12px;
  font-size: 14px;
  color: #606266;
  background-color: #fff;
  border: 1px solid #ebeef5;
  border-radius: 4px;
}

.el-upload-list__item-name {
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  cursor: pointer;
}

.el-upload-list__item-delete {
  color: #f56c6c;
  cursor: pointer;
  transition: color 0.3s;

  &:hover {
    color: #f78989;
  }
}

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