<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
      :refresher-triggered="refresherTriggered"
      @refresherrefresh="onRefresh"
    >
      <!-- 订单项 -->
      <view class="order-item" v-for="order in orderList" :key="order.id">
        <!-- 订单头部 -->
        <view class="order-header">
          <text class="order-number">订单号：{{ order.orderNo }}</text>
          <text class="order-status" :class="[getStatusClass(order.status)]">{{
            getStatusText(order.status)
          }}</text>
        </view>

        <!-- 权益商品包名 -->
        <view class="package-name">
          <text>{{ order.packageName }}</text>
        </view>

        <!-- 商品列表 -->
        <view class="goods-list">
          <view
            class="goods-item"
            v-for="goods in order.goodsList"
            :key="goods.id"
          >
            <image class="goods-image" :src="goods.image" mode="aspectFill" />
            <view class="goods-info">
              <text class="goods-name">{{ goods.name }}</text>
              <text class="goods-type">{{ getGoodsTypeName(goods.type) }}</text>
              <text class="goods-price">¥{{ goods.price }}</text>
            </view>
            <view class="goods-action">
              <button
                class="action-btn"
                :class="[getActionBtnClass(goods.type)]"
                @click="handleGoodsAction(goods)"
              >
                {{ getActionBtnText(goods.type) }}
              </button>
            </view>
          </view>
        </view>

        <!-- 订单底部 -->
        <view class="order-footer">
          <view class="order-info">
            <text class="order-time">{{ formatTime(order.createTime) }}</text>
            <text class="order-total">总计：¥{{ order.totalAmount }}</text>
          </view>
          <view class="order-actions">
            <button
              class="equity-code-btn"
              @click="showEquityCode(order)"
              v-if="order.status !== 0"
            >
              权益码
            </button>
          </view>
        </view>
      </view>

      <!-- 空状态 -->
      <view class="empty-state" v-if="orderList.length === 0 && !loading">
        <image
          class="empty-image"
          src="/static/image/empty-order.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-label">权益码：</text>
            <text class="code-value" @longpress="copyCode">{{
              currentEquity.code
            }}</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() {
    this.loadOrderList();
  },
  methods: {
    // 切换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 = {
          page: this.currentPage,
          pageSize: this.pageSize,
          status: this.tabs[this.currentTab].status,
        };

        // 这里调用实际的API接口
        const res = await this.getOrderList(params);

        if (this.currentPage === 1) {
          this.orderList = res.data.list || [];
        } else {
          this.orderList = [...this.orderList, ...(res.data.list || [])];
        }

        this.hasMore = res.data.list.length === this.pageSize;
        this.currentPage++;
      } 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: "售后/退款",
      };
      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] || "操作";
    },

    // 获取操作按钮样式类
    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",
      });
    },

    // 预约发货
    reserveDelivery(goods) {
      // 处理预约发货逻辑
      uni.showToast({
        title: "预约发货",
        icon: "none",
      });
    },

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

    // 显示权益码
    showEquityCode(order) {
      this.currentEquity = {
        qrcode: order.qrcode || "/static/image/default-qrcode.png",
        code: order.equityCode || "EQUITY123456789",
      };
      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")}`;
    },

    // API接口 - 获取订单列表
    async getOrderList(params) {
      // 模拟API数据
      return new Promise((resolve) => {
        setTimeout(() => {
          const mockData = {
            code: 200,
            data: {
              list: [
                {
                  id: 1,
                  orderNo: "EQ202401011234567",
                  packageName: "Epic Soul限定权益包",
                  status: 1,
                  totalAmount: "299.00",
                  createTime: "2024-01-01 12:00:00",
                  qrcode: "/static/image/qrcode-sample.png",
                  equityCode: "EPIC2024010112345",
                  goodsList: [
                    {
                      id: 1,
                      name: "数字藏品-桃子系列",
                      type: 1,
                      price: "99.00",
                      image: "/static/image/goods1.jpg",
                    },
                    {
                      id: 2,
                      name: "文创周边产品",
                      type: 2,
                      price: "150.00",
                      image: "/static/image/goods2.jpg",
                    },
                    {
                      id: 3,
                      name: "君道苏州体验门票",
                      type: 3,
                      price: "50.00",
                      image: "/static/image/goods3.jpg",
                    },
                  ],
                },
                // 可以添加更多模拟数据
              ],
            },
          };
          resolve(mockData);
        }, 1000);
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.order-list-container {
  min-height: 100vh;
  background-color: #f5f5f5;
}

// Tab样式
.tab-container {
  display: flex;
  background-color: #fff;
  border-bottom: 1px solid #eee;
  position: sticky;
  top: 0;
  z-index: 10;
}

.tab-item {
  flex: 1;
  padding: 30rpx 0;
  text-align: center;
  position: relative;

  &.active {
    .tab-text {
      color: #007aff;
      font-weight: bold;
    }

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

.tab-text {
  font-size: 28rpx;
  color: #333;
}

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

.order-item {
  background-color: #fff;
  border-radius: 16rpx;
  margin-bottom: 20rpx;
  overflow: hidden;
}

// 订单头部
.order-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx;
  border-bottom: 1px solid #f0f0f0;
}

.order-number {
  font-size: 28rpx;
  color: #333;
}

.order-status {
  font-size: 26rpx;
  padding: 8rpx 16rpx;
  border-radius: 20rpx;

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

  &.status-waiting {
    background-color: #d4edda;
    color: #155724;
  }

  &.status-shipping {
    background-color: #cce5ff;
    color: #004085;
  }

  &.status-completed {
    background-color: #e2e3e5;
    color: #383d41;
  }

  &.status-refund {
    background-color: #f8d7da;
    color: #721c24;
  }
}

// 权益商品包名
.package-name {
  padding: 20rpx 30rpx;
  background-color: #f8f9fa;
  border-bottom: 1px solid #f0f0f0;

  text {
    font-size: 26rpx;
    color: #666;
  }
}

// 商品列表
.goods-list {
  padding: 0 30rpx;
}

.goods-item {
  display: flex;
  align-items: center;
  padding: 30rpx 0;
  border-bottom: 1px solid #f0f0f0;

  &:last-child {
    border-bottom: none;
  }
}

.goods-image {
  width: 120rpx;
  height: 120rpx;
  border-radius: 12rpx;
  margin-right: 20rpx;
}

.goods-info {
  flex: 1;
  margin-right: 20rpx;
}

.goods-name {
  display: block;
  font-size: 28rpx;
  color: #333;
  margin-bottom: 10rpx;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.goods-type {
  display: block;
  font-size: 24rpx;
  color: #999;
  margin-bottom: 10rpx;
}

.goods-price {
  font-size: 28rpx;
  color: #ff4757;
  font-weight: bold;
}

.goods-action {
  .action-btn {
    padding: 12rpx 24rpx;
    border-radius: 20rpx;
    font-size: 24rpx;
    border: none;

    &.btn-view {
      background-color: #007aff;
      color: #fff;
    }

    &.btn-reserve {
      background-color: #ff9500;
      color: #fff;
    }

    &.btn-use {
      background-color: #34c759;
      color: #fff;
    }
  }
}

// 订单底部
.order-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx;
  background-color: #f8f9fa;
}

.order-info {
  flex: 1;
}

.order-time {
  display: block;
  font-size: 24rpx;
  color: #999;
  margin-bottom: 10rpx;
}

.order-total {
  font-size: 28rpx;
  color: #333;
  font-weight: bold;
}

.order-actions {
  .equity-code-btn {
    padding: 16rpx 32rpx;
    background-color: #007aff;
    color: #fff;
    border-radius: 24rpx;
    font-size: 26rpx;
    border: none;
  }
}

// 空状态
.empty-state {
  text-align: center;
  padding: 200rpx 0;
}

.empty-image {
  width: 200rpx;
  height: 200rpx;
  margin-bottom: 30rpx;
}

.empty-text {
  font-size: 28rpx;
  color: #999;
}

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

.load-text,
.no-more-text {
  font-size: 26rpx;
  color: #999;
}

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

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

.popup-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.popup-close {
  font-size: 40rpx;
  color: #999;
}

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

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

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

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

.code-label {
  font-size: 28rpx;
  color: #666;
  margin-right: 10rpx;
}

.code-value {
  font-size: 28rpx;
  color: #333;
  font-weight: bold;
  background-color: #f8f9fa;
  padding: 8rpx 16rpx;
  border-radius: 8rpx;
}

.code-tip {
  font-size: 24rpx;
  color: #999;
}
</style>
