<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="Search by model or package" @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 title="筛选">
            <van-field v-model="fieldValue" is-link readonly label="城市" placeholder="选择城市" @click="showPicker = true" />
            <van-popup v-model:show="showPicker" destroy-on-close round position="bottom">
              <van-picker :model-value="pickerValue" :columns="columns" @cancel="showPicker = false" @confirm="onConfirm2" />
            </van-popup>
          </van-dropdown-item>
        </van-dropdown-menu>
      </div> -->
      <div class="layer search-wrap mb10 mt1" v-loading="isStateLoading" ref="layer">
        <template v-if="spuArr.length>0">
          <div class="layer-content">
            <List :spuArr="spuArr" :zrTitle="zrTitle" :zrTitleDw="zrTitleDw"></List>
            <img class="loading" src="@/assets/img/ico/loading.gif" v-if="!skuFalg && isClient" />
            <p class="loading-text" v-if="skuFalg && testData.length<query.size">--&nbsp;No more content&nbsp;--</p>
          </div>
          <nav class="pagination" aria-label="Pagination Navigation" v-if="!isClient">
            <!-- SEO 友好的分页链接 -->
            <a v-for="page in pageCount" :key="page" :href="`/search?key=${user.publicSearch}&current=${page}&size=${query.size}`" :class="{ active: page === query.current }" :aria-current="page === query.current ? 'page' : false">
              Page {{ page }}
            </a>
          </nav>
        </template>
        <template v-if="spuArr.length<1 && sendFalg">
          <el-empty description=" " :image="empty" :image-size="350">
            <div class="noContent">
              No products found for <span class="mainColor">"{{route.query.cname}}"</span>
            </div>
          </el-empty>
        </template>
      </div>
    </div>
  </div>
</template>
<script setup lang="ts">
import { useAll } from "~/api/pubAll/service";
const { selectFindMap } = useAll();
import { Search } from "@element-plus/icons-vue";
import empty from "@/assets/img/empty.svg";
let isFirst = ref(false);
const route = useRoute();
const user = useUserStore();
const ListStore = useListStore();
const layer: any = ref(null);
let searchVal: Ref<string> = ref("⊙");
let sortOptions: any = ref([
  { text: "Default Sort", value: 0 },
  { text: "Price: Low to High", value: 1 },
  { text: "Price: High to Low", value: 2 },
]);
let storeOptions: any = ref([
  { text: "Default Stock", value: 0 },
  { text: "In Stock", value: 1 },
]);
const total = ref(0);
const query: Ref<any> = ref({
  current: route.query.current || 1,
  size: route.query.size || 10,
  records: [
    {
      searchValue: route.query.key || "",
      categoryId: route.query.categoryId || "",
    },
  ],
});

const columns = [
  { text: "Hangzhou", value: "Hangzhou" },
  { text: "Ningbo", value: "Ningbo" },
  { text: "Wenzhou", value: "Wenzhou" },
  { text: "Shaoxing", value: "Shaoxing" },
  { text: "Huzhou", value: "Huzhou" },
];
const fieldValue = ref("");
const showPicker = ref(false);
const pickerValue = ref<any[]>([]);
const onConfirm2 = ({ selectedValues, selectedOptions }: any) => {
  showPicker.value = false;
  pickerValue.value = selectedValues;
  fieldValue.value = selectedOptions[0].text;
};

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);
});
user.value.adminTitle = route.query.cname as any;
watch(
  () => route.query.key,
  (newValue: any, oldValue: any) => {
    if (!process.server) {
      isStateLoading.value = true;
      query.value.records[0].searchValue = user.value.publicSearch;
      query.value.current = 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 selectFindMap(q);
  listMain(res);
}
function linkTo() {
  navigateTo({
    path: "/login",
  });
}
function getParams() {
  user.value.publicSearch = route.query.key as any;
  query.value.records[0].searchValue = user.value.publicSearch || " ";
  query.value.records[0].categoryId = route.query.code || " ";
  if (route.query.current && route.query.size) {
    query.value.current = parseInt(route.query.current as any);
    query.value.size = parseInt(route.query.size 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 || "",
      current: q.current as number,
      size: q.size as number,
    },
    replace: true,
  });
  getSpuListFun();
}

function SearchFun() {
  navigateTo({
    path: "/search",
    query: {
      key: user.value.publicSearch,
      current: query.value.current,
      size: query.value.size,
    },
  });
}

// 防抖函数
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 && !isFetching.value) {
      getSpuListFun();
    }
  }
}, 700); // 设置200ms的防抖时间

