<template>
  <div class="category-boxs-bg">
    <div class="max-w1280 category-boxs">
      <img src="@/assets/img/loading.png" width="0" height="0" />
      <div class="search-input-wrap">
        <el-input class="input-wrap" v-model="user.publicSearch" size="large" placeholder="输入中英文产品名称搜索" @keyup.enter.native="SearchFun">
          <template #append>
            <div @click="SearchFun">
              <el-icon>
                <Search />
              </el-icon>
            </div>
          </template>
        </el-input>
      </div>
      <div class="filter-wrap">
        <van-dropdown-menu ref="menuRef">
          <van-dropdown-item v-model="query.sort" :options="sortOptions" @change="sortClick" />
          <van-dropdown-item v-model="query.storeCount" :options="storeOptions" @change="sortClick"/>
          <!-- <van-dropdown-item title="商品类目">
            <ul class="">
              <li @click="onConfirm">类目1</li>
            </ul>
          </van-dropdown-item>
          <van-dropdown-item title="商品品牌">
            <ul class="">
              <li @click="onConfirm">品牌</li>
            </ul>
          </van-dropdown-item> -->
        </van-dropdown-menu>
        <!-- <ul>
          <li @click="sortClick">排序<i :class="{'top':query.sort==1,'down':query.sort==2}"></i></li>
          <li>价格<i></i></li>
          <li>库存<i></i></li>
          <li>销量<i></i></li>
          <li class="filter">筛选<i></i></li>
        </ul> -->
      </div>
      <div class="layer search-wrap mb10 mt6" v-loading="isStateLoading" ref="layer">
        <template v-if="spuArr.length>0">
          <div class="layer-content">
            <List :spuArr="spuArr" :pageData="pageData"></List>
            <img class="loading" src="@/assets/img/ico/loading.gif" v-if="!skuFalg && user.isLogin && isClient" />
            <p class="loading-text" v-if="skuFalg && user.isLogin">--&nbsp;已经到底了&nbsp;--</p>
            <p class="loading-text" v-if="skuFalg && spuArr.length<query.pageSize && !user.isLogin">--&nbsp;已经到底了&nbsp;--</p>
          </div>
          <div class="pagination-btn" v-if="!user.isLogin && spuArr.length>=query.pageSize">
            <el-button class="btn_noLogin btn_main" @click="linkTo">
              登录后查看更多
            </el-button>
          </div>
          <nav class="pagination" aria-label="分页导航" v-if="!isClient">
            <!-- SEO 友好的分页链接 -->
            <a v-for="page in pageCount" :key="page" :href="`/search?key=${user.publicSearch}&pageNum=${page}&pageSize=${query.pageSize}`" :class="{ active: page === query.pageNum }" :aria-current="page === query.pageNum ? 'page' : false">
              第{{ page }}页
            </a>
          </nav>
        </template>
        <template v-if="spuArr.length<1 && sendFalg">
          <el-empty description=" " :image="empty" :image-size="350">
            <div class="noContent">
              暂无 <span class="mainColor">“{{user.publicSearch}}”</span> 商品
            </div>
          </el-empty>
        </template>
      </div>
    </div>
  </div>
</template>
<script setup lang="ts">
definePageMeta({
  name: "searchPage",
});
let pageTitle: any = ref("HOTKING-搜索");

