<script setup lang="ts">
import { pageUrl } from '@/utils/constants'
import { ref } from 'vue'

let name = ref('')

const history = ref<string[]>(uni.getStorageSync('search') || [])

const storeHistroy = () => {
  name.value = name.value.trim()
  if (name.value == '') return
  // 缓存搜索关键词
  const index = history.value.findIndex((item) => item === name.value)
  if (index !== -1) {
    history.value.splice(index, 1)
  }
  history.value.unshift(name.value)
  uni.setStorageSync('search', history.value)
}

const search = async () => {
  await uni.navigateTo({
    url: `${pageUrl['shopping-mall-goods-list']}?name=${name.value}`,
  })
  storeHistroy()
}

const onTapHistory = async (keyword: string) => {
  await uni.navigateTo({
    url: `${pageUrl['shopping-mall-goods-list']}?name=${keyword}`,
  })
  name.value = keyword
  storeHistroy()
}

const onCancel = () => {
  uni.navigateBack()
}

const onClearHistory = () => {
  uni.showModal({
    title: '',
    content: '确定要清空历史搜索吗',
    showCancel: true,
    success: ({ confirm, cancel }) => {
      if (confirm) {
        uni.removeStorageSync('search')
        history.value = []
      }
    },
  })
}

const onDeleteHistory = (name: string) => {
  uni.showModal({
    title: '',
    content: '确定要删除该条历史搜索吗',
    showCancel: true,
    success: ({ confirm, cancel }) => {
      if (confirm) {
        const index = history.value.findIndex((item) => item === name)
        if (index !== -1) {
          history.value.splice(index, 1)
          uni.setStorageSync('search', history.value)
        }
      }
    },
  })
}
</script>

<template>
  <view class="search">
    <uni-search-bar
      @confirm="search"
      :focus="true"
      v-model="name"
      radius="100"
      @cancel="onCancel"
    />
  </view>
  <view class="search-history">
    <text>历史搜索</text>
    <view class="trash">
      <uni-icons type="trash" color="" size="24" @tap="onClearHistory" />
    </view>
  </view>
  <view class="keyword">
    <button
      v-for="(item, index) in history"
      :key="index"
      @tap="onTapHistory(item)"
      class="keyword-button"
      aria-readonly
      @longtap="onDeleteHistory(item)"
    >
      {{ item }}
    </button>
  </view>
</template>

<style lang="scss">
page {
  padding-left: 20rpx;
}

.search {
  padding-right: 20rpx;
}

.search-history {
  display: flex;
  justify-content: space-between;
  margin-top: 10px;
  font-size: 14px;

  .trash {
    display: flex;
    align-items: center;
    margin-right: 50rpx;
  }
}

.keyword {
  display: flex;
  flex-wrap: wrap;
  margin-top: 20px;
  float: left;

  button {
    background-color: #f2f2f2;
    border-radius: 25rpx;
    color: #333333;
    font-size: 24rpx;
    align-items: center;
    margin: 0 10rpx 15rpx 15rpx;
    justify-content: flex-start;
    // padding-left: 10px;
    display: flex;

    .delete-icon {
      margin-left: 5px;
      margin-right: -10rpx;
    }
  }
}
</style>
