<template>
  <div>
    <h1>交流社区</h1>
    
    <!-- 搜索和操作栏 -->
    <a-card style="margin-bottom: 16px;">
      <div style="display: flex; flex-wrap: wrap; gap: 16px; align-items: center;">
        <a-input v-model:value="searchKeyword" placeholder="输入标题、内容或作者" style="width: 300px;">
          <template #prefix>
            <span class="iconfont icon-sousuo"></span>
          </template>
        </a-input>
        
        <a-select v-model:value="categoryFilter" placeholder="分类" style="width: 120px;">
          <a-select-option value="">全部</a-select-option>
          <a-select-option value="experience">经验分享</a-select-option>
          <a-select-option value="question">问题咨询</a-select-option>
          <a-select-option value="notice">通知公告</a-select-option>
          <a-select-option value="activity">活动信息</a-select-option>
        </a-select>
        
        <a-select v-model:value="statusFilter" placeholder="状态" style="width: 100px;">
          <a-select-option value="">全部</a-select-option>
          <a-select-option value="normal">正常</a-select-option>
          <a-select-option value="hot">热门</a-select-option>
          <a-select-option value="top">置顶</a-select-option>
        </a-select>
        
        <a-range-picker v-model:value="dateRange" style="width: 300px;" />
        
        <a-button type="primary" @click="handleSearch" style="margin-left: auto;">
          <span class="iconfont icon-sousuo"></span> 搜索
        </a-button>
        
        <a-button type="default" @click="handleReset">重置</a-button>
        
        <a-button type="primary" @click="handlePublish">
          <span class="iconfont icon-fabu"></span> 发布帖子
        </a-button>
      </div>
    </a-card>
    
    <!-- 数据统计卡片 -->
    <a-row gutter={24} style="margin-bottom: 16px;">
      <a-col :span="6">
        <a-statistic title="总帖子数" :value="totalPosts" suffix="篇" />
    </a-col>
      <a-col :span="6">
        <a-statistic title="今日新增" :value="todayNewPosts" suffix="篇" :valueStyle="{ color: '#1890ff' }" />
  </a-col>
      <a-col :span="6">
        <a-statistic title="总评论数" :value="totalComments" suffix="条" :valueStyle="{ color: '#52c41a' }" />
 </a-col>
      <a-col :span="6">
        <a-statistic title="活跃用户" :value="activeUsers" suffix="人" :valueStyle="{ color: '#faad14' }" />
  </a-col>
    </a-row>
    
    <!-- 社区活跃度图表 -->
    <a-card title="社区活跃度趋势" style="margin-bottom: 16px;">
      <div style="height: 300px;" ref="activityChartRef"></div>
    </a-card>
    
    <!-- 热门标签 -->
    <a-card title="热门标签" style="margin-bottom: 16px;">
      <div style="display: flex; flex-wrap: wrap; gap: 12px;">
        <a-tag v-for="tag in hotTags" :key="tag.id" color="blue" @click="handleTagClick(tag.name)">
          {{ tag.name }} ({{ tag.count }})
        </a-tag>
      </div>
    </a-card>
    
    <!-- 帖子列表 -->
    <a-card>
      <a-table
        :columns="columns"
        :data-source="postList"
        :pagination="pagination"
        row-key="id"
        :row-selection="{ selectedRowKeys, onChange: onSelectChange }"
        :scroll="{ x: 'max-content' }"
      >
        <!-- 分类列 -->
        <template #bodyCell:category="{ record }">
          <a-tag :color="getCategoryColor(record.category)">{{ getCategoryText(record.category) }}</a-tag>
        </template>
        
        <!-- 状态列 -->
        <template #bodyCell:status="{ record }">
          <div style="display: flex; gap: 4px;">
            <a-tag v-if="record.status === 'hot'" color="red">热门</a-tag>
            <a-tag v-if="record.status === 'top'" color="orange">置顶</a-tag>
            <a-tag v-if="record.status === 'normal'" color="default">正常</a-tag>
          </div>
        </template>
        
        <!-- 帖子标题列 -->
        <template #bodyCell:title="{ record }">
          <div style="display: flex; align-items: center; gap: 8px;">
            <span>{{ record.title }}</span>
            <span v-if="record.isHot" class="hot-icon">🔥</span>
            <span v-if="record.isTop" class="top-icon">📌</span>
          </div>
        </template>
        
        <!-- 操作列 -->
        <template #bodyCell:action="{ record }">
          <div style="display: flex; gap: 8px;">
            <a-button size="small" @click="handleView(record)">查看</a-button>
            <a-button size="small" type="primary" @click="handleEdit(record)" v-if="record.authorId === currentUserId">编辑</a-button>
            <a-button size="small" danger @click="handleDelete(record.id)" v-if="record.authorId === currentUserId">删除</a-button>
            <a-button size="small" @click="handleSetHot(record.id)" v-if="record.status !== 'hot'">设为热门</a-button>
            <a-button size="small" @click="handleSetTop(record.id)" v-if="record.status !== 'top'">置顶</a-button>
          </div>
        </template>
      </a-table>
    </a-card>
    
    <!-- 发布/编辑帖子模态框 -->
    <a-modal
      v-model:open="isPublishEditModalOpen"
      title="发布/编辑帖子"
      :footer="null"
      width={800}
    >
      <a-form
        :model="currentPost"
        layout="vertical"
        style="max-width: 700px; margin: 0 auto;"
      >
        <a-form-item label="帖子标题" name="title" :rules="[{ required: true, message: '请输入帖子标题' }]">
          <a-input v-model:value="currentPost.title" placeholder="请输入帖子标题" />
        </a-form-item>
        
        <a-row gutter={24}>
          <a-col :span="12">
            <a-form-item label="帖子分类" name="category" :rules="[{ required: true, message: '请选择帖子分类' }]">
              <a-select v-model:value="currentPost.category" placeholder="请选择帖子分类">
                <a-select-option value="experience">经验分享</a-select-option>
                <a-select-option value="question">问题咨询</a-select-option>
                <a-select-option value="notice">通知公告</a-select-option>
                <a-select-option value="activity">活动信息</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="帖子标签" name="tags">
              <a-input v-model:value="currentPost.tags" placeholder="请输入标签，用逗号分隔" />
            </a-form-item>
          </a-col>
        </a-row>
        
        <a-form-item label="帖子内容" name="content" :rules="[{ required: true, message: '请输入帖子内容' }]">
          <div style="border: 1px solid #d9d9d9; border-radius: 6px;">
            <!-- 简单的富文本编辑器工具栏 -->
            <div style="padding: 8px; background-color: #f5f5f5; border-bottom: 1px solid #d9d9d9;">
              <a-button size="small" @click="insertBold" icon="bold" /> 加粗
              <a-button size="small" @click="insertItalic" icon="italic" style="margin-left: 8px;" /> 斜体
              <a-button size="small" @click="insertLink" icon="link" style="margin-left: 8px;" /> 链接
              <a-button size="small" @click="insertImage" icon="picture" style="margin-left: 8px;" /> 图片
              <a-button size="small" @click="insertList" icon="ordered-list" style="margin-left: 8px;" /> 列表
            </div>
            <!-- 内容输入区域 -->
            <a-textarea v-model:value="currentPost.content" placeholder="请输入帖子内容" :rows="12" style="border: none; border-radius: 0 0 6px 6px;" />
          </div>
        </a-form-item>
        
        <a-form-item label="上传附件">
          <a-upload
            name="file"
            :multiple="true"
            :showUploadList="true"
            :beforeUpload="beforeUpload"
            @change="handleUploadChange"
            accept=".jpg,.jpeg,.png,.pdf,.doc,.docx,.xls,.xlsx"
          >
            <a-button>
              <span class="iconfont icon-upload"></span> 选择文件
            </a-button>
          </a-upload>
        </a-form-item>
        
        <div style="display: flex; justify-content: flex-end; gap: 16px;">
          <a-button @click="isPublishEditModalOpen = false">取消</a-button>
          <a-button type="primary" @click="handleSavePost">保存并发布</a-button>
        </div>
      </a-form>
    </a-modal>
    
    <!-- 查看帖子详情模态框 -->
    <a-modal
      v-model:open="isViewModalOpen"
      title="帖子详情"
      :footer="null"
      width={900}
      class="post-detail-modal"
    >
      <div v-if="viewPost" class="post-detail">
        <div class="post-header">
          <h2>{{ viewPost.title }}</h2>
          <div class="post-meta">
            <span>作者: {{ viewPost.authorName }}</span>
            <span>发布时间: {{ viewPost.publishTime }}</span>
            <span>浏览量: {{ viewPost.views }}</span>
            <span>评论: {{ viewPost.commentCount }}</span>
            <span>点赞: {{ viewPost.likes }}</span>
          </div>
          <div class="post-tags" style="margin-top: 8px;">
            <a-tag v-for="tag in viewPost.tags" :key="tag" color="blue">{{ tag }}</a-tag>
          </div>
        </div>
        
        <div class="post-content" v-html="renderContent(viewPost.content)"></div>
        
        <!-- 附件列表 -->
        <div v-if="viewPost.attachments && viewPost.attachments.length > 0" class="attachments">
          <h4>附件：</h4>
          <a-upload-list
            :items="getUploadItems(viewPost.attachments)"
            :locale="{ removeFile: '删除', downloadFile: '下载' }"
            :showRemoveIcon="false"
            :showDownloadIcon="true"
          />
        </div>
        
        <!-- 点赞和评论操作 -->
        <div class="post-actions" style="margin-top: 24px; padding-top: 16px; border-top: 1px solid #f0f0f0;">
          <a-button type="primary" @click="handleLikePost(viewPost.id)" :icon="viewPost.isLiked ? 'like' : 'like-o'">
            {{ viewPost.isLiked ? '已点赞' : '点赞' }} ({{ viewPost.likes }})
          </a-button>
          <a-button @click="handleSharePost(viewPost.id)" style="margin-left: 16px;">
            <span class="iconfont icon-share-alt"></span> 分享
          </a-button>
        </div>
        
        <!-- 评论区域 -->
        <div class="comments-section" style="margin-top: 24px;">
          <h3>评论 ({{ viewPost.comments ? viewPost.comments.length : 0 }})</h3>
          
          <!-- 评论输入框 -->
          <div class="comment-input" style="margin-bottom: 24px;">
            <a-input.TextArea v-model:value="newComment" placeholder="写下你的评论..." :rows="3" />
            <div style="text-align: right; margin-top: 8px;">
              <a-button type="primary" @click="handleSubmitComment">发表评论</a-button>
            </div>
          </div>
          
          <!-- 评论列表 -->
          <div class="comments-list">
            <div v-for="comment in viewPost.comments" :key="comment.id" class="comment-item">
              <div class="comment-header">
                <span class="comment-author">{{ comment.authorName }}</span>
                <span class="comment-time">{{ comment.commentTime }}</span>
              </div>
              <div class="comment-content">{{ comment.content }}</div>
              <div class="comment-actions">
                <a @click="handleReplyComment(comment.id)">回复</a>
                <a @click="handleLikeComment(comment.id)" style="margin-left: 16px;">
                  {{ comment.isLiked ? '已点赞' : '点赞' }} ({{ comment.likes }})
                </a>
              </div>
            </div>
          </div>
        </div>
      </div>
    </a-modal>
    
    <!-- 确认对话框 -->
    <a-popconfirm
      v-model:open="isConfirmModalOpen"
      title="确认操作"
      :description="confirmMessage"
      ok-text="确认"
      cancel-text="取消"
      @confirm="handleConfirmAction"
    >
      <template #reference>
        <!-- 这里是空的，通过其他按钮触发 -->
      </template>
    </a-popconfirm>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import * as echarts from 'echarts'