import { Search } from "@element-plus/icons-vue";
import empty from "@/assets/img/empty.svg";
import { DefaultQuery, pageSizes } from "~/domain/query";
import type spuType from "~/domain/Spu";
import type spuQuery from "~/api/spu/spuQuery";
import { useSpu } from "~/api/spu/spuService";
let isFirst = ref(false);
const route = useRoute();
const user = useUserStore();
const ListStore = useListStore();
let categoryId = ref("");
const layer: any = ref(null);
let searchVal: Ref<string> = ref("⊙");
const defaultQuery = () => {
  const q = new DefaultQuery({}) as any;
  q.pageSize = 20;
  q.sort = 0;
  q.storeCount = 0
  return q;
};
let cateOptions:any = ref([])
let brandOptions:any = ref([])
let sortOptions:any = ref([
    { text: '默认排序', value: 0 },
    { text: '价格升序', value: 1 },
    { text: '价格降序', value: 2 },
])
let storeOptions:any = ref([
    { text: '默认库存', value: 0 },
    { text: '有库存', value: 1 },
])
const total = ref(0);
const query: Ref<any> = ref(defaultQuery());
let skuFalg = ref(false);
let sendFalg = ref(false);
let isSeach = ref(true);
let isStateLoading = ref(false);
let pageData: Ref<any[]> = ref([]);
let isFetching: any = ref(false);
const loading = ref(false);
const nuxtApp = useNuxtApp();
const isClient = !nuxtApp.ssrContext;
const pageCount = computed(() => {
  return Math.ceil(total.value / query.value.pageSize);
});
let siteUrl = useRuntimeConfig().public.siteUrl;
let pageNum = ref((route.query.pageNum as any) || 1);
const links = computed(() => {
  const links = [
    {
      rel: "canonical",
      href: `${siteUrl}/search?key=${user.value.publicSearch}&pageNum=${pageNum.value}&pageSize=${query.value.pageSize}`,
    },
  ];
  if (pageNum.value > 1) {
    links.push({
      rel: "prev",
      href: `/search?key=${user.value.publicSearch}&pageNum=${
        pageNum.value - 1
      }&pageSize=${query.value.pageSize}`,
    });
  }
  if (pageNum.value < pageCount.value) {
    links.push({
      rel: "next",
      href: `/search?key=${user.value.publicSearch}&pageNum=${
        pageNum.value + 1
      }&pageSize=${query.value.pageSize}`,
    });
  }
  return links;
});
useHead(() => ({
  title: pageTitle.value,
  link: links,
}));
watch(
  () => route.query.key,
  (newValue: any, oldValue: any) => {
    if (!process.server) {
      isStateLoading.value = true;
      query.value.queryValue = user.value.publicSearch;
      query.value.pageNum = 1;
      window.scrollTo({
        top: 0,
        //behavior: "smooth", // 平滑滚动
      });
      setTimeout(() => {
        getSpuListFun();
      }, 500);
    }
  }
);
let menuRef:any = ref(null)
const onConfirm = () => {
  //  逻辑
  menuRef.value.close();
};

function scrollToBottom() {
  const container: any = layer.value;
  if (container) {
    container.scrollTop = container.scrollHeight;
  }
}

async function getSpuListFun() {
  if (isFetching.value) return;
  if (!isStateLoading.value) {
    loading.value = true;
    setTimeout(() => {
      scrollToBottom();
    }, 100);
  }
  isFetching.value = true;
  skuFalg.value = false;
  sendFalg.value = false;
  const q = JSON.parse(JSON.stringify(query.value));
  const res: any = await selectProductLike(q);
  listMain(res);
}
function linkTo() {
  navigateTo({
    path: "/login",
  });
}
function getParams() {
  user.value.publicSearch = route.query.key as any;
  query.value.queryValue = user.value.publicSearch;
  if (route.query.pageNum && route.query.pageSize) {
    query.value.pageNum = parseInt(route.query.pageNum as any);
    query.value.pageSize = parseInt(route.query.pageSize as any);
  }
}

onMounted(() => {
  const previousRoute: any = route.meta.previousRoute || "";
  if (
    ListStore.value.searcgListData.data &&
    previousRoute.indexOf("/product") > -1
  ) {
    query.value = ListStore.value.searcgListData.query;
    spuArr.value = ListStore.value.searcgListData.data;
    skuFalg.value = ListStore.value.searcgListData.loading;
    nextTick(async () => {
      setTimeout(() => {
        window.scrollTo({
          top: ListStore.value.searcgListData.scrollPosition,
          left: 0, // 水平滚动距离
          //behavior: 'smooth', // 平滑滚动
        });
      }, 100);
    });
  } else {
    isFirst.value = true;
    isStateLoading.value = true;
    getParams();
    // SearchFun();
    getSpuListFun();
  }
  window.addEventListener("scroll", onScroll);
});
onUnmounted(() => {
  window.removeEventListener("scroll", onScroll);
});
onBeforeUnmount(() => {
  ListStore.value.searcgListData.data = spuArr.value;
  ListStore.value.searcgListData.query = query.value;
  ListStore.value.searcgListData.scrollPosition =
    document.documentElement.scrollTop;
  ListStore.value.searcgListData.loading = skuFalg.value;
});

