<script setup lang="ts">
let pageTitle: any = ref("HOTKING-个人中心-订单管理");
useHead(() => ({
  title: pageTitle.value,
}));
definePageMeta({
  name: "storehousePage",
});
const user = useUserStore();
import { Right } from "@element-plus/icons-vue";
import empty from "@/assets/img/empty.svg";
user.value.adminTitle = "订单管理";
const navType: any = ref("");
const route = useRoute();
import { DefaultQuery, pageSizes } from "~/domain/query";
import { OrderDim } from "~/dim/order";
import { useOrder } from "~/api/order/orderService";
import type OrderQuery from "~/api/order/orderQuery";
import type Order from "~/domain/Order";
const { listOrders, pullShopOrderLabels, getOrderSummary } = useOrder();
import { type orderSummaryType } from "~/domain/Order";
import { useAll } from "~/api/pubAll/service";
const { getOrderList } = useAll();
const orderSummaryData: any = ref({} as orderSummaryType);
const adminListStore = useAdminListStore();
let loading = ref(false);
let isEnd = ref(false);
let isFirst = ref(true);
const defaultSort = { column: "orderTime", isAsc: "descending" };

navType.value = (route.query.type as string) || "";
const total = ref(0);
const pageData: Ref<any[]> = ref([]);
const query: Ref<any> = ref({
  data: { buyEndTime: "", buyStartTime: "", orderStatus: "", search: "" },
  pageNum: 1,
  pageSize: 10,
});
watch(
  () => navType.value,
  (newValue: any, oldValue: any) => {
    if (!process.server && oldValue != undefined) {
      query.value.data.orderStatus = navType.value;
      doQuery();
    }
  },
  { immediate: true }
);

onMounted(() => {
  const previousRoute: any = route.meta.previousRoute || "";
  if (
    adminListStore.value.storehouseListData.data &&
    previousRoute.indexOf("/home/order/detail") > -1
  ) {
    isFirst.value = false;
    query.value = adminListStore.value.storehouseListData.query;
    pageData.value = adminListStore.value.storehouseListData.data;
    isEnd.value = adminListStore.value.storehouseListData.loading;
    loading.value = false;
    setTimeout(() => {
      window.scrollTo({
        top: adminListStore.value.storehouseListData.scrollPosition,
        left: 0, // 水平滚动距离
        //behavior: 'smooth', // 平滑滚动
      });
    }, 10);
  } else {
    loading.value = true;
    doQuery();
  }
  window.addEventListener("scroll", onScroll);
  getOrderSummaryFun();
});

async function getOrderSummaryFun() {
  // const res: any = await getOrderSummary();
  // if (res.code == 200) {
  //   orderSummaryData.value = res.data;
  // }
}

let isFetching: any = ref(false);
async function doQuery() {
  if (isFetching.value) return;
  isFetching.value = true;
  const q = JSON.parse(JSON.stringify(query.value));
  const res: any = await getOrderList(q);
  if (res.httpCode == 200) {
    setTimeout(() => {
      res.data.records?.forEach((item: Order) => {
        pageData.value.push(item);
      });
      query.value.pageNum++;
      total.value = res.total;
      loading.value = false;
      if (
        res.data.records.length == 0 ||
        pageData.value.length == res.data.total ||
        res.data.records.length < query.value.pageSize
      ) {
        isEnd.value = true;
      }
    }, 300);
  }
  setTimeout(() => {
    isFirst.value = false;
  }, 300);
  setTimeout(() => {
    isFetching.value = false;
  }, 500);
}
function linkTo(orderSn: any ) {
  navigateTo({
    path: "/home/order/detail",
    query: {
      id: orderSn,
    },
  });
}
onUnmounted(() => {
  window.removeEventListener("scroll", onScroll);
});
const navClick = (keys: any) => {
  navType.value = keys;
  loading.value = true;
  query.value.pageNum = 1;
  isEnd.value = false;
  pageData.value = [];
  window.scrollTo({
    top: 0,
    behavior: "smooth", // 平滑滚动
  });
  navigateTo({
    path: "/home/order/list",
    query: { type: keys },
    replace: true,
  });
};

// 滚动事件处理函数
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
    ) {
      doQuery();
    }
  }
}, 200); // 设置200ms的防抖时间

