<template>
  <div class="doc-search-container">
    <!-- 左侧知识库类型选择 -->
    <div class="sidebar">
      <h2 class="sidebar-title" @click="router.push('/knowledge-list')">知识库</h2>
      <ul class="type-list">
        <!-- <li 
          class="type-item" 
          :class="{ active: activeType === '' }"
          @click="handleTypeSelect('')"
        >
          <div class="type-content">
            <span>全部类型</span>
          </div>
        </li> -->
        <li 
          v-for="type in typeOptions" 
          :key="type.value"
          class="type-item"
          :class="{ active: activeType === type.value }"
          @click="handleTypeSelect(type.value)"
        >
          <div class="type-content">
            <img :src="type.icon" :alt="type.label" class="type-icon">
            <span>{{ type.label }}</span>
          </div>
        </li>
      </ul>
    </div>

    <!-- 右侧搜索和结果区域 -->
    <div class="main-content">
      <!-- 搜索框 -->
      <div class="search-section">
        <el-input
          v-model="searchQuery"
          placeholder="请输入关键词搜索文档..."
          class="search-input"
          clearable
          @keyup.enter="handleSearch"
        >
          <!-- <template #prefix>
            <el-icon><Search /></el-icon>
          </template> -->
          <template #append>
            <el-button type="primary" :loading="loading" @click="handleSearch">
              <el-icon :size="20"><Search /></el-icon>
              <!-- 搜索 -->
            </el-button>
          </template>
        </el-input>
      </div>
      <!-- 提示语 -->
      <div class="search-tips">
        选择知识库搜索会更快
      </div>


      <!-- 搜索结果 -->
      <div class="result-section" v-loading="loading">
        <template v-if="searchResults.length">
          <div
            v-for="(item, index) in searchResults"
            :key="index"
            class="result-item"
          >
            <div class="result-content">
              <p class="result-summary ellipsis-2" v-html="highlightText(item.fileSnapshot)"></p>

              <div class="result-content-bottom">
              <div class="file-icon">
                <el-icon :size="24">
                  <Document v-if="item.fileType === 'doc'" />
                  <Files v-else-if="item.fileType === 'pdf'" />
                  <Grid v-else-if="item.fileType === 'excel'" />
                  <PictureFilled v-else-if="item.fileType === 'ppt'" />
                  <Folder v-else />
                </el-icon>
              </div>
              <div class="result-info">
                <h3 class="result-title" @click="viewDocument(item)">
                  {{ item.fileName }}
                </h3>
              </div>
              <div class="result-actions">
                <el-icon color="#FF7575" size="24" @click="toggleFavorite(item)">
                  <Star v-if="item.isCollect == 0" />
                  <StarFilled v-else />
                </el-icon>
                <!-- <el-button
                  type="primary"
                  size="small"
                  @click="toggleFavorite(item)"
                  :icon="item.isFavorite ? 'Star' : 'StarFilled'"
                  :class="{ 'is-favorite': item.isFavorite }"
                >
                  {{ item.isFavorite ? '已收藏' : '收藏' }}
                </el-button> -->
                <el-icon color="#FF7575" size="24" @click="downloadDocument(item)">
                  <Download />
                </el-icon>
                <!-- <el-button
                  type="primary"
                  size="small"
                  @click="downloadDocument(item)"
                  icon="Download"
                >
                  下载
                </el-button> -->
              </div>
              </div>

            </div>
          </div>

          
        </template>

        <el-empty
          v-else-if="!loading && searchQuery"
          description="未找到相关文档"
        />

        <el-empty
          v-else-if="!loading"
          description="请输入关键词搜索文档"
        />
      </div>
      <!-- 分页 -->
      <div class="pagination">
            <el-pagination
              v-model:current-page="currentPage"
              v-model:page-size="pageSize"
              :total="total"
              :page-sizes="[10, 20, 30, 50]"
              layout="total, sizes, prev, pager, next"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Search, View, Star, Download, Document, Files, Grid, PictureFilled, Folder } from '@element-plus/icons-vue'
import { get, post,put } from '../utils/request'
import { useUserStore } from '../stores/user'
import { useRoute, useRouter } from 'vue-router'
const userStore = useUserStore()
const router = useRouter()

import docTypeJs from '../assets/doc-type-js.png'
import docTypeSw from '../assets/doc-type-sw.png'
import docTypeXz from '../assets/doc-type-xz.png'

