<template>
  <view class="order-page">
    <!-- 顶部导航栏 - 固定定位 -->
    <view class="top-nav-fixed">
      <TopNavBar>
        <template #title>
          <Tabs
            :tabs="tabList"
            :defaultActive="currentTabIndex"
            @change="handleTabChange"
          />
        </template>
      </TopNavBar>
    </view>

    <!-- 工单列表区域 - 全屏模式 -->
    <OrderList
      :orderList="currentOrderList"
      :hasMore="hasMore"
      :isLoading="isLoading"
      :currentTab="currentTab"
      :emptyText="getEmptyText()"
      :useVirtualList="false"
      :virtualListHeight="'100vh'"
      :cellHeightMode="'auto'"
      :fixedHeight="120"
      @refresh="handleRefresh"
      @loadMore="handleLoadMore"
      @orderClick="handleOrderClick"
      @orderCall="handleOrderCall"
      @orderComplete="handleOrderComplete"
    />
  </view>
</template>

<script setup>
import { ref, computed, onMounted } from "vue";
import TopNavBar from "./components/TopNavBar/index.vue";
import Tabs from "./components/Tabs/index.vue";
import OrderList from "./components/OrderList/index.vue";

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

// 当前状态
const currentTab = ref("all");
const currentTabIndex = ref(0);
const isLoading = ref(false);
const hasMore = ref(true);
const pageNum = ref(1);
const pageSize = ref(10);
const showConsultationBar = ref(false);

// 工单数据
const allOrderList = ref([]);
const serviceOrderList = ref([]);

// 模拟工单数据
const mockOrderData = [
  {
    id: "001",
    title: "空调不制冷，需要维修",
    createTime: "2024-01-15 14:30",
    contactName: "张先生",
    contactPhone: "138****8888",
    status: "pending",
    type: "service",
  },
  {
    id: "002",
    title: "卫生间水龙头漏水",
    createTime: "2024-01-15 10:20",
    contactName: "李女士",
    contactPhone: "139****9999",
    status: "processing",
    type: "service",
  },
  {
    id: "003",
    title: "客厅灯泡需要更换",
    createTime: "2024-01-14 16:45",
    contactName: "王先生",
    contactPhone: "137****7777",
    status: "completed",
    type: "service",
  },
  {
    id: "004",
    title: "普通订单 - 商品配送",
    createTime: "2024-01-14 09:15",
    contactName: "赵女士",
    contactPhone: "136****6666",
    status: "completed",
    type: "order",
  },
  {
    id: "005",
    title: "网络连接异常",
    createTime: "2024-01-15 11:30",
    contactName: "刘先生",
    contactPhone: "135****5555",
    status: "pending",
    type: "service",
  },
];

// 计算当前显示的工单列表
const currentOrderList = computed(() => {
  return currentTab.value === "all"
    ? allOrderList.value
    : serviceOrderList.value;
});

// 获取空状态文案
const getEmptyText = () => {
  return currentTab.value === "all" ? "暂无订单数据" : "暂无服务工单";
};

// Tab切换处理
const handleTabChange = ({ index, item }) => {
  console.log("切换到:", item.label);
  currentTab.value = item.value;
  currentTabIndex.value = index;

  // 如果当前Tab没有数据，则加载数据
  if (currentOrderList.value.length === 0) {
    loadOrderData(true);
  }
};

// 加载工单数据
const loadOrderData = async (isRefresh = false) => {
  if (isLoading.value) return;

  isLoading.value = true;

  try {
    // 模拟API请求延迟
    await new Promise((resolve) => setTimeout(resolve, 1000));

    // 模拟数据过滤
    let filteredData = [];
    if (currentTab.value === "all") {
      filteredData = mockOrderData;
    } else {
      filteredData = mockOrderData.filter((item) => item.type === "service");
    }

    if (isRefresh) {
      // 刷新数据
      if (currentTab.value === "all") {
        allOrderList.value = [...filteredData];
      } else {
        serviceOrderList.value = [...filteredData];
      }
      pageNum.value = 1;
      hasMore.value = true;
    } else {
      // 加载更多
      if (currentTab.value === "all") {
        allOrderList.value.push(...filteredData.slice(0, 2));
      } else {
        serviceOrderList.value.push(...filteredData.slice(0, 2));
      }
      pageNum.value++;

      // 模拟没有更多数据
      if (pageNum.value >= 3) {
        hasMore.value = false;
      }
    }
  } catch (error) {
    console.error("加载数据失败:", error);
    uni.showToast({
      title: "加载失败，请重试",
      icon: "none",
    });
  } finally {
    isLoading.value = false;
  }
};

// 下拉刷新
const handleRefresh = async () => {
  await loadOrderData(true);
};

// 上拉加载更多
const handleLoadMore = async () => {
  if (!hasMore.value) return;
  await loadOrderData(false);
};

// 工单点击处理
const handleOrderClick = (orderData) => {
  console.log("点击工单:", orderData);
  uni.navigateTo({
    url: `/pages/order/detail?id=${orderData.id}`,
  });
};

// 工单呼叫处理
const handleOrderCall = (orderData) => {
  console.log("呼叫:", orderData);

  // 显示底部咨询栏
  showConsultationBar.value = true;

  uni.makePhoneCall({
    phoneNumber: orderData.contactPhone.replace(/\*/g, ""),
    fail: () => {
      uni.showToast({
        title: "拨号失败",
        icon: "none",
      });
    },
  });
};

// 工单完成处理
const handleOrderComplete = (orderData) => {
  console.log("标记完成:", orderData);

  uni.showModal({
    title: "确认操作",
    content: "确定要标记此工单为已完成吗？",
    success: (res) => {
      if (res.confirm) {
        // 更新工单状态
        const targetList =
          currentTab.value === "all"
            ? allOrderList.value
            : serviceOrderList.value;
        const orderIndex = targetList.findIndex(
          (item) => item.id === orderData.id
        );
        if (orderIndex !== -1) {
          targetList[orderIndex].status = "completed";
        }

        uni.showToast({
          title: "操作成功",
          icon: "success",
        });
      }
    },
  });
};

// 页面加载时初始化数据
onMounted(() => {
  loadOrderData(true);
});
</script>

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