// 搜索条件
const searchKeyword = ref('')
const categoryFilter = ref('')
const statusFilter = ref('')
const dateRange = ref([])

// 统计数据
const totalPosts = ref(2589)
const todayNewPosts = ref(45)
const totalComments = ref(12546)
const activeUsers = ref(1234)

// 分页配置
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total) => `共 ${total} 条记录`
})

// 选中的行
const selectedRowKeys = ref([])
const onSelectChange = (newSelectedRowKeys) => {
  selectedRowKeys.value = newSelectedRowKeys
}

// 图表引用
const activityChartRef = ref(null)

// 模态框状态
const isPublishEditModalOpen = ref(false)
const isViewModalOpen = ref(false)
const isConfirmModalOpen = ref(false)
const confirmMessage = ref('')
const confirmAction = ref('')
const confirmTargetId = ref('')

// 当前用户ID（模拟）
const currentUserId = ref('1')

// 当前编辑的帖子
const currentPost = reactive({
  id: '',
  title: '',
  category: 'experience',
  tags: '',
  content: '',
  authorId: currentUserId.value,
  authorName: '管理员',
  status: 'normal',
  publishTime: '',
  views: 0,
  commentCount: 0,
  likes: 0,
  isHot: false,
  isTop: false,
  attachments: []
})

