import { ref, watch } from 'vue'
import { useRoute } from 'vue-router'
import { getContentDetailApi, getContentDetailByKeywordApi } from '@/apis/article'


export interface IDataInfo {
  id: number;
  title: string;
  desc: string;
  content: string;
  picture: string;
  inorder: number;
  show: number;
  indate: number;
  update: number;
  links: any;
  linkType: any;
  position: string;
  type: string;
  category: number;
  lang: string; 
}


function useData() {

  // route 对象
  const route = useRoute()
  console.log('route', route)
  const articleId = ref<string | number>('')
  const articleType = ref<string>('')
  const dataInfo = ref<IDataInfo | string | null>(null)
  const loading = ref<boolean>(false)


  // 监听路由 id 变化
  watch(
    () => route.query,
    (newVal) => {
      console.log('newVal', newVal)
      if (newVal.type) {
        articleType.value = newVal.type as string
      }
      else {
        articleType.value = ''
      }
      if (newVal.id) {
        articleId.value = (newVal.id as (string | number))
        fetchData()
      }
    },
    {
      immediate: true
    }
  )

  function fetchData() {
    switch(articleType.value) {
      case 'header':
        fetchArticleDetailByKeyword()
        break
      default:
        fetchArticleDetailById()
        break
    }
  }


  // 根据 id 获取文章详情
  function fetchArticleDetailById() {
    loading.value = true
    getContentDetailApi({ id: articleId.value })
      .then(result => {
        dataInfo.value = result.data
      })
      .catch(err => {

      })
      .finally(() => {
        loading.value = false
      })
  }


  // 根据关键词获取文章详情
  function fetchArticleDetailByKeyword() {
    loading.value = true
    getContentDetailByKeywordApi({ type: articleId.value })
      .then(result => {
        dataInfo.value = result.data
      })
      .catch(err => {

      })
      .finally(() => {
        loading.value = false
      })
  }


  return {
    articleId,
    articleType,
    dataInfo,
    loading,
    fetchArticleDetailById
  }
}



export default useData