<script lang="ts" setup>
import { onMounted, ref, watch } from 'vue';

import { ColPage, useVbenDrawer } from '@vben/common-ui';
import { ReadCount } from '@vben/icons';

import {
  Camera,
  Delete,
  Edit,
  HomeFilled,
  Plus,
  Search,
} from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';

// 导入编辑抽屉组件
import EditDrawer from './edit-drawer.vue';
// 导入提醒抽屉组件
import RemindDrawer from './remind-drawer.vue';

// 模拟章节数据
const chapterDataRef = ref([
  {
    id: 1,
    label: '一级标题',
    children: [
      {
        id: 2,
        label: '二级标题',
        children: [{ id: 3, label: '三级标题' }],
      },
    ],
  },
  {
    id: 4,
    label: '一级标题',
    children: [
      {
        id: 5,
        label: '二级标题',
        children: [{ id: 6, label: '三级标题' }],
      },
      {
        id: 7,
        label: '二级标题',
        children: [
          { id: 8, label: '三级标题' },
          { id: 9, label: '三级标题' },
          { id: 10, label: '三级标题' },
        ],
      },
      {
        id: 11,
        label: '二级标题',
        children: [{ id: 12, label: '三级标题' }],
      },
    ],
  },
]);

const treeRef = ref();
const searchTextRef = ref<string>('');
const selectedChapterRef = ref<any>({ id: 'home', label: '主页', content: '' });
const contentRef = ref<string>('');

// 评论相关
const commentContent = ref<string>('');
const commentImages = ref<any[]>([]);

// 定义编辑抽屉
const [EditDrawerComp, drawerApi] = useVbenDrawer({
  connectedComponent: EditDrawer,
});

// 定义提醒抽屉
const [RemindDrawerComp, remindDrawerApi] = useVbenDrawer({
  connectedComponent: RemindDrawer,
});

// 过滤树形图回调
const filterNode = (value: string, data: any) => {
  if (!value) return true;
  return data.label.includes(value);
};

// 左侧属性搜索关键字监听过滤
watch(searchTextRef, (val) => {
  treeRef.value?.filter(val);
});

// 点击左侧树形图某一个节点
function nodeClick(currentNode: any) {
  selectedChapterRef.value = currentNode;
}

// 点击主页
function handleHomeClick() {
  selectedChapterRef.value = { id: 'home', label: '主页', content: '' };
}

// 添加章节
function addChapter(parentNode?: any) {
  console.log('添加章节', parentNode);
  // TODO: 实现添加章节逻辑
}

// 编辑章节
function editChapter(node: any) {
  console.log('编辑章节', node);
  // TODO: 实现编辑章节逻辑
}

// 删除章节
function deleteChapter(node: any) {
  console.log('删除章节', node);
  // TODO: 实现删除章节逻辑
}

// 章节拖拽结束事件
function handleDragEnd(draggingNode: any, dropNode: any, dropType: string) {
  console.log('拖拽结束', draggingNode, dropNode, dropType);
  // TODO: 实现章节拖拽排序逻辑
}

// 打开编辑抽屉
function openEditModal() {
  drawerApi
    .setData({ chapter: selectedChapterRef.value, isUpdate: true })
    .open();
}

// 打开提醒抽屉
function openRemindModal() {
  remindDrawerApi.setData({}).open();
}

// 保存编辑内容
function handleSaveEdit() {
  console.log('保存编辑内容');
  // TODO: 实现保存编辑内容逻辑
  ElMessage.success('章节编辑成功');
  drawerApi.close();
}

// 处理评论图片上传
function handleCommentImageUpload(options: any) {
  // 模拟上传成功处理
  const fileData = {
    uid: options.file.uid,
    name: options.file.name,
    url: URL.createObjectURL(options.file),
    status: 'success',
    raw: options.file,
  };

  // 直接通过v-model:file-list绑定，无需手动添加
  options.onSuccess(fileData);
}

// 移除评论图片
function handleCommentImageRemove(file: any, fileList: any[]) {
  commentImages.value = fileList;
}

// 预览评论图片
function handleCommentImagePreview(file: any) {
  console.log('预览图片', file);
  // TODO: 实现图片预览功能
}

// 提交评论
function submitComment() {
  if (!commentContent.value.trim() && commentImages.value.length === 0) {
    ElMessage.warning('请输入评论内容或上传图片');
    return;
  }

  // 过滤出已成功上传的图片
  const uploadedImages = commentImages.value.filter(
    (image: any) => image.status === 'success',
  );
  // TODO: 实现提交评论逻辑

  // 清空评论内容和
  commentContent.value = '';
  commentImages.value = [];
}
function deleteKnowledge() {
  //
}

onMounted(async () => {
  // TODO: 从接口获取章节数据
  // chapterDataRef.value = await getChapterTree();
});
</script>

