<script setup la lang="ts">
import { getMyCouponListApi } from '@/api/coupon'
import shopCoupon from '@/components/shop-coupon/shop-coupon.vue'
import type { couponListItem } from '@/types/coupon'
import useZPaging from '@/uni_modules/z-paging/components/z-paging/js/hooks/useZPaging'
import { reactive, ref } from 'vue'
import { onPageScroll, onReachBottom } from '@dcloudio/uni-app'
import { pageUrl } from '@/utils/constants'
import { watch } from 'vue'

const query = withDefaults(
  defineProps<{
    status?: string
  }>(),
  {
    status: '',
  },
)

const state = reactive({
  status: query.status,
})

const tabList = [
  { name: '待使用', value: '1' },
  { name: '已使用', value: '2' },
  { name: '已过期', value: '3' },
  { name: '已失效', value: '4' },
]

const current = tabList.findIndex((item) => item.value == state.status)
const tabIndex = ref(current === -1 ? 0 : current)

const tabsChange = (index: number) => {
  tabIndex.value = index
  paging.value.refresh()
}

const couponList = ref<couponListItem[]>([])
const paging = ref()
useZPaging(paging)
const queryList = async (page: number, page_size: number) => {
  const res = await getMyCouponListApi({
    page,
    page_size,
    status: tabList[tabIndex.value].value,
  })
  paging.value.complete(res.result.data)
}

const handleButtonClicked = (item: couponListItem) => {
  uni.navigateTo({
    url: `${pageUrl['goods-list']}?coupon_id=${item.coupon_id}&empty_text=暂无商品可用`,
  })
}
</script>

<template>
  <z-paging ref="paging" v-model="couponList" @query="queryList" empty-view-text="您还没有优惠券噢">
    <template #top>
      <z-tabs :list="tabList" v-model="tabIndex" @change="tabsChange" :current="tabIndex" />
    </template>
    <shop-coupon
      v-if="couponList.length > 0"
      :couponList="couponList"
      mode="user"
      buttonTitle="去使用"
      @buttonClicked="handleButtonClicked"
    />
  </z-paging>
</template>

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