import { getListDataByPage } from "../../api/documentManagement";

export default {
  data() {
    return {
      searchKeyword: '',
      searchResults: [],
      currentPage: 1,
      pageSize: 10,
      totalCount: 0,
      previewVisible: false,
      previewData: null,
      pageNum:1,

      // 文档类型映射
      documentTypes: {
        // '1': '服务条款',
        // '2': 'API文档',
        // '3': '挖矿教程',
        // '0': '其他'
      },
      searchLoading:false
    }
  },
  mounted() {
    try {
        this.documentTypes= JSON.parse(localStorage.getItem("TypeList")) || {}
    } catch (error) {
        console.log(error,"error");
    }
   
    // 从URL参数获取搜索关键词和结果数据
    this.searchKeyword = this.$route.query.keyword || '';
    
    // 如果有搜索结果数据，直接使用
    if (this.$route.query.results) {
      try {
        const results = JSON.parse(decodeURIComponent(this.$route.query.results));
        this.searchResults = results.rows || [];
        this.totalCount =results.total || 0;
      } catch (error) {
        console.error('解析搜索结果数据失败:', error);
      }
    } else if (this.searchKeyword) {
      // 如果没有结果数据但有关键词，则重新搜索
      this.fetchSearchResults();
    }
  },
  methods: {
    /**
     * 获取搜索结果
     */
    async fetchSearchResults() {
        this.setLoading('searchLoading', true);
      try {
        const response = await getListDataByPage({
          keyword: this.searchKeyword,
          pageNum: this.pageNum,
          pageSize: this.pageSize,
          lang: this.$i18n.locale
        });

        if (response && response.code === 200) {
          this.searchResults = response.rows || [];
          this.totalCount = response.total || 0;
        }
      } catch (error) {
        console.error('获取搜索结果失败:', error);
        this.$message.error('获取搜索结果失败');
      }
      this.setLoading('searchLoading', false);
    },

    /**
     * 高亮关键词
     */
    highlightKeyword(text) {
      if (!this.searchKeyword || !text) return text;
      const regex = new RegExp(`(${this.searchKeyword})`, 'gi');
      return text.replace(regex, '<mark>$1</mark>');
    },

    /**
     * 获取内容预览
     */
    getContentPreview(content) {
      if (!content) return '';
      // 移除HTML标签，获取纯文本
      const text = content.replace(/<[^>]*>/g, '');
      return text.length > 100 ? text.substring(0, 100) + '...' : text;
    },

    /**
     * 格式化日期
     */
    formatDate(dateString) {
      if (!dateString) return '';
      const date = new Date(dateString);
      return date.toLocaleDateString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
      });
    },

    /**
     * 获取文档类型名称
     */
    getDocumentTypeName(type) {
        console.log(type,"typ俯瞰风景分开发饭饭登记费记得发e",this.documentTypes);
        
        try {
            let label = this.documentTypes.find(item => item.value == type)?.label
            return this.$t(label)
        } catch (error) {
            console.log(error,"error");
            return '未知类型';
        }
     
    },

    /**
     * 处理分页变化
     */
    handlePageChange(page) {
      this.currentPage = page;
      this.fetchSearchResults();
    },

    /**
     * 处理搜索结果项点击
     */
    handleItemClick(item) {
    //   this.handlePreview(item);
    let url
    if (item.articleUrl) {
         url = `/${this.$i18n.locale}/${item.articleUrl}`
    }
       
        this.$router.push({
            path:url,
            query:{
                id:item.id
            }
        })
    },

    /**
     * 预览文档
     */
    handlePreview(item) {
      this.previewData = item;
      this.previewVisible = true;
    },



    /**
     * 关闭预览对话框
     */
    handlePreviewClose() {
      this.previewVisible = false;
      this.previewData = null;
    },
    handleCurrentChange(page){
        this.pageNum = page
        this.fetchSearchResults()
    },
    handleSizeChange(size){
        this.pageSize = size
        this.currentPage = 1
        this.pageNum = 1
        this.fetchSearchResults()
    }
  }
}