// 查看的帖子
const viewPost = ref(null)

// 上传文件列表
const uploadFileList = ref([])

// 新评论
const newComment = ref('')

// 热门标签
const hotTags = ref([
  { id: '1', name: '养殖技术', count: 1254 },
  { id: '2', name: '饲料配方', count: 897 },
  { id: '3', name: '疾病防治', count: 1567 },
  { id: '4', name: '市场分析', count: 678 },
  { id: '5', name: '品种选育', count: 456 },
  { id: '6', name: '养殖设备', count: 342 },
  { id: '7', name: '政策解读', count: 567 },
  { id: '8', name: '经验分享', count: 1023 }
])

// 帖子列表数据
const postList = ref([
  {
    id: '1',
    title: '【经验分享】如何提高牛的产奶量和品质',
    category: 'experience',
    status: 'hot',
    authorId: '2',
    authorName: '李养牛',
    publishTime: '2023-10-01 10:30',
    views: 1254,
    commentCount: 89,
    likes: 234,
    isHot: true,
    isTop: false,
    tags: ['产奶量', '品质提升', '经验分享']
  },
  {
    id: '2',
    title: '【紧急求助】牛群出现腹泻症状，应该如何处理？',
    category: 'question',
    status: 'normal',
    authorId: '3',
    authorName: '王养殖',
    publishTime: '2023-10-02 09:15',
    views: 897,
    commentCount: 123,
    likes: 45,
    isHot: false,
    isTop: false,
    tags: ['疾病防治', '腹泻', '求助']
  },
  {
    id: '3',
    title: '【通知公告】关于开展2023年养牛技术培训的通知',
    category: 'notice',
    status: 'top',
    authorId: '1',
    authorName: '管理员',
    publishTime: '2023-10-03 14:20',
    views: 2345,
    commentCount: 67,
    likes: 34,
    isHot: false,
    isTop: true,
    tags: ['技术培训', '通知']
  },
  {
    id: '4',
    title: '【市场分析】2023年下半年牛肉市场价格走势预测',
    category: 'experience',
    status: 'hot',
    authorId: '4',
    authorName: '张分析',
    publishTime: '2023-10-04 16:45',
    views: 1678,
    commentCount: 98,
    likes: 156,
    isHot: true,
    isTop: false,
    tags: ['市场分析', '价格走势', '预测']
  },
  {
    id: '5',
    title: '【活动信息】首届养牛产业博览会将于下月在我市举办',
    category: 'activity',
    status: 'normal',
    authorId: '5',
    authorName: '刘活动',
    publishTime: '2023-10-05 11:30',
    views: 987,
    commentCount: 56,
    likes: 23,
    isHot: false,
    isTop: false,
    tags: ['博览会', '活动', '产业']
  },
  {
    id: '6',
    title: '【经验分享】自制发酵饲料的配方与制作方法',
    category: 'experience',
    status: 'normal',
    authorId: '6',
    authorName: '陈饲料',
    publishTime: '2023-10-06 08:45',
    views: 1456,
    commentCount: 78,
    likes: 189,
    isHot: false,
    isTop: false,
    tags: ['发酵饲料', '配方', '制作方法']
  },
  {
    id: '7',
    title: '【问题咨询】牛舍建设的最佳朝向和通风设计？',
    category: 'question',
    status: 'normal',
    authorId: '7',
    authorName: '赵建设',
    publishTime: '2023-10-07 13:20',
    views: 765,
    commentCount: 45,
    likes: 12,
    isHot: false,
    isTop: false,
    tags: ['牛舍建设', '通风设计', '咨询']
  },
  {
    id: '8',
    title: '【政策解读】最新养牛补贴政策详解与申请指南',
    category: 'experience',
    status: 'hot',
    authorId: '8',
    authorName: '孙政策',
    publishTime: '2023-10-08 15:10',
    views: 2134,
    commentCount: 123,
    likes: 278,
    isHot: true,
    isTop: false,
    tags: ['政策解读', '补贴政策', '申请指南']
  },
  {
    id: '9',
    title: '【经验分享】提高犊牛存活率的关键技术措施',
    category: 'experience',
    status: 'normal',
    authorId: '9',
    authorName: '周犊牛',
    publishTime: '2023-10-09 09:30',
    views: 1098,
    commentCount: 67,
    likes: 145,
    isHot: false,
    isTop: false,
    tags: ['犊牛', '存活率', '技术措施']
  },
  {
    id: '10',
    title: '【通知公告】关于加强动物防疫工作的紧急通知',
    category: 'notice',
    status: 'top',
    authorId: '1',
    authorName: '管理员',
    publishTime: '2023-10-10 10:00',
    views: 1876,
    commentCount: 89,
    likes: 56,
    isHot: false,
    isTop: true,
    tags: ['动物防疫', '紧急通知']
  }
])

