<template>
  <PageLayout>
    <template #header-title>
      <q-input
        class="full-width"
        outlined
        dense
        rounded
        v-model="keyword"
        placeholder="请输入要搜索的用户"
        clearable
        hide-bottom-space
        hide-hint
        @focus="showHistory = true"
        @keyup.enter="search"
      >
        <template v-slot:prepend>
          <q-icon name="search" />
        </template>
      </q-input>
    </template>
    <template #header-right>
      <q-btn flat dense @click="search">搜索</q-btn>
    </template>
    <infinite-scroll :load="load" :list="list" ref="scrollRef">
      <template #prepend>
        <div v-if="showHistory || !list.length" class="q-pa-md bg-white wrap">
          <q-btn
            unelevated
            dense
            class="q-px-md q-py-xs q-ma-xs"
            v-for="(item, i) in searchHistory"
            :key="i"
            color="grey-5"
            no-caps
            @click="(keyword = item) && search()"
            >{{ item }}</q-btn
          >
          <div class="col-12 q-mt-sm text-center">
            <q-btn
              flat
              dense
              :disable="!searchHistory.length"
              @click="searchHistory.splice(0, searchHistory.length)"
              >清除搜索记录</q-btn
            >
          </div>
        </div>
      </template>
      <template v-slot="{ item }">
        <CustormerItem :item="item" class="q-mt-sm" />
      </template>
    </infinite-scroll>
  </PageLayout>
</template>
<script setup>
import CustormerItem from "./components/CustomerItem.vue";
import { ref, reactive,onActivated } from "vue";
import { api } from "boot/axios";
import { LocalStorage } from "quasar";
import { useInfiniteScroll } from "src/composables/infiniteScroll";
import { useRoute } from "vue-router";
const route = useRoute()
const showHistory = ref(true);
const keyword = ref("");
const searchHistory = reactive(
  LocalStorage.getItem("user_search_history") || []
);
const { list, refresh, load, scrollRef } = useInfiniteScroll((page) => {
  if (!keyword.value) {
    return Promise.resolve(true);
  }
  return api.getCustomerList({
    page,
    keyword: keyword.value,
  });
});

function search() {
  if (!keyword.value) {
    return;
  }
  showHistory.value = false;
  let i = searchHistory.indexOf(keyword.value);
  if (i >= 0) {
    searchHistory.splice(i, 1);
  }
  searchHistory.unshift(keyword.value);
  LocalStorage.set("user_search_history", searchHistory);

  refresh();
  showHistory.value = false;
}

let enterTime = route.query.t
onActivated(()=>{
  if(route.query.t!=enterTime){
    enterTime = route.query.t
    refresh()
  }
})
</script>
<style lang="scss" scoped></style>
