<template>
  <div class="knowledge-container">
    <!-- 顶部背景图区域 -->
    <div class="knowledge-cover">
      <img :src="coverImage" alt="封面图" class="cover-image">
      <div class="title-area">
        <h1 class="page-title">知识库</h1>
        <p class="page-subtitle">探索您感兴趣的领域，获取专业知识</p>
      </div>

      <!-- 搜索框 -->
      <div class="search-box">
        <el-input
          v-model="searchQuery"
          placeholder="搜索知识库内容..."
          prefix-icon="el-icon-search"
          clearable
          @keyup.enter="searchContent"
        ></el-input>
      </div>
    </div>

    <!-- 知识库内容区域 -->
    <div class="knowledge-content">
      <!-- 分类标签 -->
      <div class="category-tabs">
        <el-tabs v-model="activeCategory" @tab-click="handleCategoryChange">
          <el-tab-pane v-for="category in categories" :key="category.id" :label="category.name" :name="category.id"></el-tab-pane>
        </el-tabs>
      </div>

      <!-- 知识条目列表 -->
      <div class="knowledge-list">
        <div v-for="item in filteredKnowledgeItems" :key="item.id" class="knowledge-item">
          <!-- 知识条目头部 -->
          <div class="item-header">
            <div class="category-tag" :style="{backgroundColor: getCategoryColor(item.categoryId)}">
              {{ getCategoryName(item.categoryId) }}
            </div>
            <span class="item-date">{{ item.date }}</span>
          </div>

          <!-- 知识条目标题 -->
          <h2 class="item-title">{{ item.title }}</h2>

          <!-- 知识条目内容 -->
          <div class="item-content" v-html="item.content"></div>

          <!-- 知识条目附件 -->
          <div class="item-attachments" v-if="item.attachments && item.attachments.length > 0">
            <div class="attachment-title">
              <i class="el-icon-paperclip"></i>
              <span>附件</span>
            </div>
            <div class="attachment-list">
              <div v-for="(attachment, index) in item.attachments" :key="index" class="attachment-item">
                <i :class="getAttachmentIcon(attachment.type)"></i>
                <span class="attachment-name">{{ attachment.name }}</span>
                <el-button type="text" size="mini" @click="downloadAttachment(attachment)">
                  <i class="el-icon-download"></i>
                </el-button>
              </div>
            </div>
          </div>

          <!-- 知识条目图片 -->
          <div class="item-images" v-if="item.images && item.images.length > 0">
            <template v-if="item.images.length === 1">
              <div class="single-image-container">
                <el-image
                  :src="item.images[0]"
                  :preview-src-list="item.images"
                  fit="cover"
                  class="single-image"
                ></el-image>
              </div>
            </template>
            <template v-else>
              <div class="image-grid" :class="`grid-count-${item.images.length > 4 ? 'many' : item.images.length}`">
                <div v-for="(img, index) in item.images" :key="index" class="grid-image-container">
                  <el-image
                    :src="img"
                    :preview-src-list="item.images"
                    fit="cover"
                    class="grid-image"
                  ></el-image>
                </div>
              </div>
            </template>
          </div>

          <!-- 底部操作区 -->
          <div class="item-footer">
            <div class="action-btn" @click="handleFavorite(item)">
              <i :class="['el-icon-star-off', { 'favorited': item.isFavorited }]"></i>
              <span>{{ item.isFavorited ? '取消收藏' : '收藏' }}</span>
            </div>
            <div class="action-btn" @click="handleShare(item)">
              <i class="el-icon-share"></i>
              <span>分享</span>
            </div>
            <div class="more-actions" @click="showActionsMenu(item, $event)">
              <i class="el-icon-more"></i>
            </div>
            <div class="actions-menu" v-if="item.showActions">
              <div class="menu-item" @click="handlePrint(item)">
                <i class="el-icon-printer"></i>
                <span>打印</span>
              </div>
              <div class="menu-item" @click="handleReport(item)">
                <i class="el-icon-warning-outline"></i>
                <span>报告问题</span>
              </div>
            </div>
          </div>
        </div>

        <!-- 无内容提示 -->
        <div class="no-content" v-if="filteredKnowledgeItems.length === 0">
          <i class="el-icon-info-circle"></i>
          <p>没有找到相关内容</p>
        </div>
      </div>
    </div>

    <!-- 回到顶部 -->
    <el-backtop></el-backtop>

    <!-- 分享对话框 -->
    <el-dialog
      title="分享知识"
      v-model="shareDialogVisible"
      width="90%"
      custom-class="share-dialog"
    >
      <div class="share-options">
        <div class="share-option" v-for="option in shareOptions" :key="option.id" @click="handleShareOption(option)">
          <i :class="option.icon"></i>
          <span>{{ option.name }}</span>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    return {
      coverImage: require('@/assets/user/1.jpg'),
      searchQuery: '',
      activeCategory: 'all',
      shareDialogVisible: false,
      selectedItem: null,
      categories: [
        { id: 'all', name: '全部', color: '#409EFF' },
        { id: 'tech', name: '技术', color: '#67C23A' },
        { id: 'business', name: '商业', color: '#E6A23C' },
        { id: 'design', name: '设计', color: '#F56C6C' },
        { id: 'health', name: '健康', color: '#909399' }
      ],
      knowledgeItems: [
        {
          id: 1,
          categoryId: 'tech',
          title: 'Vue.js 3.0 核心特性解析',
          content: '本文详细介绍了Vue.js 3.0的核心特性，包括Composition API、Teleport、Fragments等新功能，以及性能优化方面的提升。使用Vue 3.0可以让您的应用获得更好的性能和开发体验。',
          date: '2023-05-15',
          images: [require('@/assets/user/1.jpg')],
          attachments: [
            { name: 'Vue3教程.pdf', type: 'pdf', url: '#' },
            { name: 'Demo代码.zip', type: 'zip', url: '#' }
          ],
          isFavorited: false,
          showActions: false
        },
        {
          id: 2,
          categoryId: 'business',
          title: '企业数字化转型策略',
          content: '数字化转型已成为企业发展的必经之路。本文分析了数字化转型的关键步骤、常见挑战和成功案例，为企业提供了实用的转型策略指南。',
          date: '2023-05-10',
          images: [
            require('@/assets/user/1.jpg'),
            require('@/assets/user/1.jpg')
          ],
          attachments: [
            { name: '数字化转型白皮书.docx', type: 'word', url: '#' }
          ],
          isFavorited: true,
          showActions: false
        },
        {
          id: 3,
          categoryId: 'design',
          title: 'UI/UX设计趋势2023',
          content: '2023年的UI/UX设计趋势呈现多样化发展。本文探讨了包括微互动、3D元素、黑暗模式优化、声音UI等在内的主要设计趋势，以及它们如何影响用户体验。',
          date: '2023-04-28',
          images: [
            require('@/assets/user/1.jpg'),
            require('@/assets/user/1.jpg'),
            require('@/assets/user/1.jpg')
          ],
          attachments: [],
          isFavorited: false,
          showActions: false
        },
        {
          id: 4,
          categoryId: 'health',
          title: '远程工作与心理健康',
          content: '长期远程工作可能对心理健康产生影响。本文提供了一系列保持心理健康的实用建议，包括建立工作常规、设置专用工作空间、定期休息等策略。',
          date: '2023-04-15',
          images: [],
          attachments: [
            { name: '远程工作健康指南.pdf', type: 'pdf', url: '#' }
          ],
          isFavorited: false,
          showActions: false
        },
        {
          id: 5,
          categoryId: 'tech',
          title: '区块链技术在供应链中的应用',
          content: '区块链技术为供应链管理带来了革命性变化。本文探讨了区块链如何提升供应链的透明度、可追溯性和效率，并分析了实际应用案例。',
          date: '2023-03-22',
          images: [require('@/assets/user/1.jpg')],
          attachments: [],
          isFavorited: true,
          showActions: false
        }
      ],
      shareOptions: [
        { id: 'wechat', name: '微信', icon: 'el-icon-chat-dot-round' },
        { id: 'weibo', name: '微博', icon: 'el-icon-chat-line-round' },
        { id: 'link', name: '复制链接', icon: 'el-icon-link' },
        { id: 'qrcode', name: '二维码', icon: 'el-icon-picture-outline-round' }
      ]
    }
  },
  computed: {
    filteredKnowledgeItems () {
      // 先根据分类筛选
      let result = this.knowledgeItems
      if (this.activeCategory !== 'all') {
        result = result.filter(item => item.categoryId === this.activeCategory)
      }

      // 再根据搜索关键词筛选
      if (this.searchQuery) {
        const query = this.searchQuery.toLowerCase()
        result = result.filter(item =>
          item.title.toLowerCase().includes(query) ||
          item.content.toLowerCase().includes(query)
        )
      }

      return result
    }
  },
  methods: {
    getCategoryName (categoryId) {
      const category = this.categories.find(c => c.id === categoryId)
      return category ? category.name : '未分类'
    },
    getCategoryColor (categoryId) {
      const category = this.categories.find(c => c.id === categoryId)
      return category ? category.color : '#909399'
    },
    getAttachmentIcon (type) {
      const icons = {
        pdf: 'el-icon-document',
        word: 'el-icon-document-checked',
        excel: 'el-icon-document',
        zip: 'el-icon-folder',
        image: 'el-icon-picture',
        video: 'el-icon-video-camera',
        audio: 'el-icon-headset'
      }
      return icons[type] || 'el-icon-document'
    },
    handleCategoryChange () {
      // 切换分类时滚动到顶部
      window.scrollTo(0, 0)
    },
    searchContent () {
      // 搜索内容
      console.log('搜索关键词:', this.searchQuery)
    },
    handleFavorite (item) {
      item.isFavorited = !item.isFavorited
      this.$message({
        message: item.isFavorited ? '已添加到收藏' : '已取消收藏',
        type: 'success',
        duration: 1500
      })
    },
    handleShare (item) {
      this.selectedItem = item
      this.shareDialogVisible = true
    },
    handleShareOption (option) {
      this.$message({
        message: `通过${option.name}分享成功`,
        type: 'success',
        duration: 1500
      })
      this.shareDialogVisible = false
    },
    showActionsMenu (item, event) {
      // 阻止事件传播到document，避免立即触发关闭
      event.stopPropagation()

      // 关闭其他所有条目的操作菜单
      this.knowledgeItems.forEach(i => {
        if (i.id !== item.id) {
          i.showActions = false
        }
      })
      // 切换当前条目的操作菜单显示状态
      item.showActions = !item.showActions
    },
    closeAllActionMenus () {
      this.knowledgeItems.forEach(item => {
        item.showActions = false
      })
    },
    handlePrint (item) {
      console.log('打印:', item.title)
      item.showActions = false
      this.$message({
        message: '准备打印...',
        type: 'info',
        duration: 1500
      })
    },
    handleReport (item) {
      console.log('报告问题:', item.title)
      item.showActions = false
      this.$message({
        message: '已提交问题报告，感谢您的反馈',
        type: 'success',
        duration: 1500
      })
    },
    downloadAttachment (attachment) {
      console.log('下载附件:', attachment.name)
      this.$message({
        message: `开始下载: ${attachment.name}`,
        type: 'success',
        duration: 1500
      })
    }
  },
  mounted () {
    // 添加document点击事件监听器，用于点击页面其他区域时关闭操作菜单
    document.addEventListener('click', this.closeAllActionMenus)
  },
  beforeUnmount () {
    // 移除事件监听器
    document.removeEventListener('click', this.closeAllActionMenus)
  }
}
</script>

