<template>
  <z-paging
    ref="paging"
    v-model="dataList"
    use-virtual-list
    :force-close-inner-list="true"
    cell-height-mode="dynamic"
    safe-area-inset-bottom
    @query="queryList"
  >
    <template #top>
      <TopNavBar titleAlign="left">
        <template #title>
          <Tabs
            :tabs="tabList"
            :defaultActive="currentTabIndex"
            @change="handleTabChange"
          />
        </template>
      </TopNavBar>
    </template>

    <template #empty>
      <CustomEmpty statusText="您暂无订单" />
    </template>

    <OrderCard
      v-for="(item, index) in dataList"
      :key="item.id || index"
      :orderData="item"
      @click="handleOrderClick"
    />
  </z-paging>
</template>

<script setup>
import { ref } from "vue";
import TopNavBar from "@/components/TopNavBar/index.vue";
import Tabs from "./components/Tabs/index.vue";
import OrderCard from "./components/OrderCard/index.vue";
import CustomEmpty from "./components/CustomEmpty/index.vue";
import { userOrderList, userWorkOrderList } from "@/request/api/OrderApi";

// Tab配置
const tabList = ref([
  { label: "全部订单", value: "all" },
  { label: "服务工单", value: "service" },
]);

// 当前状态
const currentTabIndex = ref(0);
const dataList = ref([]);
const paging = ref(null);

const queryList = async (pageNum, pageSize) => {
  try {
    let apiCall;
    // 根据当前Tab选择不同的API
    if (currentTabIndex.value === 0) {
      // 全部订单
      apiCall = userOrderList({ pageNum, pageSize });
    } else {
      // 服务工单
      apiCall = userWorkOrderList({ pageNum, pageSize });
    }

    const res = await apiCall;
    console.log("API响应:", res);

    if (res && res.data && res.data.records) {
      const records = res.data.records;

      // 完成数据加载，第二个参数表示是否还有更多数据
      paging.value.complete(records);
    } else {
      // 没有数据
      paging.value.complete([]);
    }
  } catch (error) {
    console.error("查询列表失败:", error);
    // 加载失败
    paging.value.complete(false);
  }
};

// Tab切换处理
const handleTabChange = ({ index }) => {
  console.log("Tab切换到:", index);
  currentTabIndex.value = index;
  // 清空当前数据并重新加载
  dataList.value = [];
  paging.value.reload();
};

// 处理订单点击
const handleOrderClick = ({ orderId }) => {
  // 这里可以添加订单详情跳转逻辑
  uni.navigateTo({
    url: `/pages/order/detail?orderId=${orderId}`,
  });
};
</script>

<style scoped lang="scss">
@import "./styles/list.scss";
</style>