// 表格列定义
const columns = [
  {
    title: '帖子标题',
    dataIndex: 'title',
    key: 'title',
    width: 400
  },
  {
    title: '分类',
    dataIndex: 'category',
    key: 'category',
    width: 100
  },
  {
    title: '作者',
    dataIndex: 'authorName',
    key: 'authorName',
    width: 100
  },
  {
    title: '发布时间',
    dataIndex: 'publishTime',
    key: 'publishTime',
    width: 150
  },
  {
    title: '浏览量',
    dataIndex: 'views',
    key: 'views',
    width: 80,
    sorter: (a, b) => a.views - b.views
  },
  {
    title: '评论数',
    dataIndex: 'commentCount',
    key: 'commentCount',
    width: 80,
    sorter: (a, b) => a.commentCount - b.commentCount
  },
  {
    title: '点赞数',
    dataIndex: 'likes',
    key: 'likes',
    width: 80,
    sorter: (a, b) => a.likes - b.likes
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
    width: 100
  },
  {
    title: '操作',
    key: 'action',
    width: 200,
    fixed: 'right'
  }
]

// 获取分类文本
const getCategoryText = (category) => {
  switch (category) {
    case 'experience': return '经验分享'
    case 'question': return '问题咨询'
    case 'notice': return '通知公告'
    case 'activity': return '活动信息'
    default: return category
  }
}

