<template>
  <div @keyup.enter="search">
    <v-menu offset-y>
      <template v-slot:activator="{ on }">
        <v-text-field
          ref="search"
          v-model="text"
          solo
          hide-details
          label="想要搜点神马呢"
          class="input-search"
          autocomplete="off"
          v-on="on"
        />
      </template>
      <v-list v-if="items.length > 0" class="border-list" dense>
        <v-list-item v-for="(item, index) in items" :key="index" @click="itemClick(item)">
          <v-list-item-title>{{ item.name }}</v-list-item-title>
        </v-list-item>
      </v-list>
    </v-menu>
  </div>
</template>

<script>
import { keywordSuggest } from '@/api/search/search'

export default {
  name: 'Search',
  data() {
    return {
      text: '',
      showSelect: true,
      items: []
    }
  },
  watch: {
    text: 'handleInput'
  },
  methods: {
    itemClick(item) {
      this.text = item.name
      this.$refs.search.blur()
    },
    handleInput(text) {
      if (text.trim() !== '') {
        this.showSelect = true
        setTimeout(() => {
          this.getKeyword(text)
        }, 300)
      }
    },
    getKeyword(keyword) {
      keywordSuggest(keyword)
        .then(res => {
          if (res.code === 0) {
            this.items = res.data
          } else {
            console.error(res.msg)
          }
        })
        .catch(error => {
          console.error(error.message)
        })
    },
    search() {
      this.$refs.search.blur()
      const currentUrl = this.$route.path
      if (currentUrl === '/search/result') {
        this.$router.push({
          path: '/search/result',
          query: {
            keyword: this.text,
            page: 1
          }
        })
      } else {
        const routeUrl = this.$router.resolve({
          path: '/search/result',
          query: {
            keyword: this.text,
            page: 1
          }
        })
        window.open(routeUrl.href, '_blank')
      }
    }
  }
}
</script>

<style scoped>
    /*.input-search {*/
    /*    width: 40%;*/
    /*    margin: auto;*/
    /*}*/
    /*.width-20-percent {*/
    /*    width: 20%;*/
    /*}*/
    /*.img-div {*/
    /*    margin: 16vh 0 40px 0;*/
    /*    text-align: center;*/
    /*}*/
    /*.v-menu__content {*/
    /*    box-shadow: none !important;*/
    /*}*/
    /*.border-list {*/
    /*    border: 1px solid #eee !important;*/
    /*}*/
</style>
