<route lang="json5" type="page">
{
  style: { navigationBarTitleText: '搜索' },
}
</route>

<template>
  <view class="serch-box">
    <wd-search
      placeholder="请输入牛号"
      cancel-txt="搜索"
      v-model="serchObj.searchNum"
      light
      @cancel="doSearch"
      @focus="showKeyBoard"
    />
    <view class="serch px-4 pt-4 flex">
      <text>历史搜索</text>
      <wd-icon name="delete-thin" size="40rpx" color="#3a3a3a" @click="clearList"></wd-icon>
    </view>
    <view class="history px-4 mt-4">
      <text
        class="px-4 pt-1 pb-1 item mb-2"
        v-for="(item, index) in serchObj.historyList"
        :key="index"
        @click="searchHistory(item)"
      >
        {{ item }}
      </text>
    </view>
    <!--  -->
    <wd-number-keyboard
      v-model:visible="visible"
      @input="onInput"
      @delete="onDelete"
    ></wd-number-keyboard>
  </view>
</template>

<script lang="ts" setup>
import { reactive, ref } from 'vue'

defineOptions({
  name: 'Serch',
})

let serchObj = reactive({
  searchNum: '',
  historyList: [],
})

const visible = ref<boolean>(false)

function showKeyBoard() {
  visible.value = true
}
function onDelete(value) {
  console.log('删除', value)
  serchObj.searchNum = serchObj.searchNum.slice(0, -1)
}

function onInput(value) {
  console.log(value, serchObj.searchNum, '键盘数字')
  serchObj.searchNum = `${serchObj.searchNum}${value}`
}

//用户搜索时将搜索文字存储
function doSearch(searchStr) {
  const val = searchStr.value.trim()
  if (val) {
    const history = serchObj.historyList.filter((item) => item !== val)
    history.unshift(val)
    if (history.length > 6) {
      history.pop()
    }
    serchObj.historyList = history
    uni.setStorageSync('history', JSON.stringify(serchObj.historyList))
    uni.navigateTo({ url: `/pages/searchDetail/searchDetail?serch=${searchStr.value}` })
  }
}

// 清除历史记录
function clearList() {
  serchObj.historyList = []
  uni.setStorageSync('history', JSON.stringify(serchObj.historyList))
}
// 历史搜索
function searchHistory(val) {
  console.log(val, '999')
  serchObj.searchNum = val
  uni.navigateTo({ url: `/pages/searchDetail/searchDetail?serch=${val}` })
}
onLoad(() => {
  //进入搜索页面时将存储在本地的历史记录取出并展示
  let history = uni.getStorageSync('history')
  if (history) {
    serchObj.historyList = JSON.parse(history) || []
    console.log(serchObj.historyList, '初始化历史')
  }
})
</script>

<style lang="scss" scoped>
//
.serch {
  justify-content: space-between;
  font-size: 36rpx;
  color: #3a3a3a;
}
.item {
  display: inline-block;
  margin-right: 10rpx;
  font-size: 24rpx;
  background-color: #eae8e8;
  border-radius: 4rpx;
}
</style>