// 获取分类颜色
const getCategoryColor = (category) => {
  switch (category) {
    case 'experience': return 'blue'
    case 'question': return 'orange'
    case 'notice': return 'red'
    case 'activity': return 'green'
    default: return 'default'
  }
}

// 搜索处理
const handleSearch = () => {
  console.log('搜索条件:', {
    keyword: searchKeyword.value,
    category: categoryFilter.value,
    status: statusFilter.value,
    dateRange: dateRange.value
  })
  // 这里应该有实际的搜索逻辑
  // 模拟搜索后的总数
  pagination.total = postList.value.length
}

// 重置处理
const handleReset = () => {
  searchKeyword.value = ''
  categoryFilter.value = ''
  statusFilter.value = ''
  dateRange.value = []
  selectedRowKeys.value = []
}

// 发布帖子
const handlePublish = () => {
  // 重置当前帖子数据
  Object.assign(currentPost, {
    id: '',
    title: '',
    category: 'experience',
    tags: '',
    content: '',
    authorId: currentUserId.value,
    authorName: '管理员',
    status: 'normal',
    publishTime: '',
    views: 0,
    commentCount: 0,
    likes: 0,
    isHot: false,
    isTop: false,
    attachments: []
  })
  uploadFileList.value = []
  isPublishEditModalOpen.value = true
}

