<template>
  <view class="list-page">
    <view class="tabs-box">
      <up-tabs :list="list" @click="tabsChange" lineColor="#f8c20f"></up-tabs>
    </view>
    <view v-if="orderList.length === 0" class="empty">
      <image
        style="width: 60%"
        src="https://mp-ad17e5cd-05c1-4df9-b060-556e25dac130.cdn.bspapp.com/mini/common/empty.png"
        mode="widthFix"
      ></image>
      <text>暂无订单~</text>
    </view>
    <view v-else class="inner">
      <view
        v-for="(item, index) in orderList"
        :key="index"
        class="block"
        @click="nativeTo(item)"
      >
        <view class="header">
          <view class="title">订单号:{{ item.orderNo }}</view>
          <view class="tag" :class="['status' + item.status]">
            {{ getOrderType(item.status) }}
          </view>
        </view>
        <view class="detail">
          <image
            style="width: 50px; height: 50px; border-radius: 6px"
            :src="item.images[0] || emptyImg"
            mode="scaleToFill"
            v-if="item.images"
            @click="previewImage(item.images)"
          ></image>
        </view>

        <view class="end">
          <view>
            <view class="desc">
              订单自估重量：
              <span
                class="price"
                v-for="(i, index) in item.goldMaterials"
                :key="index"
                >{{ `${getCate(i.type)}${i.weight}g` }}</span
              >
            </view>
          </view>
          <view class="desc">
            <view class="">下单时间：{{ item.createTime }}</view>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref } from "vue";
import {
  onLoad,
  onShow,
  onPullDownRefresh,
  onReachBottom,
} from "@dcloudio/uni-app";
import { depositPageAPI } from "@/api/functions";
import { useAppStore } from "@/stores/app";
const appStore = useAppStore();
// 响应式变量（替代 Vue2 的 data）
const list = ref([
  { name: "全部", status: "" },
  { name: "待签收", status: 0 },
  { name: "待检测", status: 1 },
  { name: "待确认", status: 2 },
  { name: "已完成", status: 4 },
]);
const options = ref({ status: 0 });
const orderList = ref([]);
const emptyImg = ref(
  "https://mp-ad17e5cd-05c1-4df9-b060-556e25dac130.cdn.bspapp.com/mini/recycle/example/example1.png"
);

const params = ref({
  page: 1,
  limit: 20,
  status: "",
  // userId: appStorze.userInfo.userId,
});
const total = ref(0);
const loading = ref(false); // 加载状态
const hasMore = ref(true); // 是否还有更多数据

onShow((options) => {
  console.log(1111);
  params.value.page = 1;
  getOrderList();
});
const getOrderList = async (isRefresh = false) => {
  if (loading.value) return;
  loading.value = true;
  uni.showLoading({
    title: "加载中",
  });
  try {
    const res = await depositPageAPI(params.value);
    console.log(res);

    const newList = res.data.list.map((v) => {
      return {
        ...v,
        images: JSON.parse(v.expressImage),
      };
    });

    if (isRefresh) {
      orderList.value = newList;
    } else {
      // 避免重复添加
      if (params.value.page === 1) {
        orderList.value = newList;
      } else {
        orderList.value = [...orderList.value, ...newList];
      }
    }
    total.value = res.data.total;
    // 判断是否还有更多数据
    hasMore.value = orderList.value.length < total.value;
    uni.hideLoading();
  } catch (error) {
    console.error("获取订单列表失败:", error);
    uni.showToast({
      title: "加载失败",
      icon: "none",
    });
  } finally {
    loading.value = false;
    // 停止下拉刷新动画
    if (isRefresh) {
      uni.stopPullDownRefresh();
    }
  }
};
// 其他生命周期
onPullDownRefresh(() => {
  // 下拉刷新逻辑（保持原有空实现，可根据需求补充）
});

onReachBottom(() => {
  // 如果没有更多数据或正在加载中，则不执行
  if (!hasMore.value || loading.value) return;

  // 增加页码
  params.value.page++;
  // 加载下一页数据
  getOrderList();
});

