<template>
  <view class="order-list-container">
    <!-- Tab切换 -->
    <view class="tab-container">
      <view
        class="tab-item"
        :class="{ active: currentTab == index }"
        v-for="(tab, index) in tabs"
        :key="index"
        @click="switchTab(index)"
      >
        <text class="tab-text">{{ tab.name }}</text>
      </view>
    </view>

    <!-- 订单列表 -->
    <scroll-view
      class="order-scroll"
      scroll-y
      @scrolltolower="loadMore"
      refresher-enabled
      :show-scrollbar="false"
      :refresher-triggered="refresherTriggered"
      @refresherrefresh="onRefresh"
      enhanced
    >
      <!-- 订单项 -->
      <view
        class="order-item"
        v-for="order in orderList"
        :key="order.id"
        @click="goToOrderDetail(order)"
      >
        <!-- 订单头部 -->

        <!-- 权益商品包名 -->
        <view class="package-section">
          <text class="package-name">{{ order.orderName }}</text>
          <text class="status-name">{{ getStatusText(order.status) }}</text>
        </view>

        <!-- 商品列表 -->
        <view class="goods-section">
          <view class="goods-list">
            <view
              class="goods-item"
              v-for="goods in order.orderChildVos"
              :key="goods.id"
            >
              <image
                v-if="goods.goodsImg"
                class="goods-image"
                :src="showImgJdsz(goods.goodsImg&&goods.goodsImg.split(',')[0])"
                mode="aspectFill"
              />
              <view class="goods-info">
                <text class="goods-name">{{ goods.goodsTitle }}</text>
                <view class="goods-meta">
                  <text class="goods-type">{{
                    getGoodsTypeName(goods.type)
                  }}</text>
                  <text class="goods-quantity">数量：{{ goods.num || 1 }}</text>
                </view>
              </view>
              <view class="goods-action">
                <!-- 未使用 -->
                <button
                  v-if="goods.status == 1"
                  class="action-btn"
                  :class="[getActionBtnClass(goods.status)]"
                  @click.stop="handleGoodsAction(goods)"
                >
                  {{ getActionBtnText(goods.type) }}
                </button>
                <button
                  v-else
                  class="action-btn"
                  :class="[getActionBtnClass(goods.status)]"
                  @click.stop="handleGoodsAction(goods)"
                >
                  {{ getActionBtnTexted(goods.type) }}
                </button>
              </view>
            </view>
          </view>
        </view>

        <!-- 订单底部 -->
        <view class="order-footer">
          <view class="order-info">
            <view class="order-total-section">
              <text class="total-label">实付金额</text>
              <text class="order-total">¥{{ order.payMoney || 0 }}</text>
            </view>
          </view>
          <view class="order-actions">
            <button
              class="equity-code-btn"
              @click.stop="showEquityCode(order)"
              v-if="order.status !== 0"
            >
              <text>权益码</text>
            </button>
          </view>
        </view>
      </view>
      <!-- 空状态 -->
      <view
        class="empty-state"
        v-if="(goodsList && goodsList.length == 0) || loading"
      >
        <image
          class="empty-image"
          :src="
            showImg('/uploads/20250808/c16267f9cc2b7a68bf23713b5847987e.png')
          "
          mode="aspectFit"
        />
        <text class="empty-text">暂无订单</text>
      </view>

      <!-- 加载更多 -->
      <view class="load-more" v-if="hasMore && orderList.length > 0">
        <text class="load-text">{{
          loading ? "加载中..." : "上拉加载更多"
        }}</text>
      </view>

      <!-- 没有更多数据 -->
      <view class="no-more" v-if="!hasMore && orderList.length > 0">
        <text class="no-more-text">没有更多数据了</text>
      </view>
    </scroll-view>

    <!-- 权益码弹窗 -->
    <uni-popup ref="equityPopup" type="center">
      <view class="equity-popup">
        <view class="popup-header">
          <text class="popup-title">权益码</text>
          <text class="popup-close" @click="closeEquityPopup">×</text>
        </view>
        <view class="popup-content">
          <!-- 二维码 -->
          <!-- <view class="qrcode-container">
						<image class="qrcode-image" :src="currentEquity.qrcode" mode="aspectFit" />
					</view> -->
          <!-- 编号串码 -->
          <view class="code-container">
            <text class="code-value" @longpress="copyCode">{{
              currentEquity.activeCode
            }}</text>
          </view>
          <text class="code-tip">长按编号可复制</text>
        </view>
      </view>
    </uni-popup>
  </view>