// 搜索相关
const searchQuery = ref('')
const loading = ref(false)
const searchResults = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

const activeType = ref('')
const handleTypeSelect = (type) => {
  activeType.value = type
  // handleSearch()
}

// 选项配置
const typeOptions = ref([])

// 添加获取知识库列表的方法
const getKnowInfoList = async () => {
  try {
    // const response = await get('/admin/knowInfo/getList',{pageNum:1,pageSize:100})
    const userId = userStore.userInfo.id
    const response = await get('/admin/user/chat/knowInfoList?userId='+userId)

    console.log('response', response);
    
    typeOptions.value = response.data.map(item => ({ 
      value: item.id,
      label: item.name,
      icon: getIconByType(item.type) // 根据类型获取对应图标
    }))
  } catch (error) {
    ElMessage.error('获取知识库列表失败')
  }
}

// 添加根据类型获取图标的方法
const getIconByType = (type) => {
  const iconMap = {
    'technical': docTypeJs,
    'business': docTypeSw,
    'administrative': docTypeXz
  }
  return iconMap[type] || docTypeJs
}

// 在组件挂载时获取知识库列表
onMounted(() => {
  getKnowInfoList()
})


// 搜索处理
const handleSearch = async () => {
  // if (!searchQuery.value.trim() && !activeType.value) return
  
  loading.value = true
  try {
    const params = {
      searchText: searchQuery.value,
      konwInfoId: activeType.value,
      pageNum: currentPage.value,
      pageSize: pageSize.value
    }
    
    const response = await get('/admin/knowFile/search', params)
    searchResults.value = response.data.rows
    total.value = Number(response.data.total)
  } catch (error) {
    // 模拟数据
    // searchResults.value = [
    //   {
    //     id: 1,
    //     title: '文档1',
    //     summary: '文档1摘要',
    //     type: 'doc',  
    //     date: '2024-01-01',
    //     isFavorite: false,
    //     favorites: 0,
    //     url: 'https://www.baidu.com'
    //   },
    //   {
    //     id: 2,
    //     title: '文档2',
    //     summary: '文档2摘要',
    //     type: 'doc',
    //     date: '2024-01-01',
    //   }
    // ] ;
    // total.value = 2;

    ElMessage.error('搜索失败，请重试')
  } finally {
    loading.value = false
  }
}

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val
  handleSearch()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  handleSearch()
}

// 文档操作
const viewDocument = (doc) => {
  window.open(doc.fileUrl, '_blank')
}

const downloadDocument = async (doc) => {
  // fileUrl是文件的地址,直接下载
  try {
    window.open(doc.fileUrl, '_blank')
    // 添加文件下载记录
    await post('/admin/userHistoryLog/saveFileDownloadLog', {
      relatedId: doc.id
    })
  } catch (error) {
    console.log('error', error);
    ElMessage.error('下载失败，请重试文件地址:'+doc.fileUrl)
  }
}

const toggleFavorite = async (doc) => {
  console.log('doc', doc);
  try {
    if (doc.isCollect == 0) {
      await post('admin/userCollect/save', {
        id: doc.collectId,
        relatedType: 'file.search',
        relatedId: doc.id,
      })
    } else {
      await put('admin/userCollect/cancel', {
        id: doc.collectId,
        relatedType: 'file.search',//related_type : AI问答 : ai.answer 方案:scheme 文件检索: file.search
        relatedId: doc.id,
      })
    }
    doc.isCollect = doc.isCollect == 0 ? 1 : 0
    ElMessage.success(doc.isCollect == 1 ? '收藏成功' : '已取消收藏')
    handleSearch()
  } catch (error) {
    ElMessage.error('操作失败，请重试')
  }
}

// 工具函数
const getTagType = (type) => {
  const types = {
    doc: '',
    pdf: 'success',
    excel: 'warning',
    ppt: 'danger'
  }
  return types[type] || 'info'
}

const formatDate = (date) => {
  return new Date(date).toLocaleDateString()
}

const highlightText = (text) => {
  if (!searchQuery.value) return text
  
  const regex = new RegExp(searchQuery.value, 'gi')
  return text.replace(regex, match => `<span class="highlight">${match}</span>`)
}
</script>

<style lang="scss" scoped>
.doc-search-container {
  height: 100%;
  display: flex;
  // gap: $spacing-base;
  background-color: #fff;
  // padding: $spacing-base;
}

