<template>
  <div>
    <nav-bar title="搜索" :style="{ 'background-color':'#F7F7FA'}" />
    <search-bar @onSearch="onSearch" @onCancel="onCancel"/>
    <component v-if="showResult" :is="searchResult" :lists="lists"></component>
  </div>
</template>

<script lang="ts">
import { defineComponent,computed,ref } from 'vue'
import NavBar from "@/components/NavBar/index.vue"
import { useRoute } from 'vue-router'
import SearchBar from './components/SearchBar/index.vue'
import Empty from './components/Empty/index.vue'
import Result from './components/Result/index.vue'
import { searchNews, searchPolicy } from '@/service/NewsService/index'

export default defineComponent({
  components:{ NavBar,SearchBar,Empty,Result },
  setup () {
    const route = useRoute()
    const types = route.query.type
    let isEmpty = ref(true)
    let lists = ref([] as any)
    const searchResult = computed(()=>{
      return isEmpty.value ? 'Empty':'Result'
    })

    let showResult = ref(false)
    const request = types === 'news' ? searchNews : searchPolicy
    const onSearch = (visible:boolean,val:string)=>{
      showResult.value = visible
      request(val).then(res => {
        lists.value = res.data.items
        lists.value.sort((a: {update_at: number}, b: {update_at: number}) => b.update_at - a.update_at)
        if (lists.value.length > 0) {
          isEmpty.value = false
        }
      })
    } 
    const onCancel = (visible:boolean)=>{
      showResult.value = visible
    } 
    return {
      isEmpty,
      searchResult,
      showResult,
      lists,
      onSearch,
      onCancel
    }
  }
})
</script>

<style scoped>

</style>