<template>
  <el-input
    v-model="keyword"
    size="large"
    placeholder="请输入搜索关键字"
    clearable
    @keydown.enter="search"
  >
    <template #append>
      <el-button :icon="ElIconSearch" @click="search">搜索</el-button>
    </template>
  </el-input>
</template>

<script>
import { ref } from 'vue'
import { useRoute } from 'vue-router'

export default {
  name: 'SearchInput',
  setup () {
    const route = useRoute()
    const keyword = route.query.kwd || ''
    return {
      keyword: ref(keyword)
    }
  },
  watch: {
    // 路由参数变化时，触发数据搜索
    '$route.query': function (newQuery) {
      this.keyword = newQuery.kwd == null ? '' : newQuery.kwd.trim()
    }
  },
  methods: {
    // 执行搜索
    search () {
      this.keyword = this.keyword.trim()
      if (this.keyword === '') {
        return
      }
      // 如果当前在搜索页，直接替换路径
      if (this.$route.path === '/search') {
        this.$router.push({ path: '/search', query: { kwd: this.keyword } })
        return
      }
      // 打开搜索页
      window.open(`/search?kwd=${this.keyword}`)
    }
  }
}
</script>

<style scoped lang="scss">
.el-input {
  width: 300px;
  border-radius: 40px;
  overflow: hidden;
  :deep(.el-input__wrapper) {
    box-shadow: none;
    .el-input__inner {
      font-size: var(--font-size-base);
    }
  }
  // 搜索按钮
  :deep(.el-input-group__append) {
    padding: 0 10px;
    width: 65px;
    background-color: var(--primary-color-dark-deep);
    box-shadow: none;
    font-size: var(--font-size-base);
    color: var(--color-white);
    overflow: hidden;
    .el-button {
      display: flex;
      align-items: center;
      padding: 0;
      width: 100%;
      height: 100%;
      .el-icon {
        margin-right: 5px;
      }
    }
  }
}
</style>