// Use multiple languages ​​in ts
const {
  appContext: {
    config: { globalProperties },
  },
} = getCurrentInstance()!;
const isOpen = ref(true);
function doQuery() {
  const q = JSON.parse(JSON.stringify(query.value));
  navigateTo({
    path: "/search",
    query: {
      key: q.simpleSearch || "",
      pageNum: q.pageNum as number,
      pageSize: q.pageSize as number,
    },
    replace: true,
  });
  getSpuListFun();
}

function SearchFun() {
  if (searchVal.value == user.value.publicSearch) return;
  searchVal.value = JSON.parse(JSON.stringify(user.value.publicSearch));
  query.value.pageNum = 1;
  isStateLoading.value = true;
  if (!user.value.publicSearch) {
    query.value.queryValue = "";
    isSeach.value = false;
    doQuery();
  } else {
    if (!isSeach.value || user.value.publicSearch != route.query.key) {
      query.value.pageNum = 1;
    }
    query.value.queryValue = user.value.publicSearch;
    navigateTo({
      path: "/search",
      query: {
        key: user.value.publicSearch,
        pageNum: query.value.pageNum,
        pageSize: query.value.pageSize,
      },
      replace: true,
    });
    isStateLoading.value = true;
    sendFalg.value = false;
    spuArr.value = [];
    setTimeout(() => {
      getSpuListFun();
    }, 100);
  }
}

// 防抖函数
const debounce = (func: any, delay: any) => {
  let timeout: any;
  return function (...args: any) {
    if (timeout) clearTimeout(timeout);
    timeout = setTimeout(() => {
      func.apply(this, args);
    }, delay);
  };
};

// 滚动事件处理函数
const isBottom = ref(false); // 用于标记是否到底部
const onScroll = debounce((event: any) => {
  if (isFirst.value) {
    return;
  }
  const scrollTop = window.scrollY || document.documentElement.scrollTop; // 当前滚动位置
  const clientHeight = document.documentElement.clientHeight; // 可视区域高度
  const scrollHeight = document.documentElement.scrollHeight; // 整个文档高度

  // 判断是否滚动到底部（允许 10px 的偏差）
  isBottom.value = scrollTop + clientHeight >= scrollHeight - 5 * 280;
  if (isBottom.value) {
    if (
      !loading.value &&
      !skuFalg.value &&
      user.value.isLogin &&
      !isFetching.value
    ) {
      getSpuListFun();
    }
  }
}, 700); // 设置200ms的防抖时间

