<script setup lang="ts">
import CouponItem from '../components/coupon/index.vue'

definePage({ name: 'xsb-coupon', islogin: true, style: { navigationBarTitleText: '优惠券列表' } })

const tabList = [
  { label: '待使用', useStatus: 2 },
  { label: '已使用', useStatus: 1 },
  { label: '已过期', useStatus: 5 },
  { label: '冻结', useStatus: 7 },
]

const activeTab = ref(0)
const activeCoupon = ref(null)
const routeType = ref('')

const { data: couponList, isLastPage, page, reload } = usePagination(
  (pageNum, pageSize) => Apis.xsb.memberCouponPage({
    data: {
      pageNum,
      pageSize,
      useStatus: tabList[activeTab.value].useStatus,
    },
  }),
  {
    immediate: true,
    pageNum: 1,
    pageSize: 10,
    initialData: [],
    data: res => res.data?.list ?? [],
    append: true,
  },
)
onLoad((options: any) => {
  console.log(options)
  if (options.type) {
    routeType.value = options.type
  }
  if (options.couponId) {
    activeCoupon.value = options.couponId
    switchTab(Number(options.activeTab))
  }
})

function switchTab(index: number) {
  if (activeTab.value === index)
    return
  activeTab.value = index
  couponList.value = []
  reload()
}

onReachBottom(() => {
  if (!isLastPage.value) {
    page.value++
  }
})
</script>

<template>
  <view class="min-h-screen bg-white">
    <!-- Tab 导航 -->
    <view class="sticky top-0 z-10 bg-white">
      <wd-tabs v-model="activeTab" @change="switchTab($event.index)">
        <wd-tab v-for="tab in tabList" :key="tab.useStatus" :title="tab.label" />
      </wd-tabs>
    </view>

    <!-- 列表 -->
    <view class="p-24rpx">
      <view v-for="item in couponList" :key="item.id" class="mb-20rpx">
        <view :class="[item.allowanceId == activeCoupon ? 'border-2rpx border-red-4 rounded-16rpx border-solid' : '']">
          <CouponItem
            :itemcoupon="item"
            :show-use-btn="item.useStatus === 2"
            :route-type="routeType"
          />
        </view>
      </view>

      <!-- 空状态 -->
      <StatusTip v-if="couponList.length === 0" tip="暂无内容" />
      <!-- 底部占位 -->
      <view class="h-40rpx" />
    </view>
  </view>
</template>

<style lang="scss" scoped></style>
