import { ref, computed } from 'vue'
import { getFAQCateListApi } from '@/apis/article'


// 问题
export interface IFAQInfo {
  id: number;
  title: string;
  links: string;
  content: string; 
}

// 分类列表
export interface ICateInfo {
  id: number;
  pid: number;
  name: string;
  sort: number;
  code: number | string;
  lists: Array<IFAQInfo>; 
}


function useData() {

  // 分类列表
  const categoryList = ref<ICateInfo[]>([])
  const isLoading = ref<boolean>(false)
  // 当前选中的分类
  const activeCategoryId = ref<string | number>(0)          // id
  const activeCategoryInfo = ref<ICateInfo | null>(null)    // 分类信息
   // 当前查看的问题详情
   const currentQuestion = ref<IFAQInfo | null>(null)

  // 搜索查询词
  const searchQuery = ref<string>('')
  // 搜索结果
  const searchResults = ref<Array<IFAQInfo>>([])


  // 切换分类
  const changeCategory = (categoryInfo: ICateInfo) => {
    activeCategoryInfo.value = categoryInfo
    activeCategoryId.value = categoryInfo.id
    currentQuestion.value = null
    searchResults.value = []
  }


  // 搜索问题
  const searchQuestions = () => {
    if (!searchQuery.value.trim()) {
      searchResults.value = []
      return
    }

    const query = searchQuery.value.toLowerCase()
    const list: IFAQInfo[] = []
    for (let i = 0; i < categoryList.value.length; i++) {
      let cateInfo: ICateInfo = categoryList.value[i]
      for (let j = 0; j < cateInfo.lists.length; j++) {
        let faqInfo: IFAQInfo = cateInfo.lists[j]
        if (faqInfo.title.toLowerCase().includes(query) || faqInfo.content.toLowerCase().includes(query)) {
          list.push(faqInfo)
        }
      }
    }
    searchResults.value = list
    currentQuestion.value = null
  }


  // 显示问题详情
  const showQuestionDetail = (question: IFAQInfo) => {
    currentQuestion.value = question
  }

  // 返回问题列表
  const backToList = () => {
    currentQuestion.value = null
  }


  // 获取问题列表
  function fetchFAQList() {
    isLoading.value = true
    getFAQCateListApi({})
      .then((result) => {
        // console.log('result', result)
        if (result.data && result.data.length > 0) {
          categoryList.value =  result.data
          activeCategoryInfo.value = result.data[0]
          activeCategoryId.value = result.data[0].id
        }
        else {
          categoryList.value =  []
          activeCategoryInfo.value = null
          activeCategoryId.value = ''
        }
      })
      .catch(err => {})
      .finally(() => {
        isLoading.value = false
      })
  }
  fetchFAQList()

  return {
    categoryList,
    isLoading,
    activeCategoryId,
    activeCategoryInfo,
    currentQuestion,
    searchQuery,
    searchResults,
    changeCategory,
    showQuestionDetail,
    searchQuestions,
    backToList,
  }
}



export default useData