// 编辑帖子
const handleEdit = (record) => {
  // 复制记录数据到当前帖子
  Object.assign(currentPost, JSON.parse(JSON.stringify(record)))
  isPublishEditModalOpen.value = true
}

// 查看帖子
const handleView = (record) => {
  // 模拟获取帖子详情，包括评论等
  const postDetail = {
    ...JSON.parse(JSON.stringify(record)),
    content: `
      <p>这是帖子的详细内容。在实际应用中，这里会显示完整的帖子内容，包括富文本格式。</p>
      <h3>主要内容</h3>
      <p>1. 这里是第一点内容...</p>
      <p>2. 这里是第二点内容...</p>
      <p>3. 这里是第三点内容...</p>
      <h3>注意事项</h3>
      <ul>
        <li>注意事项一</li>
        <li>注意事项二</li>
        <li>注意事项三</li>
      </ul>
      <p>希望这些内容对大家有所帮助！</p>
    `,
    attachments: ['附件1.pdf', '附件2.jpg'],
    comments: [
      {
        id: '1',
        authorName: '评论用户1',
        commentTime: '2023-10-01 11:00',
        content: '感谢分享，非常实用！',
        likes: 10,
        isLiked: false
      },
      {
        id: '2',
        authorName: '评论用户2',
        commentTime: '2023-10-01 12:30',
        content: '我有个问题想请教一下...',
        likes: 5,
        isLiked: false
      },
      {
        id: '3',
        authorName: '评论用户3',
        commentTime: '2023-10-01 14:15',
        content: '按照你的方法试了一下，效果不错！',
        likes: 8,
        isLiked: false
      }
    ],
    isLiked: false
  }
  viewPost.value = postDetail
  newComment.value = ''
  isViewModalOpen.value = true
}

// 删除帖子 - 弹出确认对话框
const handleDelete = (id) => {
  confirmMessage.value = '确定要删除该帖子吗？'
  confirmAction.value = 'delete'
  confirmTargetId.value = id
  isConfirmModalOpen.value = true
}

// 设为热门 - 弹出确认对话框
const handleSetHot = (id) => {
  confirmMessage.value = '确定要将该帖子设为热门吗？'
  confirmAction.value = 'setHot'
  confirmTargetId.value = id
  isConfirmModalOpen.value = true
}

// 置顶 - 弹出确认对话框
const handleSetTop = (id) => {
  confirmMessage.value = '确定要将该帖子置顶吗？'
  confirmAction.value = 'setTop'
  confirmTargetId.value = id
  isConfirmModalOpen.value = true
}