onBeforeUnmount(() => {
  adminListStore.value.storehouseListData.data = pageData.value;
  adminListStore.value.storehouseListData.query = query.value;
  adminListStore.value.storehouseListData.scrollPosition =
    document.documentElement.scrollTop;
  adminListStore.value.storehouseListData.loading = isEnd.value;
});
let orderStatus = ref([
  {
    label: "全部订单",
    value: "",
  },
  {
    label: "审核不通过",
    value: "-2",
  },
  {
    label: "待审核",
    value: "-1",
  },
  {
    label: "待付款",
    value: "0",
  },
  {
    label: "待发货",
    value: "1",
  },
  {
    label: "已发货",
    value: "2",
  },
  {
    label: "已完成",
    value: "3",
  },
  {
    label: "已取消",
    value: "4",
  },
]);
function returnStatus(Status: any) {
  return orderStatus.value.filter((item: any) => Status == item.value)[0].label;
}
</script>
<template>
  <div class="admin-boxs-bg">
    <div class="admin-wrap storehouse-wrap">
      <el-affix :offset="43">
        <div class="storehouse-nav-box">
          <ul class="storehouse-nav">
            <li v-for="(item) in orderStatus" :key="item.value" @click="navClick(item.value)" :class="{'current':navType == item.value}">
              {{ item.label }}
              <!-- <i v-if="orderSummaryData[`${keys}Count`]>0 && (keys=='waitout' || keys=='preout' || keys=='exception' || keys=='cancel')">{{ setNumber(orderSummaryData[`${keys}Count`]) }}</i> -->
            </li>
          </ul>
        </div>
      </el-affix>
      <div class="storehouse-con" v-loading="loading">
        <ul class="sh-ul">
          <li class="sh-li" v-for="(item) in pageData" :key="item.orderCode" @click="linkTo(item.orderSn)">
            <div class="li-code">
              <span>{{item.orderSn}}({{item.createTime.substring(0,19)}})</span>
              <span class="mainColor">{{returnStatus(item.orderStatus)}}</span>
            </div>
            <div class="li-info">
              <div class="sku-wrap">
                <template v-if="item.hktOrderGoods.length<=2">
                  <div class="sku-img-item" v-for="i in item.hktOrderGoods" :key="i">
                    <NuxtImg :src="i.goodsImg" loading="lazy" placeholder="/img/loading.png"></NuxtImg>
                  </div>
                </template>
                <template v-else>
                  <div class="sku-img-item" v-for="(i,d) in item.hktOrderGoods" :key="i" v-show="d<=1">
                    <template v-if="d<=1">
                      <NuxtImg :src="i.goodsImg" loading="lazy" placeholder="/img/loading.png"></NuxtImg>
                    </template>
                  </div>
                  <div class="sku-img-more">
                    更多 <el-icon>
                      <Right />
                    </el-icon>
                  </div>
                </template>

                <div class="sku-img-info" v-if="item.hktOrderGoods.length==1">
                  <p class="text-overflow">{{item.hktOrderGoods[0].goodsName}}</p>
                  <p class="text-overflow">制造商料号：{{item.hktOrderGoods[0].materialSn}}</p>
                  <p class="text-overflow">我的料号：{{item.hktOrderGoods[0].customerSn}}</p>
                </div>
              </div>
              <div class="sku-price">
                <h3 class="price">¥150.11</h3>
                <p>×2500 pcs</p>
              </div>
            </div>
          </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>
    </div>
  </div>
</template>
<style scoped lang="scss">
.storehouse-wrap {
  color: #333;
  padding: 0 0px 66px;
  :deep(.el-loading-mask) {
    top: 150px;
  }
  .el-affix {
    :deep(.el-affix--fixed) {
      top: 44px !important;
      .storehouse-nav {
        background: #fff;
        box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
      }
    }
  }
  .storehouse-nav-box {
    overflow: hidden;
    width: 100%;
    height: 38px;
    margin-bottom: 12px;
    margin-top: -6px;
  }
  .storehouse-nav {
    display: flex;
    flex-direction: row;
    height: 44px;
    padding: 0 15px;
    overflow: auto;
    li {
      font-size: 14px;
      height: 38px;
      line-height: 41px;
      position: relative;
      padding: 0 10px;
      min-width: max-content;
      &.current {
        color: $mainColor;
      }
      i {
        padding: 0 5px;
        height: 16px;
        color: #fff;
        background: $mainColor;
        position: absolute;
        font-size: 10px;
        border-radius: 30px;
        top: 0px;
        right: -8px;
        min-width: 16px;
        display: flex;
        align-items: center;
        justify-content: center;
        font-style: unset;
      }
    }
  }
  .storehouse-con {
    font-size: 14px;
    padding: 0 12px;
    .li-info {
      display: flex;
      justify-content: space-between;
    }
    .sku-price {
      display: flex;
      justify-content: center;
      flex-direction: column;
      h3 {
        font-weight: bold;
        font-size: 20px;
      }
      p {
        color: #666;
        text-align: right;
      }
    }
    .sh-li {
      background: #fff;
      border-radius: 4px;
      padding: 12px;
      & + .sh-li {
        margin-top: 12px;
      }
    }
    .li-code {
      display: flex;
      justify-content: space-between;
      margin-bottom: 8px;
    }
    .sku-wrap {
      display: flex;
      align-items: center;
    }
    .sku-img-more {
      width: 60px;
      min-width: 60px;
      height: 60px;
      border-radius: 4px;
      margin-left: 8px;
      background: #e8e8e8;
      color: #666;
      display: flex;
      align-items: center;
      justify-content: center;
    }
    .sku-img-item {
      width: 60px;
      min-width: 60px;
      height: 60px;
      position: relative;
      border-radius: 4px;
      & + .sku-img-item {
        margin-left: 8px;
      }
      p {
        background: rgba($color: #000000, $alpha: 0.5);
        color: #fff;
        border-radius: 50px;
        min-width: 15px;
        padding: 0 5px;
        height: 15px;
        font-size: 10px;
        position: absolute;
        bottom: 6px;
        left: 0;
        right: 0;
        margin: auto;
        line-height: 15px;
        font-weight: 400;
        text-align: center;
        display: flex;
        align-items: center;
        justify-content: center;
        width: max-content;
      }
      img {
        flex-shrink: 1;
        width: 100%;
        height: 100%;
        -o-object-fit: contain;
        object-fit: contain;
        border-radius: 4px;
      }
    }
    .sku-img-info {
      margin-left: 8px;
      line-height: 20px;
      display: flex;
      flex-direction: column;
      justify-content: center;
      font-size: 12px;
      max-width: 170px;
      p {
        height: 20px;
        line-height: 20px;
        span {
          margin-right: 2px;
          color: #666;
        }
      }
    }
  }
}
</style> 