<style scoped>
.knowledge-container {
  min-height: 100vh;
  background-color: #f7f7f7;
  width: 100%;
}

.knowledge-cover {
  position: relative;
  height: 45vh;
  min-height: 320px;
  max-height: 550px;
  overflow: hidden;
  background-color: #000;
  width: 100%;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
}

.cover-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  opacity: 0.8;
  position: absolute;
  top: 0;
  left: 0;
  z-index: 0;
  object-position: center top;
}

.search-box {
  position: absolute;
  bottom: 60px;
  left: 50%;
  transform: translateX(-50%);
  width: 80%;
  max-width: 650px;
  z-index: 2;
}

.search-box .el-input {
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.25);
}

.search-box .el-input >>> .el-input__inner {
  height: 50px;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  font-size: 16px;
  padding-left: 40px;
}

.knowledge-cover::after {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient(rgba(0,0,0,0.3), rgba(0,0,0,0.6));
  z-index: 1;
}

.title-area {
  position: absolute;
  left: 0;
  top: 35%;
  width: 100%;
  text-align: center;
  color: #fff;
  z-index: 2;
}

.page-title {
  font-size: 36px;
  font-weight: 600;
  margin: 0;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.5);
  letter-spacing: 2px;
}

.page-subtitle {
  font-size: 18px;
  margin-top: 10px;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.5);
  max-width: 80%;
  margin-left: auto;
  margin-right: auto;
}