</template>

<script>
export default {
  data() {
    return {
      currentTab: 0,
      tabs: [
        {
          name: "全部",
          status: "",
        },
        {
          name: "待使用",
          status: 1,
        },
        {
          name: "待收货",
          status: 2,
        },
        {
          name: "已完成",
          status: 3,
        },
        {
          name: "售后/退款",
          status: 4,
        },
      ],
      orderList: [],
      loading: false,
      refresherTriggered: false,
      hasMore: true,
      currentPage: 1,
      pageSize: 10,
      currentEquity: {
        qrcode: "",
        code: "",
      },
    };
  },
  onLoad(e) {
    if (e.status) {
      this.currentTab = e.status;
    }
    this.loadOrderList();
  },
  methods: {
    showImgJdsz(img) {
      if (!img) return;
      if (img.indexOf("https://") != -1 || img.indexOf("http://") != -1) {
        return img;
      } else {
        return this.JDSU_IMG_URL + img;
      }
    },
    // 切换Tab
    switchTab(index) {
      this.currentTab = index;
      this.resetList();
      this.loadOrderList();
    },

    // 重置列表
    resetList() {
      this.orderList = [];
      this.currentPage = 1;
      this.hasMore = true;
    },

    // 加载订单列表
    async loadOrderList() {
      if (this.loading || !this.hasMore) return;

      this.loading = true;
      try {
        const params = {
          pageNum: this.currentPage,
          pageSize: this.pageSize,
          status: this.tabs[this.currentTab].status,
        };
        this.Post(
          {
            ...params,
          },
          "/framework/order/list",
          "DES"
        ).then((res) => {
          if (res.code == 200) {
            this.orderList.push(...res.rows);
            this.hasMore = res.rows.length === this.pageSize;
            this.currentPage++;
          } else {
            uni.showToast({
              title: res.msg,
              icon: "none",
            });
          }
        });
      } catch (error) {
        console.error("加载订单列表失败:", error);
        uni.showToast({
          title: "加载失败",
          icon: "none",
        });
      } finally {
        this.loading = false;
        this.refresherTriggered = false;
      }
    },

    // 上拉加载更多
    loadMore() {
      this.loadOrderList();
    },

    // 下拉刷新
    onRefresh() {
      this.refresherTriggered = true;
      this.resetList();
      this.loadOrderList();
    },

    // 获取订单状态文本
    getStatusText(status) {
      const statusMap = {
        0: "待激活",
        1: "待使用",
        2: "待收货",
        3: "已完成",
        4: "售后/退款",
        "-1": "取消",
      };
      return statusMap[status] || "未知";
    },

    // 获取订单状态样式类
    getStatusClass(status) {
      const classMap = {
        0: "status-pending",
        1: "status-waiting",
        2: "status-shipping",
        3: "status-completed",
        4: "status-refund",
      };
      return classMap[status] || "";
    },

    // 获取商品类型名称
    getGoodsTypeName(type) {
      const typeMap = {
        1: "IP数字资产",
        2: "IP资源商品",
        3: "门票",
      };
      return typeMap[type] || "未知类型";
    },

    // 获取操作按钮文本
    getActionBtnText(type) {
      const textMap = {
        1: "查看",
        2: "预约发货",
        3: "去使用",
      };
      return textMap[type] || "操作";
    },
    getActionBtnTexted(type) {
      const textMap = {
        1: "查看",
        2: "已使用",
        3: "已使用",
      };
      return textMap[type] || "操作";
    },

    // 获取操作按钮样式类
    getActionBtnClass(type) {
      const classMap = {
        1: "btn-view",
        2: "btn-reserve",
        3: "btn-use",
      };
      return classMap[type] || "";
    },

    // 处理商品操作
    handleGoodsAction(goods) {
      switch (goods.type) {
        case 1: // IP数字资产 - 查看
          this.viewDigitalAsset(goods);
          break;
        case 2: // IP资源商品 - 预约发货
          this.reserveDelivery(goods);
          break;
        case 3: // 君道苏州门票 - 去使用
          this.useTicket(goods);
          break;
      }
    },

    // 查看数字资产
    viewDigitalAsset(goods) {
      // 跳转到数字资产详情页面
      uni.showToast({
        title: "查看数字资产",
        icon: "none",
      });
      uni.navigateTo({
        url: "/subPackages/memorialAlbum/detail",
      });
    },

    // 预约发货
    reserveDelivery(goods) {
      // 跳转到确认订单页面
      uni.navigateTo({
        url: `/subPackages/orderQy/confrim?goodsId=${goods.orderId}`,
      });
    },

    // 使用门票
    useTicket(goods) {
      // 处理使用门票逻辑
      uni.showToast({
        title: "使用门票",
        icon: "none",
      });
    },

    // 跳转到订单详情页面
    goToOrderDetail(order) {
      uni.navigateTo({
        url: `/subPackages/orderQy/detail?id=${order.orderId}`,
      });
    },

    // 显示权益码
    showEquityCode(order) {
      this.currentEquity = {
        qrcode: order.qrcode || "/static/image/default-qrcode.png",
        activeCode: order.activeCode,
      };
      this.$refs.equityPopup.open();
    },

    // 关闭权益码弹窗
    closeEquityPopup() {
      this.$refs.equityPopup.close();
    },

    // 复制权益码
    copyCode() {
      uni.setClipboardData({
        data: this.currentEquity.code,
        success: () => {
          uni.showToast({
            title: "已复制到剪贴板",
            icon: "success",
          });
        },
      });
    },

    // 格式化时间
    formatTime(time) {
      if (!time) return "";
      const date = new Date(time);
      return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(
        2,
        "0"
      )}-${String(date.getDate()).padStart(2, "0")} ${String(
        date.getHours()
      ).padStart(2, "0")}:${String(date.getMinutes()).padStart(2, "0")}`;
    },
  },
};
</script>

<style lang="scss" scoped>
// 主题色彩变量
$primary-color: #667eea;
$secondary-color: #f8f9fa;
$text-primary: #2d3748;
$text-secondary: #718096;
$text-muted: #a0aec0;
$border-color: #e2e8f0;
$success-color: #48bb78;
$warning-color: #ed8936;
$danger-color: #f56565;
$bg-light: #f7fafc;

.order-list-container {
  min-height: 100vh;
  background-color: $bg-light;
}

// Tab样式
.tab-container {
  display: flex;
  background-color: #ffffff;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
  color: black;
  position: sticky;
  top: 0;
  z-index: 10;
}

.tab-item {
  flex: 1;
  padding: 32rpx 0;
  text-align: center;
  position: relative;
  transition: all 0.3s ease;
  color: #333333;

  &.active {
    .tab-text {
      color: #77f3f9;
      font-weight: 600;
    }

    &::after {
      content: "";
      position: absolute;
      bottom: 0;
      left: 50%;
      transform: translateX(-50%);
      width: 60rpx;
      height: 4rpx;
      background-color: #77f3f9;
      border-radius: 2rpx;
    }
  }

  &:not(.active) {
    .tab-text {
      opacity: 1;
    }
  }
}

.tab-text {
  font-size: 26rpx;
  color: #333333;
  font-weight: 600;
  transition: all 0.3s ease;
}

// 订单列表样式
.order-scroll {
  height: calc(100vh - 120rpx);
  padding: 0 24rpx;
  width: 702rpx;
}

.order-item {
  background-color: #ffffff;
  border-radius: 20rpx;
  overflow: hidden;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.08);
  border: none;
  transition: all 0.3s ease;
  margin-top: 40rpx;

  &:active {
    transform: scale(0.98);
  }
}

// 订单头部
.order-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 24rpx 28rpx 20rpx;
  background: $secondary-color;
}

.order-left {
  flex: 1;
}

.order-number-section {
  display: flex;
  flex-direction: column;
  gap: 6rpx;
}

.order-label {
  font-size: 24rpx;
  color: $text-muted;
  font-weight: 500;
}

.order-number {
  font-size: 28rpx;
  color: $text-primary;
  font-weight: 600;
  font-family: -apple-system, BlinkMacSystemFont, "PingFang SC",
    "Helvetica Neue", STHeiti, "Microsoft Yahei", Tahoma, Simsun, sans-serif;
}

.order-status-wrapper {
  display: flex;
  align-items: center;
}

.order-status {
  font-size: 26rpx;
  padding: 12rpx 20rpx;
  border-radius: 24rpx;
  font-weight: 600;
  letter-spacing: 0.5rpx;

  &.status-pending {
    background: #fff3cd;
    color: #856404;
  }

  &.status-waiting {
    background: $success-color;
    color: #ffffff;
  }

  &.status-shipping {
    background: $primary-color;
    color: #ffffff;
  }

  &.status-completed {
    background: $text-secondary;
    color: #ffffff;
  }

  &.status-refund {
    background: $danger-color;
    color: #ffffff;
  }
}

// 权益商品包
.package-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 20rpx;
}

.package-name {
  flex: 1;
  font-size: 30rpx;
  color: $text-primary;
  font-weight: 600;
  letter-spacing: 0.5rpx;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  margin-right: 20rpx;
}

.status-name {
  font-size: 26rpx;
  color: $text-secondary;
  font-weight: 500;
  flex-shrink: 0;
}

// 商品部分
.goods-section {
  margin: 20rpx 0;
}

.goods-title {
  font-size: 28rpx;
  color: $text-primary;
  font-weight: 600;
  padding: 0 28rpx 16rpx;
  border-bottom: 2rpx solid $border-color;
  margin-bottom: 20rpx;
}

.goods-list {
  padding: 0 20rpx;
}

.goods-item {
  display: flex;
  align-items: center;
  padding: 20rpx;
  margin-bottom: 12rpx;
  background: #ffffff;
  border-radius: 16rpx;
  border: 1px solid rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.04);

  &:last-child {
    margin-bottom: 0;
  }

  &:active {
    transform: scale(0.98);
    background: #f8f9fa;
  }
}

.goods-image {
  width: 100rpx;
  height: 100rpx;
  border-radius: 12rpx;
  margin-right: 20rpx;
  flex-shrink: 0;
}

.goods-info {
  margin-right: 20rpx;
  width: 330rpx;
}

.goods-name {
  display: block;
  font-size: 26rpx;
  color: $text-primary;
  font-weight: 600;
  margin-bottom: 12rpx;
  line-height: 1.4;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.goods-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.goods-type {
  font-size: 24rpx;
  color: $text-secondary;
  // background: $secondary-color;
  // padding: 8rpx 16rpx;
  border-radius: 20rpx;
  font-weight: 500;
  margin-right: 16rpx;
}

.goods-quantity {
  font-size: 22rpx;
  color: $text-muted;
  font-weight: 500;
}

.goods-price {
  font-size: 26rpx;
  color: $danger-color;
  font-weight: 600;
  font-family: "SF Mono", "Monaco", "Cascadia Code", monospace;
}

.goods-action {
  margin-left: auto;

  .action-btn {
    padding: 0rpx 20rpx;
    border-radius: 10rpx;
    font-size: 24rpx;
    font-weight: 600;
    border: none;
    color: #333333;
    transition: all 0.3s ease;
    min-width: 100rpx;
    text-align: center;
    background-color: #77f3f9;
    height: 55rpx;
    line-height: 55rpx;

    &:active {
      transform: scale(0.95);
    }

    // &.btn-view {
    //   background: $primary-color;
    // }

    // &.btn-reserve {
    //   background: $warning-color;
    // }

    // &.btn-use {
    //   background: $success-color;
    // }
  }
}

// 订单底部
.order-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 24rpx 28rpx;
  background: white;
  margin-top: 20rpx;
}

.order-info {
  flex: 1;
  display: flex;
  gap: 32rpx;
}

.order-time-section,
.order-total-section {
}

.time-label,
.total-label {
  margin-right: 10rpx;
  font-size: 22rpx;
  color: $text-muted;
  font-weight: 500;
}

.order-time {
  font-size: 26rpx;
  color: $text-primary;
  font-weight: 500;
  font-family: -apple-system, BlinkMacSystemFont, "PingFang SC",
    "Helvetica Neue", STHeiti, "Microsoft Yahei", Tahoma, Simsun, sans-serif;
}

.order-total {
  font-size: 32rpx;
  color: $danger-color;
  font-weight: 600;
  font-family: -apple-system, BlinkMacSystemFont, "PingFang SC",
    "Helvetica Neue", STHeiti, "Microsoft Yahei", Tahoma, Simsun, sans-serif;
}

.order-actions {
  .equity-code-btn {
    display: flex;
    align-items: center;
    gap: 10rpx;
    padding: 2rpx 24rpx;
    background: white;
    color: #333333;
    border-radius: 10rpx;
    font-size: 24rpx;
    font-weight: 600;
    border: 1rpx solid #77f3f9;
    transition: all 0.3s ease;
    height: 55rpx;
    line-height: 55rpx;

    &:active {
      transform: scale(0.95);
    }

    .btn-icon {
      font-size: 20rpx;
    }
  }
}

// 空状态
.empty-state {
  text-align: center;
  padding: 240rpx 40rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
}

.empty-image {
  width: 240rpx;
  height: 240rpx;
  margin-bottom: 40rpx;
  opacity: 0.8;
}

.empty-text {
  font-size: 32rpx;
  color: $text-muted;
  font-weight: 500;
}

// 加载更多
.load-more,
.no-more {
  text-align: center;
  padding: 40rpx;
}

.load-text,
.no-more-text {
  font-size: 28rpx;
  color: $text-muted;
  font-weight: 500;
}

// 权益码弹窗
.equity-popup {
  width: 600rpx;
  background-color: #ffffff;
  border-radius: 16rpx;
  overflow: hidden;
}

.popup-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx;
  border-bottom: 1px solid $border-color;
}

.popup-title {
  font-size: 32rpx;
  font-weight: 600;
  color: $text-primary;
}

.popup-close {
  font-size: 40rpx;
  color: $text-muted;
}

.popup-content {
  padding: 40rpx 30rpx;
  text-align: center;
}

.qrcode-container {
  margin-bottom: 40rpx;
}

.qrcode-image {
  width: 300rpx;
  height: 300rpx;
  border: 1px solid $border-color;
  border-radius: 12rpx;
}

.code-container {
  margin-bottom: 20rpx;
}

.code-label {
  font-size: 28rpx;
  color: $text-secondary;
  margin-right: 10rpx;
}

.code-value {
  font-size: 28rpx;
  color: $text-primary;
  font-weight: 600;
  background-color: $secondary-color;
  padding: 8rpx 16rpx;
  border-radius: 8rpx;
}

.code-tip {
  font-size: 24rpx;
  color: $text-muted;
}
</style>
