<template>
  <div class="category-boxs-bg">
    <!-- 顶部大图 -->
    <section class="banner"></section>
    <div class="max-w1280 category-boxs">
      <img src="@/assets/img/loading.svg" width="0" height="0" />
      <!--  @scroll="onScroll" -->
      <div class="news-nav-tab">
        <NuxtLink to="/information">Industry Insights</NuxtLink>
        <a href="javascript:;" class="current">Company News</a>
      </div>
      <div class="layer search-wrap mb20" v-loading="isStateLoading" ref="layer">
        <template v-if="spuArr.length>0">
          <div class="layer-content">
            <div class="news-list">
              <NuxtLink v-for="(item, index) in spuArr" :key="index" class="news-item" :to="{path:`/news/detail`,query:{code:item.id}}">
                <!-- 新闻图片 -->
                <div class="news-img">
                  <img :src="item.img" :alt="item.title" class="img-content">
                </div>

                <div class="news-content">
                  <div class="news-date">
                    <svg class="date-icon" viewBox="0 0 24 24" width="14" height="14">
                      <path d="M19 3h-1V1h-2v2H8V1H6v2H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm0 16H5V8h14v11zM9 10H7v2h2v-2zm4 0h-2v2h2v-2zm4 0h-2v2h2v-2zm-8 4H7v2h2v-2zm4 0h-2v2h2v-2zm4 0h-2v2h2v-2z" fill="#999" />
                    </svg>
                    <span class="date-text">{{ item.publishTime }}</span>
                  </div>
                  <h3 class="news-title">{{ item.title }}</h3>
                  <p class="news-desc">{{ item.description }}</p>
                </div>
              </NuxtLink>
            </div>
            <img class="loading" src="@/assets/img/ico/loading.gif" v-if="!skuFalg" />
            <p class="loading-text" v-if="skuFalg">--&nbsp;No more content&nbsp;--</p>
            <p class="loading-text" v-if="skuFalg && spuArr.length<query.pageSize">--&nbsp;No more content&nbsp;--</p>
          </div>
        </template>
        <template v-if="spuArr.length<1 && sendFalg">
          <el-empty description=" " :image="empty" :image-size="350">
            <div class="noContent">
              No data
            </div>
          </el-empty>
        </template>
      </div>
    </div>
  </div>
</template>
<script setup lang="ts">
import { useAll } from "~/api/pubAll/service";
const { getNewsList } = useAll();
import empty from "@/assets/img/empty.svg";
const route = useRoute();
const user = useUserStore();
user.value.adminTitle = "Company News";
const ListStore = useListStore();
let isFirst = ref(false);
let spuArr: Ref<any[]> = ref([]);
const layer: any = ref(null);
const cid: any = ref(40);
const total = ref(0);
const query: Ref<any> = ref({
  current: 1,
  records: [{ cid: cid.value, language: 2 }],
  size: 12,
});
let skuFalg = ref(false);
let sendFalg = ref(false);
let isStateLoading = ref(false);
let pageData: Ref<any[]> = ref([]);

function scrollToBottom() {
  const container: any = layer.value;
  if (container) {
    container.scrollTop = container.scrollHeight;
  }
}
let isFetching: any = ref(false);
async function getNewsListFun() {
  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 getNewsList(q);

  if (res.httpCode == 200) {
    if (isStateLoading.value) {
      spuArr.value = [];
      isStateLoading.value = false;
    }
    let pageDataArr: any = [];
    res.data.records?.forEach((item: any) => {
      spuArr.value.push(item);
      pageDataArr.push(item);
    });
    if (pageDataArr.length > 0) {
      pageData.value = JSON.parse(JSON.stringify(pageDataArr));
    }

    query.value.current++;
    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 < query.value.size
    ) {
      skuFalg.value = true;
    }
  }
  setTimeout(() => {
    isFirst.value = false;
  }, 100);
  setTimeout(() => {
    isFetching.value = false;
  }, 500);
}

function getParams() {
  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(async () => {
  const previousRoute: any = route.meta.previousRoute || "";
  if (
    ListStore.value.newsListData.data &&
    previousRoute.indexOf("/detail") > -1
  ) {
    query.value = ListStore.value.newsListData.query;
    spuArr.value = ListStore.value.newsListData.data;
    skuFalg.value = ListStore.value.newsListData.loading;
    nextTick(async () => {
      setTimeout(() => {
        window.scrollTo({
          top: ListStore.value.newsListData.scrollPosition,
          left: 0, // 水平滚动距离
          //behavior: 'smooth', // 平滑滚动
        });
      }, 100);
    });
  } else {
    isFirst.value = true;
    isStateLoading.value = true;
    getParams();
    doQuery();
  }
  window.addEventListener("scroll", onScroll);
});
onUnmounted(() => {
  window.removeEventListener("scroll", onScroll);
});
onBeforeUnmount(() => {
  ListStore.value.newsListData.data = spuArr.value;
  ListStore.value.newsListData.query = query.value;
  ListStore.value.newsListData.scrollPosition =
    document.documentElement.scrollTop;
  ListStore.value.newsListData.loading = skuFalg.value;
});
const {
  appContext: {
    config: { globalProperties },
  },
} = getCurrentInstance()!;
function doQuery() {
  const q = JSON.parse(JSON.stringify(query.value));
  navigateTo({
    path: "/news",
    query: {
      current: q.current as number,
      size: q.size as number,
    },
  });
  getNewsListFun();
}

const loading = ref(false);
// 防抖函数
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) {
      getNewsListFun();
    }
  }
}, 700); // 设置200ms的防抖时间
</script>
<style scoped lang="scss">
.category-boxs-bg {
  .banner {
    height: 200px;
    background-position: center;
    background-repeat: no-repeat;
    background: url(~/assets/img/banner/banner_pub.png) no-repeat center center;
    background-size: 100% auto;
  }
}
.category-boxs {
  background: #fafafa !important;
}
.search-wrap {
  min-height: 150px;
  margin-top: 20px;
}
/* 新闻列表 */
.news-list {
  display: flex;
  flex-direction: column;
}

/* 新闻项：移动端通用内边距 */
.news-item {
  display: flex;
  flex-direction: row;
  align-items: flex-start;
  margin-bottom: 12px;
  padding: 12px 12px;
  background-color: #fff;
  text-decoration: none;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.02);
}

/* 新闻图片：375屏最优80px */
.news-img {
  width: 80px;
  height: 80px;
  border-radius: 6px;
  overflow: hidden;
  flex-shrink: 0;
  margin-right: 12px;
}

.img-content {
  width: 100%;
  height: 100%;
  object-fit: cover;
  display: block;
}

/* 新闻内容区 */
.news-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  min-height: 80px;
}

/* 日期栏：14px 弱化处理 */
.news-date {
  display: flex;
  align-items: center;
  margin-bottom: 4px;
}

.date-icon {
  margin-right: 4px;
}

.date-text {
  font-size: 12px;
  color: #999999;
}

/* 核心：新闻标题18px（375屏黄金尺寸） */
.news-title {
  font-size: 14px;
  font-weight: 500;
  color: #333333;
  line-height: 1.4;
  margin-bottom: 4px;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

/* 新闻摘要：16px 次要信息 */
.news-desc {
  font-size: 12px;
  color: #666666;
  line-height: 1.3;
  display: -webkit-box;
  -webkit-line-clamp: 1;
  -webkit-box-orient: vertical;
  overflow: hidden;
}
</style>
