<script setup lang="ts">
let pageTitle: any = ref("HOTKING-个人中心-我的收藏");
useHead(() => ({
  title: pageTitle.value,
}));
const user = useUserStore();
user.value.adminTitle = "我的收藏";
import empty from "@/assets/img/empty.svg";
import { useAll } from "~/api/pubAll/service";
const { getCollectList, deleteFavorites, saveHktFavorites } = useAll();
import { showLoadingToast, closeToast } from "vant";
import type msgListQuery from "~/api/msg/msgQuery";
import { useMsg } from "~/api/msg/msgService";
import type msgType from "~/domain/Msg";
import { DefaultQuery, pageSizes } from "~/domain/query";
import { useSpu } from "~/api/spu/spuService";
import type spuQuery from "~/api/spu/spuQuery";
const { getSpuList } = useSpu();
const adminListStore = useAdminListStore();
const route = useRoute();
let loading = ref(false);
let isEnd = ref(false);
let isFirst = ref(true);
let isFetching: any = ref(false);
let total = ref(0);
const pageData: Ref<any[]> = ref([]);
const open = ref({
  detail: false,
});
const query: Ref<any> = ref({
  categoryName: "",
  pageNum: 1,
  pageSize: 10,
});
let detailInfo: Ref<any> = ref({}); //默认sku信息
async function getSpuListFun() {
  if (isFetching.value) return;
  isFetching.value = true;
  const q = JSON.parse(JSON.stringify(query.value));
  const res: any = await getCollectList(q);
  if (res.httpCode == 200) {
    setTimeout(() => {
      res.data?.records.forEach((item: any, idx: number) => {
        console.log(idx);
        let priceTemplateArr = JSON.parse(
          item.priceTemplate.replace(/^\\?"/, "").replace(/"\\?$/, "")
        );
        item.priceTemplateArr = priceTemplateArr;
        pageData.value.push(item);
      });
      query.value.pageNum++;
      total.value = res.total;
      loading.value = false;
      if (
        res.data?.records.length == 0 ||
        pageData.value.length == res.total ||
        res.data?.records.length < query.value.pageSize
      ) {
        isEnd.value = true;
      }
    }, 300);
  }
  setTimeout(() => {
    isFirst.value = false;
  }, 300);
  setTimeout(() => {
    isFetching.value = false;
  }, 500);
}
async function collectFun(item: any, idx: number) {
  let res: any = null;
  // 显示加载
  const toast = showLoadingToast({
    message: "",
    forbidClick: true,
    duration: 0,
  });
  res = await deleteFavorites({ id: item.id });
  toast.close();
  if (res.httpCode == 200) {
    ElMessage.success("取消成功");
    total.value -= 1;
    pageData.value.splice(idx, 1);
  }
}
function pcDialog(item: any) {
  navigateTo({
    path:`/product`,query:{code:item.goodsId}
  })
  // open.value.detail = true;
  // detailInfo.value = item;
}
onMounted(() => {
  const previousRoute: any = route.meta.previousRoute || "";
  if (
    adminListStore.value.collectListData.data &&
    previousRoute.indexOf("/detail") > -1
  ) {
    isFirst.value = false;
    query.value = adminListStore.value.collectListData.query;
    pageData.value = adminListStore.value.collectListData.data;
    isEnd.value = adminListStore.value.collectListData.loading;
    loading.value = false;
    setTimeout(() => {
      window.scrollTo({
        top: adminListStore.value.collectListData.scrollPosition,
        left: 0, // 水平滚动距离
      });
    }, 10);
  } else {
    loading.value = true;
    getSpuListFun();
  }
  window.addEventListener("scroll", onScroll);
});
onUnmounted(() => {
  window.removeEventListener("scroll", onScroll);
});
// 滚动事件处理函数
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 - 100;
  if (isBottom.value) {
    if (
      !loading.value &&
      !isEnd.value &&
      user.value.isLogin &&
      !isFetching.value
    ) {
      getSpuListFun();
    }
  }
}, 500); // 设置200ms的防抖时间

onBeforeUnmount(() => {
  adminListStore.value.collectListData.data = pageData.value;
  adminListStore.value.collectListData.query = query.value;
  adminListStore.value.collectListData.scrollPosition =
    document.documentElement.scrollTop;
  adminListStore.value.collectListData.loading = isEnd.value;
});

function done(){
  cancel();
}
function cancel() {
  Object.keys(open.value).forEach(
    (key) => (open.value[key as keyof typeof open.value] = false)
  );
}
</script>
<template>
  <div class="admin-boxs-bg">
    <div class="admin-wrap collect-wrap" v-loading="loading">
      <ul class="product-ul">
        <li class="product-li" v-for="(item,idx) in pageData" :id="`item-${item.spuCode}`" :key="item.spuCode">
          <NuxtLink :to="{path:`/product`,query:{code:item.goodsId}}">
            <div class="product-img">
              <NuxtImg :src="item.goodsImg" :alt="item.name" loading="lazy" placeholder="/img/loading.png"></NuxtImg>
              <img v-if="item.goodsImg" :src="item.goodsImg" style="width:0;height: 0;">
            </div>
            <div class="product-info">
              <h3 :title="item.name" class="title">{{item.goodsName}}</h3>
              <p>品牌：{{item.brandName}}</p>
              <p>型号：{{item.materialSn}}</p>
              <p>封装：{{item.packageSpecification}}</p>
              <p>库存：现货</p>
              <p class="price"><span class="mainColor">¥{{item.priceTemplateArr[0].price}}起</span></p>
            </div>
          </NuxtLink>
          <el-button class="btn_main addCart" @click="pcDialog(item)">
            加购
          </el-button>
          <i class="collect-icon" @click="collectFun(item,idx)"></i>
        </li>
      </ul>

      <img class="loading" src="@/assets/img/ico/loading.gif" v-if="!isEnd && user.isLogin && !isFirst && pageData.length>0" />
      <template v-if="pageData.length<1 && isEnd">
        <el-empty description=" " :image="empty" :image-size="350">
          <div class="noContent">
            没有数据
          </div>
        </el-empty>
      </template>
      <p class="loading-text" v-else-if="isEnd && user.isLogin">--&nbsp;已经到底了&nbsp;--</p>
    </div>
    <el-drawer :title="detailInfo.goodsName" v-model="open.detail" size="auto" direction="btt" append-to-body class="detail-drawer" @close="open.detail = false" :with-header="false" :z-index="2000">
      <editCart :detailInfo="detailInfo" @done="done"></editCart>
    </el-drawer>
  </div>
</template>
<style scoped lang="scss">
.collect-wrap {
  padding: 12px 0px 66px;
  background: #f7f7f7;
}
.product-li {
  position: relative;
  .collect-icon {
    width: 40px;
    height: 40px;
    background: url(@/assets/img/icon/sc_yes.svg) no-repeat center center;
    background-size: 22px 22px;
    display: block;
    position: absolute;
    z-index: 2;
    right: 6px;
    top: 0;
  }
}
.product-info {
  position: relative;
}
</style> 