.sidebar {
  width: 350px;
  background-color: $background-gray;
  border-radius: 0px 30px 30px 0px;
  box-shadow: 2px 0px 10px 0px rgba(172,165,165,0.5);
  
  .sidebar-title {
    padding: $spacing-base;
    margin-bottom: 23px;
    font-size: 24px;
    font-weight: bold;
    border-bottom: 1px solid $border-lighter;
    text-align: center;
    color: #191A1E;
    cursor: pointer;
  }

  .type-list {
    list-style: none;
    padding: 0;
    margin: 0;

    .type-item {
      padding: 0  50px 0 50px; 
      cursor: pointer;
      transition: all 0.3s ease;

      // &:hover {
      //   .type-content{
      //     border-image: linear-gradient(226deg, rgba(237, 38, 38, 1), rgba(246, 181, 181, 1)) 1 1;
      //   }
      // }

      &.active {
        .type-content{
          border: 1px solid #ED2626;
          // border-image: linear-gradient(226deg, rgba(237, 38, 38, 1), rgba(246, 181, 181, 1)) 1 1;
        }
      }

      .type-content {
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 12px;
        height: 80px;
        background: linear-gradient( 131deg, #FFFFFF 0%, #FFFFFF 100%);
        box-shadow: 0px 1px 3px 0px rgba(192,202,209,0.5);
        border-radius: 15px;
        margin-bottom: 20px;

        .type-icon {
          width: 40px;
          height: 46px;
          object-fit: contain;
        }

        span {
          font-weight: 500;
          font-size: 20px;
          color: #31333C;
        }
      }
    }
  }
}

.main-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: $spacing-base;
  min-width: 0; // 防止内容溢出
  padding: 0 20px;
}

.search-section {
  padding-top: 76px;
  // padding: $spacing-base;
  background-color: $background-white;
  border-radius: $border-radius-base;
  // box-shadow: $box-shadow-light;
  .search-input{
    height: 60px;
    border-radius: 15px;
  }
  :deep(.el-input__wrapper) {
    border-top-left-radius: 15px;
    border-bottom-left-radius: 15px;
  }
  :deep(.el-input-group__append) {
    border-top-right-radius: 15px;
    border-bottom-right-radius: 15px;
    width: 78px;
  }
}

.search-tips{
  font-weight: 500;
  font-size: 16px;
  color: #31333C;
  line-height: 30px;
}

.result-section {
  flex: 1;
  overflow-y: auto;
  padding: $spacing-base;
  background-color: #F9FAFB;
  border-radius: 12px;
  // box-shadow: $box-shadow-light;
}

.result-item {
  padding: $spacing-base;
  margin-bottom: 14px;
  background-color: #fff;
  
  &:last-child {
    border-bottom: none;
  }
  
  .result-content {
    .file-icon {
      flex-shrink: 0;
      width: 40px;
      height: 40px;
      display: flex;
      align-items: center;
      justify-content: center;
      background-color: $background-lighter;
      border-radius: $border-radius-base;
      
      .el-icon {
        font-size: 24px;
        color: $primary-color;
      }
    }

    .result-summary {
        margin: $spacing-mini 0;
        font-weight: 400;
        font-size: 21px;
        color: #191A1E;
        line-height: 32px;
        margin-bottom: 24px;
        
        :deep(.highlight) {
          color: $primary-color;
          font-weight: bold;
          background-color: rgba($primary-color, 0.1);
          padding: 0 2px;
          border-radius: 2px;
        }
      }
    
    .result-info {
      flex: 1;
      min-width: 0;
      
      .result-title {
        margin: 0 0 $spacing-mini;
        font-size: 16px;
        color: #6C6E72;
        cursor: pointer;
        margin-left: 12px;
      }
    }

    .result-content-bottom{
        display: flex;
        align-items: center;
        justify-content: space-between;
        background: #FFF6F6;
        border-radius: 12px;
        padding: 8px 20px;
      }
    
    .result-actions {
      flex-shrink: 0;
      display: flex;
      gap: $spacing-mini;

      .el-icon {
        cursor: pointer;
        margin-left: 10px;
      }
      
      .el-button {
        &.is-favorite {
          background-color: $warning-color;
          border-color: $warning-color;
          
          &:hover {
            background-color: $primary-color-hover;
            border-color: $primary-color-hover;
          }
        }
      }
    }
  }
}

.pagination {
  margin-top: $spacing-large;
  margin-bottom: 20px;
  display: flex;
  justify-content: center;
}
</style> 