<template>
  <view class="search">
    <!-- 导航栏 -->
    <u-navbar :border-bottom="false" :is-back="false">
      <view class="pl-base w-full">
        <u-search
          @search="Search"
          border-color="#E5E5E5"
          bg-color="#ffffff"
          placeholder="搜索商品名称"
          v-model="searchText"
          :show-action="false"
        ></u-search>
      </view>
      <template #right>
        <view @tap="back" class="text-md text-txBase mx-base"> 取消 </view>
      </template>
    </u-navbar>
    <!--历史记录 -->
    <block v-if="history.length">
      <view class="px-22rpx pt-38rpx text-txBase font-extrabold text-md flex items-center justify-between">
        <view>历史记录</view>
        <view @tap="show = true">
          <image class="w-36rpx h-36rpx" src="/static/svg/del.svg" mode=""></image>
        </view>
      </view>
      <!--  -->
      <view class="flex items-center flex-wrap">
        <view
          @tap="onTap(item)"
          class="text-md text-primary mt-base ml-22rpx px-35rpx py-10rpx bg-bgInput rounded-lg"
          v-for="(item, index) in history"
          :key="index"
          >{{ item }}</view
        >
      </view>
    </block>
    <!-- 实时热搜 -->
    <block v-if="hotList.length">
      <view class="px-22rpx pt-38rpx text-txBase font-extrabold text-md"> 实时热搜 </view>
      <!--  -->
      <view class="flex items-center flex-wrap">
        <view
          @tap="onTap(item)"
          class="text-md text-primary mt-base ml-22rpx px-35rpx py-10rpx bg-bgInput rounded-lg"
          v-for="(item, index) in hotList"
          :key="index"
          >{{ item }}</view
        >
      </view>
    </block>
    <!-- 是否删除历史记录弹窗 -->
    <cu-modal v-model="show" @confirm="confirm" confirm-color="#378264" show-cancel-button content="是否删除历史记录"> </cu-modal>
  </view>
</template>

<script>
export default {
  data() {
    return {
      searchText: '',
      hotList: [],
      show: false,
    };
  },
  computed: {
    history() {
      return this.$store.getters.history;
    },
  },
  onLoad() {
    this.getHot();
  },
  methods: {
    async getHot() {
      const { keys } = await this.$api.get('/v1/product/search-hot-keys');
      const arr = keys ?? [];
      this.hotList = arr.filter((e) => !!e);
    },
    back() {
      uni.navigateBack({
        delta: 1,
      });
    },
    onTap(e) {
      this.searchText = e;
      this.Search();
    },
    //获取历史记录
    Search() {
      if (!this.searchText.trim()) return;
      this.$u.route('/pages/search/search_result', {
        searchText: this.searchText,
      });
      this.$store.commit('user/SET_HISTORY', this.searchText);
    },
    //删除历史记录
    confirm() {
      this.$store.commit('user/DEL_HISTORY');
    },
  },
};
</script>

<style lang="scss" scoped>
.search {
  background: #ffffff;
  height: 100vh;
}
</style>