<template>
  <div class="knowledge-detail-container">
    <ColPage :left-width="25" auto-content-height>
      <template #left>
        <div
          :style="{ minWidth: '250px' }"
          class="border-border bg-card mr-2 flex h-full flex-col rounded-[var(--radius)] border p-2"
        >
          <!-- 知识库标题 -->
          <div class="mb-4">
            <div class="mb-2 flex items-center justify-between">
              <h3 class="flex items-center text-lg font-bold">
                <img src="/icon/1.png" alt="知识库" class="mr-2 h-6 w-6" />
                知识库示例
              </h3>
            </div>
            <ElInput
              v-model="searchTextRef"
              placeholder="请输入章节名称"
              :prefix-icon="Search"
            />
          </div>

          <!-- 单独的主页项 -->
          <div class="mb-2">
            <div
              class="flex cursor-pointer items-center rounded p-2 transition-colors hover:bg-gray-100"
              @click="handleHomeClick"
            >
              <HomeFilled class="mr-2 h-4 w-4" />
              <span>主页</span>
            </div>
          </div>

          <!-- 单独的目录标题 -->
          <div class="mb-2 flex items-center justify-between p-2 font-medium">
            <span class="text-gray-500">目录</span>
            <ElButton
              type="primary"
              size="small"
              circle
              @click.stop="addChapter()"
              class="!h-6 !w-6 !p-0"
              title="添加一级章节"
            >
              <Plus class="!h-3 !w-3" />
            </ElButton>
          </div>

          <!-- 章节树 -->
          <div class="flex-1 overflow-auto">
            <ElTree
              ref="treeRef"
              :data="chapterDataRef"
              node-key="id"
              default-expand-all
              highlight-current
              :expand-on-click-node="false"
              :filter-node-method="filterNode"
              @node-click="nodeClick"
              draggable
              :allow-drop="
                (draggingNode, dropNode, type) => {
                  // 只允许在同级或父级下拖拽
                  return type === 'inner' || type === 'prev' || type === 'next';
                }
              "
              @node-drag-end="handleDragEnd"
            >
              <template #default="{ node, data }">
                <div class="flex w-full items-center justify-between">
                  <!-- 节点文本 -->
                  <span>{{ node.label }}</span>

                  <!-- 操作按钮 -->
                  <div
                    class="flex items-center space-x-1 opacity-0 transition-opacity hover:opacity-100"
                  >
                    <ElButton
                      type="primary"
                      size="small"
                      circle
                      @click.stop="addChapter(data)"
                      class="!h-6 !w-6 !p-0"
                      title="添加子章节"
                    >
                      <Plus class="!h-3 !w-3" />
                    </ElButton>
                    <ElButton
                      type="warning"
                      size="small"
                      circle
                      @click.stop="editChapter(data)"
                      class="!h-6 !w-6 !p-0"
                      title="编辑章节"
                    >
                      <Edit class="!h-3 !w-3" />
                    </ElButton>
                    <ElButton
                      type="danger"
                      size="small"
                      circle
                      @click.stop="deleteChapter(data)"
                      class="!h-6 !w-6 !p-0"
                      title="删除章节"
                    >
                      <Delete class="!h-3 !w-3" />
                    </ElButton>
                  </div>
                </div>
              </template>
            </ElTree>
          </div>
        </div>
      </template>

      <!-- 右侧内容显示区域 -->
      <div
        class="border-border bg-card mr-2 flex h-full flex-col rounded-[var(--radius)] border p-4"
      >
        <!-- 顶部操作栏 -->
        <div class="mb-4 flex items-center justify-between">
          <div class="flex items-center space-x-3">
            <h3 class="text-xl font-bold">
              {{ selectedChapterRef?.label || '主页' }}
            </h3>
            <div class="flex items-center space-x-1 text-sm text-gray-500">
              2025-07-21 18:01:38
              <ReadCount class="ml-2 size-4 text-blue-500" />
              <span class="text-blue-500">51</span>
            </div>
          </div>
          <div class="flex items-center space-x-2">
            <ElButton type="text" @click="openEditModal"> 编辑 </ElButton>
            <ElButton type="text" @click="openRemindModal"> 提醒 </ElButton>
            <!-- <ElButton type="text"> 历史 </ElButton> -->
            <ElButton type="text" @click="deleteKnowledge"> 删除 </ElButton>
          </div>
        </div>

        <!-- 内容显示区域 -->
        <div class="mb-4">
          <!-- 主页内容 -->
          <div
            v-if="selectedChapterRef?.id === 'home'"
            class="prose max-w-none"
          >
            <h2>编辑主页</h2>
            <p>
              此页面是知识库的主页，你可以点击右上角「编辑」，开始编辑主页内容，例如在主页中介绍知识库的内容。
            </p>

            <h2>新建文档</h2>
            <p>点击左侧「目录+」按钮，开始创建你的文档。</p>
          </div>

          <!-- 章节内容 -->
          <div v-else-if="selectedChapterRef" class="prose max-w-none">
            <p>
              {{
                selectedChapterRef.content || '暂无内容，点击编辑开始添加内容'
              }}
            </p>
          </div>

          <!-- 默认内容 -->
          <div v-else class="py-10 text-center text-gray-500">
            请选择左侧章节查看内容
          </div>
        </div>

        <!-- 评论区域 -->
        <div class="border-t pt-4">
          <h4 class="mb-3 font-bold">评论</h4>

          <!-- 评论列表 -->
          <div class="mb-4">
            <!-- 评论项 -->
            <div class="mb-4 rounded bg-gray-50 p-3">
              <div class="mb-2 flex items-center">
                <div
                  class="mr-2 flex h-8 w-8 items-center justify-center rounded-full bg-gray-200"
                >
                  <Camera class="h-4 w-4" />
                </div>
                <div class="font-medium">用户名</div>
                <div class="ml-2 text-xs text-gray-500">
                  2025-07-21 18:01:38
                </div>
              </div>
              <div class="mb-2">
                这是一条评论内容，用户可以在这里发表自己的看法和意见。
              </div>
              <!-- 评论图片 -->
              <div class="mb-2 flex space-x-2">
                <img
                  src="https://picsum.photos/80/80"
                  alt="评论图片"
                  class="h-20 w-20 rounded object-cover"
                />
                <img
                  src="https://picsum.photos/80/80"
                  alt="评论图片"
                  class="h-20 w-20 rounded object-cover"
                />
              </div>
              <!-- <div class="flex items-center text-sm text-gray-500">
                <span class="mr-4 cursor-pointer hover:text-blue-500"
                  >点赞 (5)</span
                >
                <span class="cursor-pointer hover:text-blue-500">回复</span>
              </div> -->
            </div>

            <!-- 评论项 -->
            <div class="mb-4 rounded bg-gray-50 p-3">
              <div class="mb-2 flex items-center">
                <div
                  class="mr-2 flex h-8 w-8 items-center justify-center rounded-full bg-gray-200"
                >
                  <Camera class="h-4 w-4" />
                </div>
                <div class="font-medium">用户名</div>
                <div class="ml-2 text-xs text-gray-500">
                  2025-07-21 17:45:22
                </div>
              </div>
              <div class="mb-2">
                这是另一条评论内容，用户可以在这里发表自己的看法和意见。
              </div>
              <!-- <div class="flex items-center text-sm text-gray-500">
                <span class="mr-4 cursor-pointer hover:text-blue-500"
                  >点赞 (3)</span
                >
                <span class="cursor-pointer hover:text-blue-500">回复</span>
              </div> -->
            </div>
          </div>

          <!-- 评论操作区域 -->
          <div class="flex flex-col space-y-3">
            <div class="flex space-x-3">
              <div
                class="flex h-8 w-8 items-center justify-center rounded-full bg-gray-200"
              >
                <Camera class="h-4 w-4" />
              </div>
              <div class="flex-1">
                <ElInput
                  v-model="commentContent"
                  type="textarea"
                  placeholder="写下您的评论..."
                  resize="none"
                  rows="3"
                />

                <!-- 上传图片区域 -->
                <div class="mt-2">
                  <!-- 使用ElUpload组件实现多图片上传 -->
                  <ElUpload
                    v-model:file-list="commentImages"
                    action="#"
                    accept=".jpg,.jpeg,.png,.gif"
                    list-type="picture-card"
                    show-file-list
                    :auto-upload="true"
                    :drag="false"
                    :limit="10"
                    :multiple="true"
                    :http-request="handleCommentImageUpload"
                    :on-remove="handleCommentImageRemove"
                    :on-preview="handleCommentImagePreview"
                    class="mb-2"
                  >
                    <div class="flex h-full w-full items-center justify-center">
                      <ElIcon class="el-upload__icon">
                        <Plus size="18" />
                      </ElIcon>
                    </div>
                  </ElUpload>
                </div>

                <!-- 评论按钮 -->
                <div class="mt-2 flex justify-end">
                  <ElButton type="primary" size="small" @click="submitComment">
                    评论
                  </ElButton>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 编辑抽屉组件 -->
      <EditDrawerComp />
      <!-- 提醒抽屉组件 -->
      <RemindDrawerComp />
    </ColPage>
  </div>
</template>

<style scoped lang="scss">
.knowledge-detail-container {
  display: flex;
  flex-direction: column;
  width: 100%;
  height: 100%;
}

// 自定义树节点样式
:deep(.el-tree-node__content) {
  padding-right: 8px;
}

::v-deep .el-upload--picture-card {
  --el-upload-picture-card-size: 148px;

  box-sizing: border-box;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  width: 60px;
  height: 60px;
  vertical-align: top;
  cursor: pointer;
  background-color: #fafafa;
  background-color: var(--el-fill-color-lighter);
  border: 1px dashed #cdd0d6;
  border: 1px dashed var(--el-border-color-darker);
  border-radius: 6px;
}
</style>
