<template>
  <div>
    <!--    {{ list }}-->

    <div class="max-w-screen-lg my-[50px] mx-auto">
      <n-h2> 搜索结果：</n-h2>
      <template v-if="list.length > 0">
        <n-list hoverable clickable>
          <template v-for="(item, index) in list" :key="index">
            <n-list-item @click="handleToArticle(item)">
              <n-thing :title="item.title" content-style="margin-top: 10px;">
                <template #description>
                  <div class="color-[#909090]">
                    {{ htmlspecialchars(item.content) }}
                  </div>
                </template>
              </n-thing>
            </n-list-item>
          </template>
        </n-list>

        <div class="my-[50px] mx-auto text-center color-[#909090]">共 {{ list.length }} 条数据</div>
      </template>
      <n-empty
        v-else
        size="large"
        :description="$t('no_data')"
        class="min-h-[500px] flex align-center justify-center"
      >
        <template #extra>
          <n-button size="small" @click="$router.push('/')"> 返回</n-button>
        </template>
      </n-empty>
    </div>
  </div>
</template>

<route>
{
name: "search",
meta: {
layout: "base"
}
}
</route>
<script lang="ts" setup>
import { NList, NListItem, NThing, NH2, NEmpty, NButton } from 'naive-ui'
import { type ArticleDetailType, getArticleSearch } from '@/api'
import router from '@/plugins/router.ts'

const list = ref<ArticleDetailType[]>([])

function htmlspecialchars(str: string) {
  const div = document.createElement('div')
  div.innerHTML = str
  const text = div.textContent || ''
  return text.length > 150 ? `${text.substring(0, 150)}...` : text
}

const route = useRoute()
onMounted(async () => {
  watchEffect(() => {
    if (route.query.key) {
      getArticleSearch(route.query.key).then((result) => {
        list.value = result.data
      })
    }
  })
})

const handleToArticle = (item: ArticleDetailType) => {
  router.push(`/showdoc/${item.id}`)
}
</script>