import { useAll } from "~/api/pubAll/service";
const { selectProductLike } = useAll();
const spuArr = ref<any[]>([]);
// SSR + 客户端自动请求和缓存
getParams();
// const {
//   data: ssrData,
//   error,
//   refresh,
// } = await useAsyncData<any>(`selectProductLike`, () =>
//   selectProductLike({ ...query.value })
// );
// if (ssrData.value) {
//   listMain(ssrData.value);
// } else {
//   getSpuListFun();
// }
function listMain(res: any) {
  if (res.httpCode == 200) {
    if (isStateLoading.value) {
      spuArr.value = [];
      isStateLoading.value = false;
    }
    res.data?.records?.forEach((item: any) => {
      const exists = spuArr.value.some((i: any) => i.id === item.id);
      if (item.priceTemplate?.length > 0) {
        item.priceTemplateArr = JSON.parse(item.priceTemplate);
      }
      if (!exists) {
        spuArr.value.push(item);
      }
    });
    query.value.pageNum++;
    total.value = res.data.total;
    loading.value = false;
    setTimeout(() => {
      sendFalg.value = true;
    }, 100);
    if (
      res.data.records.length == 0 ||
      spuArr.value.length == res.data.total ||
      res.data.records.length.length < query.value.pageSize
    ) {
      skuFalg.value = true;
    }
  }
  setTimeout(() => {
    isFirst.value = false;
  }, 100);
  setTimeout(() => {
    isFetching.value = false;
  }, 500);
}
function sortClick() {
  query.value.pageNum = 1;
  isStateLoading.value = true;
  sendFalg.value = false;
  spuArr.value = [];
  getSpuListFun();
}
</script>
<style scoped lang="scss">
.category-boxs {
  padding-bottom: 1px;
}
.layer {
  width: 100%;
  margin-bottom: 0;
}
.search-wrap {
  min-height: 200px;
  padding-bottom: 66px;
  // overflow-y: auto;
  -webkit-overflow-scrolling: touch;
  :deep(.el-loading-mask) {
    background-color: unset;
  }
}
.el-pagination {
  margin-bottom: 20px;
}
.pagination-wrap {
  display: flex;
  align-items: center;
  justify-content: center;
}
.search-input-wrap {
  padding: 12px 12px 6px 12px;
  display: flex;
  .input-wrap {
    height: 32px;
    background: #fff;
    border-radius: 28px;
    width: 100%;
    border: 1px solid rgba(0, 0, 0, 0.15);
  }
  :deep(.el-input--large .el-input__wrapper) {
    border-radius: 28px;
    box-shadow: unset;
    padding-right: 0;
  }
  :deep(.el-input__inner) {
    height: 30px;
    line-height: 20px;
    padding: 5px 0;
  }
  :deep(.el-input__prefix) {
    font-size: 18px;
  }
  .el-input:deep(.el-input__wrapper.is-focus) {
    box-shadow: unset !important;
  }
  :deep(.el-input-group__append) {
    background: #fff;
    border-radius: 0 25px 25px 0;
    box-shadow: 0 0 0 1px #fff inset;
    color: $mainColor;
    padding: 0 10px;
    .el-icon {
      width: 26px;
      height: 26px;
      font-size: 18px;
      display: flex;
      align-items: center;
      justify-content: center;
    }
  }
}
.category-icon {
  width: 48px;
  height: 40px;
  background: url("@/assets/img/category.png") no-repeat center center;
  background-size: 24px auto;
  display: block;
}
.filter-wrap {
  padding: 0 0px;
  ul {
    display: flex;
    justify-content: space-between;
  }
  li {
    display: flex;
    height: 30px;
    align-items: center;
    width: 20%;
    width: 20%;
    min-width: 20%;
    justify-content: center;
    &.filter {
      i {
        background: url(@/assets/img/filter.svg) no-repeat center center;
        background-size: 14px 14px;
        width: 14px;
        height: 14px;
        &::before,
        &::after {
          display: none;
        }
      }
    }
    i {
      width: 10px;
      height: 11px;
      margin-left: 3px;
      position: relative;
      &.top {
        &::after {
          border-color: transparent transparent $mainColor transparent;
        }
      }
      &.down {
        &::before {
          border-color: $mainColor transparent transparent;
        }
      }
      &::before {
        content: "";
        position: absolute;
        bottom: 0px;
        right: 0px;
        font-size: 0;
        height: 0;
        width: 0;
        border-width: 5px 5px 0;
        border-style: solid dashed;
        border-color: #b9b9b9 transparent transparent;
        overflow: hidden;
        transition: all 0.4s ease 0s;
      }
      &::after {
        content: "";
        position: absolute;
        top: 0px;
        right: 0px;
        font-size: 0;
        height: 0;
        width: 0;
        border-width: 0px 5px 5px 5px;
        border-style: solid dashed solid dashed;
        border-color: transparent transparent #b9b9b9 transparent;
        overflow: hidden;
        transition: all 0.4s ease 0s;
      }
    }
  }
}
</style>
<style lang="scss">
.Category-drawer {
  .el-drawer__header {
    margin-bottom: 0px;
  }
  .el-drawer__body {
    padding-top: 10px;
    padding-left: 0;
    padding-right: 0;
  }
  li {
    padding-left: 20px;
    padding-right: 20px;
  }
  .current {
    background: rgba(255, 0, 79, 0.17);
    color: $mainColor;
  }
}
</style>
