<template>
  <!-- 搜索历史 -->
  <div class="history mt-3">
    <div class="text-sm text-text-secondary">搜索历史</div>
    <template v-if="history.length > 0">
      <div class="list mt-1">
        <div
          v-for="(item, index) in history"
          :key="index"
          class="flex items-center border-b border-border-lighter"
        >
          <app-icon
            icon-name="history"
            class-name="h-2.5 w-2.5 flex-shrink-0"
          />
          <div class="pl-2.5 py-3.5 text-sm flex-1 truncate" @click="search(item)">{{ item }}</div>
          <div class="h-11 w-11 flex items-center justify-end" @click="deleteHistory(item)">
            <app-icon
              icon-name="close-history"
              class-name="h-5 w-5 flex-shrink-0"
            />
          </div>
        </div>
      </div>
      <div class="text-sm py-3.5 mt-1 text-center text-text-secondary" @click="clearHistory">
        清空历史
      </div>
    </template>
    <template v-else>
      <div class="text-sm text-text-secondary text-center py-8">暂无搜索历史</div>
    </template>
  </div>
</template>

<script lang="ts">
import Vue from 'vue'

export default Vue.extend({
  name: 'SearchHistory',
  components: {
    'app-icon': () => import('@/components/common/Icon.vue')
  },
  props: {
    history: {
      type: Array,
      default() {
        return []
      }
    }
  },
  data() {
    return {}
  },
  computed: {
    historyCopy() {
      return this.history
    }
  },
  methods: {
    deleteHistory(keyword: string) {
      const index = this.historyCopy.findIndex(item => item === keyword)
      this.historyCopy.splice(index, 1)
      this.$emit('update:history', this.historyCopy)
    },
    clearHistory() {
      this.historyCopy = []
      this.$emit('update:history', this.historyCopy)
    },
    search(keyword: string) {
      this.$emit('search', keyword)
    }
  }
})
</script>

<style lang="less">

</style>