onShow(() => {
  // 页面显示时逻辑（保持原有空实现，可根据需求补充）
});

// 标签页切换
const tabsChange = (item) => {
  params.value.status = item.status;
  params.value.page = 1;
  getOrderList();
};
// 跳转详情页（原 methods 中的 nativeTo）
const nativeTo = (item) => {
  if (item.status === 2 || item.status == 3 || item.status == 4) {
    uni.navigateTo({
      url: `/pages/users/vault/storeMetal/gmReport?orderInfo=${encodeURIComponent(
        JSON.stringify(item)
      )}`,
    });
  }
};

// 获取商品类别（原 methods 中的 getCate）
const getCate = (cate) => {
  switch (cate) {
    case 1:
      return "黄金";
    case 3:
      return "白银";
    case 2:
      return "铂金";
    case 4:
      return "K金";
    default:
      return ""; // 增加默认值，避免 undefined
  }
};

// 获取订单状态文本（原 methods 中的 getOrderType）
const getOrderType = (status) => {
  switch (status) {
    case 0:
      return "待签收";
    case 1:
      return "待检测";
    case 2:
      return "待确认";
    case 3:
      return "待充值";
    case 4:
      return "已完成";
    default:
      return "-"; // 增加默认值，避免 undefined
  }
};
const previewImage = (urls) => {
  uni.previewImage({
    current: urls[0],
    urls: urls, // 需要预览的图片URL列表
    success: () => {},
    fail: (err) => {
      console.error("预览图片失败:", err);
    },
  });
};
</script>

<style scoped lang="scss">
.list-page {
  // min-height: 100vh;
  background: $uni-bg-primary !important;
}

.tabs-box {
  width: 100%;
  height: 75rpx;
  // background: #ffffff;
  box-sizing: border-box;
  ::v-deep .u-tabs__wrapper__nav__item {
    padding: 0 37rpx;
  }
}

.empty {
  display: flex;
  flex-direction: column;
  align-items: center;
  color: #fff;
}
.tabs {
  z-index: 100;
  position: sticky;
}
.inner {
  padding: 10px;
  .footer {
    border-radius: 5px;
    border: 0 0 10px 20px;
    color: #707070;
    font-size: 12px;
    padding: 10px;
    background-color: rgb(252, 247, 230);
  }
}
.block {
  margin-bottom: 10px;
  padding-top: 10px;
  border-radius: 5px;
  background-color: #fff;
  border: 1px solid #cecece;
  .header {
    padding: 0 10px;
    position: relative;
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding-bottom: 10px;
    border-bottom: 1px solid #eee;
    .tag {
      font-size: 12px;
      padding: 2px 5px;
      border-radius: 4px;
      color: #ff0800;
      background-color: #ffcece;
      &.status-1 {
        color: #555;
        background-color: #eeeeee;
      }
      &.status1 {
        color: #ff9900;
        background-color: #ffeccf;
      }
      &.status2 {
        color: #d6006b;
        background-color: #fdd3e9;
      }
      &.status3 {
        color: #9900ff;
        background-color: #e2b7ff;
      }
      &.status4 {
        color: rgb(48, 24, 136);
        background-color: #bbb0fa;
      }
      &.status5 {
        color: #0051ff;
        background-color: #b7d6ff;
      }
      &.status6 {
        color: #3dac27;
        background-color: #c8ffb7;
      }
    }
    .title {
      font-size: 14px;
    }
  }
  .info {
    flex: 1;
    width: 100%;
    font-size: 14px;
    margin-left: 10px;
    color: #999;
    .cartList {
      margin-bottom: 3px;
      display: flex;
      justify-content: space-between;
      .right {
        min-width: 120px;
        display: flex;
        justify-content: space-between;
        .weight {
          color: #daa520;
        }
      }
    }
  }
  .detail {
    display: flex;
    padding: 10px 13px;
  }
  .end {
    padding: 10px 10px;
    color: #999;
    font-size: 14px;

    .desc {
      margin-bottom: 6px;
      display: flex;
      align-items: center;
      // justify-content: space-between;

      .price {
        margin-right: 10rpx;
      }
    }
  }
}
</style>
