<template>
  <div class="flex h-dvh flex-col overflow-hidden bg-linear-[180deg,#E8FFF1_0%,#F5F7FA_186px]">
    <TopNavBar :title="t('service.title')" />

    <div class="min-h-0 flex-1 overflow-y-auto scrollbar-none [-ms-overflow-style:none] [&::-webkit-scrollbar]:hidden">
      <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
        <CustomEmpty v-if="showEmpty" emptyIcon="https://oss.nianxx.cn/mp/static/version_101/order/service_empty.png"
          :statusText="t('service.empty.list')" />

        <van-list v-else v-model:loading="loading" v-model:error="listError" :finished="finished"
          :immediate-check="false" :finished-text="t('common.state.noMore')"
          :error-text="t('common.errors.loadFailedRetry')" @load="onLoad">
          <OrderCard v-for="(item, index) in dataList" :key="item.id || index" :orderData="item" />
        </van-list>
      </van-pull-refresh>
    </div>
  </div>
</template>

<script setup>
import { computed, onMounted, ref } from "vue";
import { useI18n } from "vue-i18n";
import { userWorkOrderList } from "@/api/workOrder";
import TopNavBar from "@/components/TopNavBar/index.vue";
import CustomEmpty from "@/components/CustomEmpty/index.vue";
import OrderCard from "./components/OrderCard/index.vue";

const { t } = useI18n();
const PAGE_SIZE = 10;
const dataList = ref([]);
const currentPage = ref(1);
const loading = ref(false);
const finished = ref(false);
const refreshing = ref(false);
const listError = ref(false);

const showEmpty = computed(() => {
  return !loading.value && !refreshing.value && finished.value && dataList.value.length === 0;
});

const finishLoading = () => {
  loading.value = false;
  refreshing.value = false;
};

const queryList = async (pageNum = currentPage.value, pageSize = PAGE_SIZE) => {
  try {
    const res = await userWorkOrderList({ pageNum, pageSize });
    console.log("API响应:", res);

    const records = Array.isArray(res?.data?.records) ? res.data.records : [];
    const total = Number(res?.data?.total ?? 0);
    const hasTotal = Number.isFinite(total) && total > 0;

    if (pageNum === 1) {
      dataList.value = records;
    } else {
      dataList.value = [...dataList.value, ...records];
    }

    finished.value =
      records.length < pageSize || (hasTotal && dataList.value.length >= total);
    if (!finished.value) {
      currentPage.value = pageNum + 1;
    }
    listError.value = false;
  } catch (error) {
    console.error("查询列表失败:", error);
    listError.value = true;
  } finally {
    finishLoading();
  }
};

const reloadList = () => {
  currentPage.value = 1;
  finished.value = false;
  listError.value = false;
  loading.value = true;
  queryList(1);
};

const onLoad = () => {
  queryList();
};

const onRefresh = () => {
  reloadList();
};

onMounted(() => {
  reloadList();
});
</script>

<style scoped lang="scss"></style>