let zrTitle: any = ref([]);
let zrTitleDw: any = ref([]);
const spuArr = ref<any[]>([]);
const testData: any = ref([]);
let nAllSearchList: any = ref([]);
let initData: any = ref();
let SortData: any = ref({});
let newFilter: any = ref({
  goodsType: [],
  packageSpecification: [],
  pp: [[], [], [], [], [], [], [], [], [], []],
});
let pp: any = ref([[], [], [], [], [], [], [], [], [], []]);
getParams();
function listMain(res: any) {
  if (res.httpCode == 200) {
    if (isStateLoading.value) {
      spuArr.value = [];
      isStateLoading.value = false;
    }
    if (Object.keys(res.data).length == 0) {
      skuFalg.value = true;
      isFirst.value = false;
      isFetching.value = false;
      sendFalg.value = true;
      nAllSearchList.value = [];
      initData.value = {};
      return;
    }
    if (isFirst.value) {
      initData.value = {};
      nAllSearchList.value = [];
    }
    testData.value = [];
    if (isFirst.value) {
      spuArr.value = res.data?.page?.records || [];
    } else {
      res.data?.page?.records.forEach((item: any) => {
        spuArr.value.push(item);
      });
    }
    testData.value = res.data?.page?.records || [];
    initData.value = res.data;
    SortData.value = res.SortData;
    for (const key in SortData.value) {
      if (key.indexOf("attr") > -1) {
        var aa: any = key.replace("attr", "");
        newFilter.value.pp[aa - 1] = SortData.value[key];
      }
    }
    newFilter.value.goodsType = SortData.value?.goodsType;
    newFilter.value.packageSpecification = SortData.value?.packageSpecification;
    
    total.value = res.data?.page?.total || 0;
    zrTitle.value = [];
    zrTitleDw.value = [];
    for (const key2 in initData.value?.typeHead2) {
      if (key2.indexOf("attr") > -1) {
        let str = initData.value.typeHead2[key2] || "";
        initData.value.typeHead2[key2] = str
          .replace(/\s*[\(（][^\)\）]*[\)\）]/g, "")
          .trim();
        zrTitle.value.push({
          label: key2,
          value: initData.value.typeHead2[key2],
        });
        zrTitleDw.value.push({
          label: key2,
          value: initData.value.typeHead3[key2]
            .replace("（", "(")
            .replace("）", ")"),
        });
      }
    }
    query.value.current++;
    loading.value = false;
    setTimeout(() => {
      sendFalg.value = true;
    }, 100);
    if (
      testData.value.length == 0 ||
      spuArr.value.length == total.value ||
      testData.value.length < query.value.size
    ) {
      skuFalg.value = true;
    }
  }
  setTimeout(() => {
    isFirst.value = false;
  }, 100);
  setTimeout(() => {
    isFetching.value = false;
  }, 500);
}
function sortClick() {
  loading.value = false;
  query.value.current = 1;
  isStateLoading.value = true;
  sendFalg.value = false;
  skuFalg.value = false;
  spuArr.value = [];
  isFetching.value = false;
  getSpuListFun();
}
</script>
<style scoped lang="scss">
.category-boxs-bg {
  background: #f4f4f4;
}
.category-boxs {
  padding-bottom: 1px;
  background: #f4f4f4 !important;
}
.layer {
  width: 100%;
  margin-bottom: 0;
}
.search-wrap {
  min-height: 200px;
  padding-bottom: 10px;
  padding-top: 12px;
  // 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: 6px 12px 12px 12px;
  background: #fff;
  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>