// 确认操作
const handleConfirmAction = () => {
  if (confirmAction.value === 'delete') {
    console.log('删除帖子:', confirmTargetId.value)
    // 这里应该有实际的删除逻辑
    // 模拟删除成功
    alert(`成功删除帖子ID: ${confirmTargetId.value}`)
  } else if (confirmAction.value === 'setHot') {
    console.log('设为热门:', confirmTargetId.value)
    // 这里应该有实际的设为热门逻辑
    // 模拟设置成功
    alert('成功设为热门帖子')
  } else if (confirmAction.value === 'setTop') {
    console.log('置顶:', confirmTargetId.value)
    // 这里应该有实际的置顶逻辑
    // 模拟设置成功
    alert('成功置顶帖子')
  }
  isConfirmModalOpen.value = false
}

// 保存帖子
const handleSavePost = () => {
  console.log('保存帖子:', currentPost)
  // 这里应该有实际的保存逻辑
  // 模拟保存成功
  isPublishEditModalOpen.value = false
  alert('帖子发布成功')
}

// 标签点击
const handleTagClick = (tagName) => {
  searchKeyword.value = tagName
  handleSearch()
}

// 点赞帖子
const handleLikePost = (postId) => {
  if (viewPost.value && viewPost.value.id === postId) {
    viewPost.value.isLiked = !viewPost.value.isLiked
    viewPost.value.likes += viewPost.value.isLiked ? 1 : -1
  }
}

// 分享帖子
const handleSharePost = (postId) => {
  alert('分享功能开发中...')
}

// 提交评论
const handleSubmitComment = () => {
  if (!newComment.value.trim()) {
    alert('评论内容不能为空')
    return
  }
  
  if (viewPost.value) {
    const newCommentObj = {
      id: Date.now().toString(),
      authorName: '当前用户',
      commentTime: new Date().toLocaleString('zh-CN'),
      content: newComment.value,
      likes: 0,
      isLiked: false
    }
    
    if (!viewPost.value.comments) {
      viewPost.value.comments = []
    }
    viewPost.value.comments.unshift(newCommentObj)
    viewPost.value.commentCount++
    newComment.value = ''
  }
}

// 回复评论
const handleReplyComment = (commentId) => {
  const comment = viewPost.value.comments.find(c => c.id === commentId)
  if (comment) {
    newComment.value = `回复 @${comment.authorName}: `
    // 滚动到评论输入框
    setTimeout(() => {
      const inputElement = document.querySelector('.comment-input textarea')
      if (inputElement) {
        inputElement.focus()
      }
    }, 100)
  }
}

// 点赞评论
const handleLikeComment = (commentId) => {
  const comment = viewPost.value.comments.find(c => c.id === commentId)
  if (comment) {
    comment.isLiked = !comment.isLiked
    comment.likes += comment.isLiked ? 1 : -1
  }
}

// 渲染内容（简单的HTML渲染）
const renderContent = (content) => {
  return content
}

// 获取上传文件项
const getUploadItems = (files) => {
  return files.map((file, index) => ({
    uid: `${index}`,
    name: file,
    status: 'done',
    url: `#${file}`,
  }))
}

// 文件上传前处理
const beforeUpload = (file) => {
  const isLt20M = file.size / 1024 / 1024 < 20
  if (!isLt20M) {
    alert('文件大小不能超过 20MB!')
    return Upload.LIST_IGNORE
  }
  return false // 阻止自动上传
}

// 文件上传变化处理
const handleUploadChange = ({ fileList }) => {
  uploadFileList.value = fileList
}

// 富文本编辑器工具函数
const insertBold = () => {
  insertText('**', '**')
}

const insertItalic = () => {
  insertText('_', '_')
}