.knowledge-content {
  padding: 50px 0 30px;
  width: 100%;
  max-width: 960px;
  margin: 0 auto;
  position: relative;
  z-index: 1;
}

.category-tabs {
  margin-bottom: 20px;
}

.category-tabs >>> .el-tabs__nav-wrap::after {
  height: 1px;
  background-color: #e8e8e8;
}

.category-tabs >>> .el-tabs__active-bar {
  height: 3px;
  border-radius: 1.5px;
}

.category-tabs >>> .el-tabs__item {
  font-size: 16px;
  padding: 0 25px;
}

.knowledge-list {
  margin-top: 30px;
}

.knowledge-item {
  background-color: #fff;
  padding: 25px;
  margin-bottom: 20px;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.item-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.category-tag {
  display: inline-block;
  padding: 3px 10px;
  border-radius: 4px;
  color: #fff;
  font-size: 12px;
  font-weight: 500;
}

.item-date {
  color: #999;
  font-size: 14px;
}

.item-title {
  margin-top: 0;
  margin-bottom: 15px;
  font-size: 20px;
  font-weight: 600;
  color: #333;
  line-height: 1.4;
}

.item-content {
  color: #666;
  line-height: 1.6;
  margin-bottom: 20px;
  font-size: 15px;
}

.item-attachments {
  margin-bottom: 20px;
  background-color: #f9f9f9;
  padding: 15px;
  border-radius: 8px;
}

.attachment-title {
  display: flex;
  align-items: center;
  color: #666;
  font-size: 15px;
  margin-bottom: 10px;
}

.attachment-title i {
  margin-right: 5px;
}

.attachment-list {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.attachment-item {
  display: flex;
  align-items: center;
  padding: 8px 15px;
  background-color: #fff;
  border-radius: 4px;
  border: 1px solid #eee;
}

.attachment-item i {
  margin-right: 10px;
  color: #666;
}

.attachment-name {
  flex: 1;
  color: #333;
  font-size: 14px;
}

.item-images {
  margin-bottom: 20px;
  width: 100%;
}

.single-image-container {
  width: 100%;
  display: flex;
  justify-content: center;
  margin-bottom: 15px;
}

.single-image {
  max-width: 100%;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  max-height: 400px;
  object-fit: contain;
}

.image-grid {
  display: grid;
  gap: 10px;
  width: 100%;
}

.grid-count-2 {
  grid-template-columns: repeat(2, 1fr);
}

.grid-count-3 {
  grid-template-columns: repeat(3, 1fr);
}

.grid-count-4, .grid-count-many {
  grid-template-columns: repeat(2, 1fr);
}

.grid-image-container {
  aspect-ratio: 1 / 1;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.grid-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.item-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-top: 15px;
  border-top: 1px solid #f0f0f0;
  position: relative;
}

.action-btn {
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 8px 15px;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.2s;
  color: #666;
}

.action-btn:hover {
  background-color: #f5f5f5;
}

.action-btn i {
  font-size: 16px;
}

.action-btn .favorited {
  color: #FF9900;
}

.more-actions {
  width: 26px;
  height: 26px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  color: #fff;
  background-color: #666;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.2);
  z-index: 21;
}

.more-actions i {
  font-size: 16px;
}

.actions-menu {
  position: absolute;
  right: 36px;
  top: 50%;
  transform: translateY(-50%);
  background-color: #555;
  border-radius: 3px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
  overflow: hidden;
  z-index: 22;
}

.menu-item {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 16px;
  min-width: 100px;
  color: #fff;
  cursor: pointer;
  transition: background-color 0.2s;
}

.menu-item:hover {
  background-color: #666;
}

.menu-item i {
  font-size: 16px;
}

.no-content {
  text-align: center;
  padding: 50px 0;
  color: #999;
}

.no-content i {
  font-size: 48px;
  margin-bottom: 15px;
}

.no-content p {
  font-size: 16px;
}

.share-options {
  display: flex;
  justify-content: space-around;
  flex-wrap: wrap;
  gap: 15px;
  padding: 20px 0;
}

.share-option {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
  cursor: pointer;
  transition: transform 0.2s;
}

.share-option:hover {
  transform: scale(1.1);
}

.share-option i {
  font-size: 24px;
  color: #409EFF;
  background-color: #ecf5ff;
  width: 50px;
  height: 50px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.share-option span {
  font-size: 14px;
  color: #333;
}

@media screen and (min-width: 768px) {
  .grid-count-3, .grid-count-many {
    grid-template-columns: repeat(3, 1fr);
  }

  .grid-count-4 {
    grid-template-columns: repeat(2, 1fr);
    grid-template-rows: repeat(2, 1fr);
  }
}

@media screen and (max-width: 576px) {
  .grid-count-2, .grid-count-3, .grid-count-4, .grid-count-many {
    grid-template-columns: repeat(2, 1fr);
  }

  .single-image {
    max-height: 300px;
  }
}

@media screen and (max-width: 768px) {
  .knowledge-content {
    padding: 50px 15px 30px;
  }

  .knowledge-item {
    padding: 20px;
  }

  .search-box {
    width: 90%;
  }

  .page-title {
    font-size: 28px;
  }

  .page-subtitle {
    font-size: 16px;
  }

  .item-footer {
    flex-wrap: wrap;
  }
}
</style>
