<script setup>
  import { ref, computed, onMounted, reactive } from 'vue'
  import { navigateTo } from '@/utils/router'
  import {
    getUserBuyRecordList,
    updateUserBuyRecord
  } from '../../../api/my-index'
  import { useUI } from '../../../utils/use-ui'

  const { showDialog, showToast } = useUI()
  // 响应式数据
  const paging = ref(null)
  const activeFilter = ref('') // -1表示全部
  const orders = ref([])
  const loading = ref(true)
  const formData = reactive({
    dataList: [],
    pageNum: 1,
    pageSize: 15
  })

  // 状态映射
  const statusMap = {
    0: { text: '待支付', color: 'status-wait-pay', bgColor: '#fff0f0' },
    1: { text: '已支付', color: 'status-paid', bgColor: '#f0f9ff' },
    2: { text: '已取消', color: 'status-cancelled', bgColor: '#f5f5f5' },
    3: { text: '已完成', color: 'status-completed', bgColor: '#f0fff0' },
    4: { text: '等待拼团', color: 'status-group', bgColor: '#fff5f0' },
    5: { text: '待发货', color: 'status-wait-ship', bgColor: '#f0f5ff' },
    6: { text: '已发货', color: 'status-shipped', bgColor: '#f0f5ff' },
    7: {
      text: '待收货',
      color: 'status-wait-receive',
      bgColor: '#f0f5ff'
    },
    8: { text: '已收货', color: 'status-received', bgColor: '#f0fff0' },
    9: { text: '已退款', color: 'status-refunded', bgColor: '#f5f5f5' }
  }

  // 初始化加载订单数据
  const getList = async () => {
    try {
      const res = await getUserBuyRecordList({
        // orderType: 1,
        orderStatus: activeFilter.value,
        pageNum: formData.pageNum,
        pageSize: formData.pageSize
      })
      formData.dataList = res.rows
      paging.value.complete(res.rows)
    } catch (error) {
      paging.value.complete(false)
    }
  }

  // 切换筛选状态
  const changeFilter = status => {
    formData.pageNum = 1
    activeFilter.value = status
    getList()
  }

  // 跳转到订单详情
  const goToDetail = item => {
    let url = ''
    if (item.orderType == 1) {
      url = '/pages/discover/order/detail'
    } else {
      url = '/pages/shop-together/detail'
    }
    navigateTo(url, { id: item.id })
  }

  // 获取状态文本
  const getStatusText = status => {
    return statusMap[status]?.text || '未知状态'
  }

  // 获取状态对应的CSS类
  const getStatusClass = status => {
    return statusMap[status]?.color || 'status-default'
  }

  /** 确认收货按钮回调 */
  const confirmReceipt = async item => {
    const show = await showDialog('提示', '确认已收到商品吗？')
    if (!show) return
    const data = {
      orderStatus: 8,
      id: item.id
    }
    await updateUserBuyRecord(data)
    item.orderStatus = 8
    showToast('收货成功', 'success')
  }
</script>

<template>
  <z-paging
    ref="paging"
    v-model="formData.dataList"
    :default-page-no="formData.pageNum"
    :default-page-size="formData.pageSize"
    safe-area-inset-bottom
    use-safe-area-placeholder
    :paging-style="{ 'background-color': '#f9f9f9' }"
    @query="getList"
  >
    <template #top>
      <!-- 页面标题 -->
      <view class="page-header">
        <text class="page-title">我的购买记录</text>
      </view>

      <!-- 订单状态筛选（可选功能） -->
      <scroll-view
        class="status-filter"
        scroll-x="true"
        :show-scrollbar="false"
      >
        <view
          class="filter-item"
          :class="{ active: activeFilter === '' }"
          @tap="changeFilter('')"
        >
          全部订单
        </view>
        <view
          class="filter-item"
          :class="{ active: activeFilter === 0 }"
          @tap="changeFilter(0)"
        >
          待支付
        </view>
        <view
          class="filter-item"
          :class="{ active: activeFilter === 5 }"
          @tap="changeFilter(5)"
        >
          待发货
        </view>
        <view
          class="filter-item"
          :class="{ active: activeFilter === 7 }"
          @tap="changeFilter(7)"
        >
          待收货
        </view>
        <view
          class="filter-item"
          :class="{ active: activeFilter === 3 }"
          @tap="changeFilter(3)"
        >
          已完成
        </view>
      </scroll-view>
    </template>
    <view class="order-list-page">
      <!-- 订单列表 -->
      <view class="order-list-container">
        <!-- 加载状态 -->
        <!-- <view v-if="loading" class="loading-container">
        <view class="loading-item" v-for="i in 3" :key="i">
          <view class="skeleton-image"></view>
          <view class="skeleton-text-container">
            <view class="skeleton-text-line short"></view>
            <view class="skeleton-text-line medium"></view>
            <view class="skeleton-text-line long"></view>
          </view>
        </view>
      </view> -->

        <!-- 订单列表 -->
        <view class="order-list">
          <view
            class="order-card"
            v-for="item in formData.dataList"
            :key="item.id"
            @tap="goToDetail(item)"
          >
            <!-- 订单头部：订单号 + 状态 -->
            <view class="order-header">
              <view class="order-info">
                <text class="order-number">
                  订单号: {{ item.orderNo }}
                </text>
                <text class="order-time">{{ item.updateTime }}</text>
              </view>
              <view class="order-status">
                <text
                  class="status-label"
                  :class="getStatusClass(item.orderStatus)"
                >
                  {{ getStatusText(item.orderStatus) }}
                </text>
              </view>
            </view>

            <!-- 商品信息 -->
            <view class="goods-item">
              <image
                :src="item.productImage"
                class="goods-image"
                mode="aspectFill"
              />
              <view class="goods-info">
                <text class="goods-name">{{ item.userName }}</text>
                <text class="goods-spec">
                  {{ item.specText }}
                </text>
                <view class="goods-price-info">
                  <text class="goods-price">¥{{ item.unitPrice }}</text>
                  <text class="goods-quantity">x1</text>
                </view>
              </view>
            </view>

            <!-- 订单统计信息 -->
            <view class="order-summary">
              <text class="total-quantity">共1件商品</text>
              <view class="price-section">
                <text class="total-label">合计:</text>
                <text class="total-price">¥{{ item.payAmount }}</text>
              </view>
            </view>

            <!-- 底部按钮 -->
            <view v-if="item.orderStatus == 7" class="bottom-btn">
              <button @click.stop="confirmReceipt(item)">确认收货</button>
            </view>

            <!-- 底部装饰线 -->
            <view class="card-footer">
              <view class="decorative-line"></view>
            </view>
          </view>
        </view>
      </view>
    </view>
  </z-paging>
</template>

<style lang="scss" scoped>
  @import './index.scss';
</style>
