<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="query.companyName" size="large" placeholder="Search by company name" @keyup.enter.native="SearchFun">
          <template #append>
            <div @click="SearchFun">
              <el-icon>
                <Search />
              </el-icon>
            </div>
          </template>
        </el-input>
      </div>
      <div class="layer search-wrap mb10 mt1" v-loading="isStateLoading" ref="layer">
        <template v-if="spuArr.length>0">
          <div class="layer-content">
            <ul class="product-ul">
              <li class="product-li" v-for="(item) in spuArr" :id="`item-${item.id}`" :key="item.id">
                <a href="javascript:;">
                  <div class="product-info">
                    <h3 class="title">Company Name: <span>{{ item.companyName }}</span></h3>
                    <p>Authorization No.: <span>{{ item.authority }}</span></p>
                    <p>Company Address: <span>{{ item.address }}</span></p>
                    <p>Authorization Start: <span>{{ item.effectiveStartTime.substring(0,11) }}</span></p>
                    <p>Authorization End: <span>{{ item.effectiveEndTime.substring(0,11) }}</span></p>
                    <p>Certificate: <a :href="item.pdfUrl" v-if="item.pdfUrl" target="blank">View</a></p>
                  </div>
                </a>
              </li>
            </ul>
            <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 results
            </div>
          </el-empty>
        </template>
      </div>
    </div>
  </div>
</template>
<script setup lang="ts">
import { useAll } from "~/api/pubAll/service";
const { supplierSelect, 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();
user.value.adminTitle = "Supplier Search";
const ListStore = useListStore();
const layer: any = ref(null);
let searchVal: Ref<string> = ref("⊙");
const total = ref(0);
const query: Ref<any> = ref({
  current: route.query.current || 1,
  size: route.query.size || 10,
  companyName: route.query.key || "",
});
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);
});
watch(
  () => route.query.key,
  (newValue: any, oldValue: any) => {
    if (!process.server) {
      isStateLoading.value = true;
      query.value.companyName = route.query.key as any;
      query.value.current = 1;
      window.scrollTo({
        top: 0,
        //behavior: "smooth", // 平滑滚动
      });
      setTimeout(() => {
        getSpuListFun();
      }, 500);
    }
  }
);
let menuRef: any = ref(null);
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 supplierSelect(q);
  listMain(res);
}
function linkTo() {
  navigateTo({
    path: "/login",
  });
}
function getParams() {
  query.value.companyName = user.value.publicSearch || " ";
  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 || "";
  isFirst.value = true;
  isStateLoading.value = true;
  getParams();
  // SearchFun();
  getSpuListFun();
  window.addEventListener("scroll", onScroll);
});
onUnmounted(() => {
  window.removeEventListener("scroll", onScroll);
});
onBeforeUnmount(() => {});

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

function SearchFun() {
  testData.value = [];
  isFirst.value = true;
  query.value.current = 1;
  isStateLoading.value = true;
  if (!query.value.companyName) {
    isSeach.value = false;
    doQuery();
  } else {
    if (!isSeach.value || query.value.companyName != route.query.key) {
      query.value.current = 1;
    }
    navigateTo({
      path: "/suppliers",
      query: {
        key: query.value.companyName,
        current: query.value.current,
        size: query.value.size,
      },
      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 && !isFetching.value) {
      getSpuListFun();
    }
  }
}, 700); // 设置200ms的防抖时间

let zrTitle: any = ref([]);
let zrTitleDw: any = ref([]);
const spuArr = ref<any[]>([]);
const testData: any = ref([]);
getParams();
function listMain(res: any) {
  if (res.httpCode == 200) {
    if (isStateLoading.value) {
      spuArr.value = [];
      isStateLoading.value = false;
    }
    if (Object.keys(res.data.records).length == 0) {
      skuFalg.value = true;
      isFirst.value = false;
      isFetching.value = false;
      sendFalg.value = true;
      return;
    }
    total.value = res.data.total || 0;
    testData.value = res.data.records
    if (isFirst.value) {
      spuArr.value = res.data.records;
    } else {
      res.data.records?.forEach((item: any) => {
        spuArr.value.push(item);
      });
    }
    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);
}
</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;
  }
}
.product-ul .product-li{
  a{
    padding-left:0;
  }
}
</style>