const insertLink = () => {
  const url = prompt('请输入链接地址:')
  if (url) {
    insertText(`[链接文本](`, `)`)
  }
}

const insertImage = () => {
  const url = prompt('请输入图片URL:')
  if (url) {
    insertText(`![图片描述](`, `)`)
  }
}

const insertList = () => {
  insertText('- ', '\n')
}

const insertText = (before, after) => {
  const textarea = document.querySelector('textarea[v-model*="currentPost.content"]')
  if (textarea) {
    const start = textarea.selectionStart
    const end = textarea.selectionEnd
    const text = textarea.value
    const newText = text.substring(0, start) + before + text.substring(start, end) + after + text.substring(end)
    currentPost.content = newText
    
    // 设置光标位置
    setTimeout(() => {
      textarea.focus()
      textarea.selectionStart = textarea.selectionEnd = start + before.length
    }, 0)
  }
}

// 初始化活跃度趋势图表
const initActivityChart = () => {
  if (!activityChartRef.value) return
  
  const chart = echarts.init(activityChartRef.value)
  
  const option = {
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      data: ['帖子数', '评论数', '活跃用户数']
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月']
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: '帖子数',
        type: 'line',
        stack: 'Total',
        data: [120, 132, 101, 134, 90, 120, 130, 125, 110, 120, 115, 130]
      },
      {
        name: '评论数',
        type: 'line',
        stack: 'Total',
        data: [500, 550, 480, 600, 450, 520, 580, 560, 510, 550, 530, 590]
      },
      {
        name: '活跃用户数',
        type: 'line',
        stack: 'Total',
        data: [800, 850, 820, 880, 830, 860, 890, 870, 840, 880, 860, 900]
      }
    ]
  }
  
  chart.setOption(option)
  
  window.addEventListener('resize', () => {
    chart.resize()
  })
}

// 组件挂载时初始化图表
onMounted(() => {
  setTimeout(() => {
    initActivityChart()
  }, 100)
})

// 初始化数据
pagination.total = postList.value.length
</script>

<style scoped>
  .post-detail-modal .ant-modal-body {
    max-height: 70vh;
    overflow-y: auto;
  }
  
  .post-detail {
    padding: 8px;
  }
  
  .post-header h2 {
    margin-bottom: 12px;
    color: #333;
  }
  
  .post-meta {
    display: flex;
    gap: 24px;
    color: #666;
    font-size: 14px;
    margin-bottom: 16px;
  }
  
  .post-content {
    padding: 16px 0;
    line-height: 1.8;
    color: #333;
  }
  
  .post-content h3 {
    margin: 16px 0 8px 0;
    color: #333;
  }
  
  .post-content p {
    margin: 8px 0;
  }
  
  .post-content ul {
    padding-left: 24px;
  }
  
  .post-content li {
    margin: 4px 0;
  }
  
  .attachments {
    margin-top: 24px;
    padding-top: 16px;
    border-top: 1px solid #f0f0f0;
  }
  
  .attachments h4 {
    margin-bottom: 12px;
    color: #333;
  }
  
  .comments-section h3 {
    margin-bottom: 16px;
    color: #333;
  }
  
  .comment-item {
    padding: 16px 0;
    border-bottom: 1px solid #f0f0f0;
  }
  
  .comment-item:last-child {
    border-bottom: none;
  }
  
  .comment-header {
    display: flex;
    justify-content: space-between;
    margin-bottom: 8px;
  }
  
  .comment-author {
    font-weight: bold;
    color: #333;
  }
  
  .comment-time {
    color: #999;
    font-size: 14px;
  }
  
  .comment-content {
    margin-bottom: 8px;
    color: #333;
    line-height: 1.6;
  }
  
  .comment-actions {
    font-size: 14px;
  }
  
  .comment-actions a {
    color: #1890ff;
    cursor: pointer;
  }
  
  .hot-icon, .top-icon {
    font-size: 14px;
  }
</style>