<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
            @click="previewImage(item.imageList)"
            style="width: 50px; height: 50px; border-radius: 6px"
            :src="item.imageList[0] || emptyImg"
            mode="scaleToFill"
          ></image>
          <view class="info">
            <view>{{ item.metalTypeDesc }}</view>
            <view class="right">
              <view>
                金价：
                <span class="weight">{{ item.goldPricePerGram }}/g</span>
              </view>
              <view>
                自估重量：
                <span class="weight">{{ item.estimatedWeight }}克</span>
              </view>
            </view>
          </view>
        </view>
        <view class="end">
          <view class="desc">
            <view class="">下单时间：{{ item.createTime }}</view>
            <uni-countdown
              v-if="item.status == 1"
              :minute="item.countdown || 0"
              color="#ff0000"
              @timeup="timeupHandle(item)"
            ></uni-countdown>
          </view>
        </view>
        <view v-if="item.status == 1" class="footer"
          >*请尽快邮寄，倒计时结束后未寄出系统将自动取消订单。</view
        >
      </view>
    </view>
    <!-- 下拉加载必须代码块 -->
    <!-- <tm-loadding v-if="loading" style="padding-bottom: 15px"></tm-loadding>
    <tm-loadding
      v-if="!loading && !hasMore"
      success
      icon="icon-times-circle-fill"
      label="没有更多啦"
      color="mymain"
      style="padding-bottom: 15px"
    ></tm-loadding> -->
  </view>
</template>

<script setup>
import { ref, computed, onMounted } from "vue";
import { recycleListAPI } from "@/api/functions";
import { useAppStore } from "@/stores/app";
import {
  onLoad,
  onPullDownRefresh,
  onShow,
  onReachBottom,
} from "@dcloudio/uni-app";
const appStore = useAppStore();
// 定义数据
const list = ref([
  { name: "全部", status: "" },
  { name: "待寄出", status: 1 },
  { name: "待检测", status: 3 },
  { name: "待确认", status: 4 },
  { name: "已完成", status: 7 },
]);

const orderList = ref([]);
const orderAll = ref([]);
const emptyImg = ref(
  "https://mp-ad17e5cd-05c1-4df9-b060-556e25dac130.cdn.bspapp.com/mini/recycle/example/example1.png"
);

// 计算属性
const pageTop = computed(() => {
  // return vk.getVuex("$app.totalBarHeight");
  return 0; // 占位，实际项目中替换为正确的顶部高度计算
});
const total = ref(0);
const hasMore = ref(true);
const loading = ref(false);
const params = ref({
  limit: 10,
  page: 1,
  status: "",
  userId: appStore.userInfo.userId,
});
// 初始化
const init = async (isRefresh = false) => {
  if (loading.value) return;
  loading.value = true;
  uni.showLoading({
    title: "加载中",
  });
  try {
    // 模拟接口调用
    const res = await recycleListAPI(params.value);
    console.log(res);

    const newList = res.data.list?.map((item) => {
      return {
        ...item,
        countdown: getTimeDiff(item.expirationTime),
        imageList: item.images ? JSON.parse(item.images) : [],
      };
    });
    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();
    }
  }
};

// 计算目标时间与当前时间的差值（返回分钟数）
const getTimeDiff = (targetTimeStr) => {
  const targetTime = new Date(targetTimeStr).getTime();
  const currentTime = Date.now();
  const diffMs = targetTime - currentTime;
  const diffMinutes = diffMs / 60000;
  return diffMinutes > 0 ? diffMinutes : 0;
};
// 时间到结束
const timeupHandle = (item) => {
  item.status = 0;
};

// 标签页切换
const tabsChange = (item) => {
  params.value.status = item.status;
  params.value.page = 1;
  init();
};

// 跳转到详情页
const nativeTo = (item) => {
  console.log(item);
  if (item.status == 1) {
    uni.navigateTo({
      url: `/pages/users/vault/recycle/order_fill?order=${JSON.stringify(
        item
      )}`,
      // url: "/pages/users/vault/recycle/report",
    });
  } else if (item.status == 4 || item.status == 7) {
    uni.navigateTo({
      url: `/pages/users/vault/recycle/report?orderInfo=${encodeURIComponent(
        JSON.stringify(item)
      )}`,
    });
  }
};

// 计算总重量
const totalWeight = (order) => {
  let totalWeight = 0;
  for (const key in order.cart) {
    if (Object.hasOwnProperty.call(order.cart, key)) {
      const item = order.cart[key];
      totalWeight += Number(item.weight) || 0;
    }
  }
  return totalWeight.toFixed(2);
};

// 获取商品类别
const getCate = (cate) => {
  switch (cate) {
    case "au":
      return "黄金";
    case "ag":
      return "白银";
    case "pt":
      return "铂金";
    case "kau":
      return "K金";
    default:
      return "其他";
  }
};

// 获取订单状态文本
const getOrderType = (status) => {
  switch (status) {
    case 0:
      return "已取消";
    case 1:
      return "待寄出";
    case 2:
      return "等待签收";
    case 3:
      return "等待检测";
    case 4:
      return "确认报告";
    case 5:
      return "确认总价";
    case 6:
      return "正在打款";
    case 7:
      return "交易完成";
    default:
      return "未知状态";
  }
};

// 生命周期钩子
onShow(() => {
  params.value.page = 1;
  init();
});

// 下拉刷新
onPullDownRefresh(() => {});

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

  // 增加页码
  params.value.page++;
  // 加载下一页数据
  init();
});
const previewImage = (urls) => {
  console.log(urls[0]);

  uni.previewImage({
    current: urls[0], // 当前显示图片的URL
    urls: urls, // 需要预览的图片URL列表
    success: () => {},
    fail: (err) => {
      console.error("预览图片失败:", err);
    },
  });
};
</script>

<style>
.empty {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  color: #ffffff;
}
page {
  height: 100%;
  background-color: #f8f8f8;
}
</style>

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

.tabs-box {
  width: 100%;
  height: 75rpx;
  // background: #ffffff;
  box-sizing: border-box;
  ::v-deep .u-tabs__wrapper__nav__item {
    padding: 0 37rpx;
  }
}
.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,
      &.status5 {
        color: rgb(48, 24, 136);
        background-color: #bbb0fa;
      }
      &.status6 {
        color: #3dac27;
        background-color: #c8ffb7;
      }
    }
    .title {
      font-size: 14px;
    }
  }

  .detail {
    display: flex;
    padding: 10px 13px;
    .info {
      flex: 1;
      width: 100%;
      font-size: 14px;
      margin-left: 10px;
      color: #999;

      .right {
        min-width: 120px;
        // display: flex;
        // justify-content: space-between;
        .weight {
          // width: 100%;
          color: #daa520;
        }
      }
    }
  }
  .end {
    padding: 10px 10px;
    color: #999;
    font-size: 14px;

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