<script setup lang="ts">
import router from '@/router'

import { StaticUrl } from '@/config'
// Tab 列表
const tabList = ref([
  { label: '可用', value: 2 },
  { label: '已使用', value: 1 },
  { label: '已过期', value: 5 },
])
const currentTab = ref(2)

// 状态映射
const statusMap = new Map([
  [2, '可用'],
  [1, '已使用'],
  [5, '已过期'],
])

// 分页请求
const { data, isLastPage, page, reload } = usePagination(
  (pageNum, pageSize) => Apis.app.get_smqjh_system_app_api_membercoupon_page({
    params: { pageNum, pageSize, useStatus: currentTab.value },
  }),
  {
    initialPage: 1,
    initialPageSize: 10,
    immediate: false,
    data: res => res.data?.list,
    append: true,
  },
)

// 切换 Tab
function handleTabChange(value: number) {
  currentTab.value = value
  page.value = 1
  reload()
}

function handleUse(_item: Api.AppMemberCouponVO) {
  router.pushTab({ name: 'home' })
  useTabbar().setTabbarItemActive('home')
}

// 取消订单（占位）
async function handleCancelOrder(_item: Api.AppMemberCouponVO) {
  // useGlobalToast().show('功能开发中')
  await useUserStore().handleCommonCancelOrderJY(_item.lockOrderId as string)
  reload()
}

// 付款（占位）
function handlePay(_item: Api.AppMemberCouponVO) {
  // useGlobalToast().show('功能开发中')
  useUserStore().handleCommonGoXiaoJuPay(_item.lockOrderId as string)
}

// 计算倒计时剩余毫秒数
function getCountdownTime(orderCreateTime?: string): number {
  if (!orderCreateTime)
    return 0
  const createTime = new Date(orderCreateTime).getTime()
  const expireTime = createTime + 15 * 60 * 1000 // 假设15分钟支付有效期
  const remaining = expireTime - Date.now()
  return remaining > 0 ? remaining : 0
}

onShow(() => {
  page.value = 1
  reload()
})

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

<template>
  <view class="min-h-100vh bg-#f5f5f5">
    <!-- Tab 切换 -->
    <view class="sticky top-0 z-10 flex items-center justify-between bg-white px24rpx">
      <view
        v-for="item in tabList"
        :key="item.value"
        class="py24rpx text-28rpx"
        :class="[currentTab === item.value ? 'text-[var(--them-color)] font-semibold border-b-4rpx border-[var(--them-color)]' : 'text-#666']"
        @click="handleTabChange(item.value)"
      >
        {{ item.label }}
      </view>
    </view>

    <!-- 券列表 -->
    <view class="px24rpx pt20rpx">
      <view
        v-for="item in data"
        :key="item.id"
        class="mb20rpx rounded-16rpx bg-white px24rpx py28rpx"
      >
        <view @click="router.push({ name: 'voucherDetail', params: { id: item.id as string } })">
          <!-- 券信息头部 -->
          <view class="flex items-center justify-between">
            <view class="flex items-center">
              <image
                :src="`${StaticUrl}/smqjh-reful-juan.png`"
                class="mr12rpx h32rpx w32rpx"
              />
              <view class="text-30rpx font-semibold">
                抵扣{{ item.discountMoney }}元(满{{ item.amountMoney }}元可用)
              </view>
            </view>
            <!-- 待支付倒计时 -->
            <view v-if="item.lockStatus === 1 && currentTab === 2" class="flex items-center text-24rpx text-#1890ff">
              待支付(<wd-count-down :time="getCountdownTime(item.orderCreateTime)" format="还剩mm:ss" />)
            </view>
          </view>

          <!-- 券详情 -->
          <view class="mt16rpx text-26rpx text-#999">
            适用：全部合作油站
          </view>
          <view class="mt12rpx text-26rpx text-#999">
            有效期至：{{ item.expirationTime }}
          </view>
          <view class="mt12rpx text-26rpx text-#999">
            可抵扣：<text class="text-#ff4d3a">
              ￥{{ item.discountMoney }}
            </text>
          </view>
          <view class="mt12rpx text-26rpx text-#999">
            状态：{{ statusMap.get(item.useStatus as number) || '' }}
          </view>
        </view>

        <!-- 操作按钮区域 -->
        <view v-if="currentTab === 2" class="mt20rpx">
          <!-- 未被锁定 - 显示去使用 -->
          <view v-if="item.lockStatus !== 1" class="flex justify-end">
            <wd-button size="small" plain custom-class="use-btn" @click="handleUse(item)">
              去使用
            </wd-button>
          </view>

          <!-- 被锁定 - 显示订单信息和操作 -->
          <view v-else>
            <view class="flex items-center text-26rpx text-#1890ff">
              <wd-icon name="info-circle" size="28rpx" color="#1890ff" class="mr8rpx" />
              当前订单未支付，券被占用
            </view>
            <view class="mt16rpx flex items-center justify-between">
              <view class="text-26rpx text-#999">
                订单号：{{ item.lockOrderId }}
              </view>
              <view class="flex items-center gap-16rpx">
                <wd-button size="small" plain custom-class="cancel-btn" @click="handleCancelOrder(item)">
                  取消订单
                </wd-button>
                <wd-button size="small" plain custom-class="pay-btn" @click="handlePay(item)">
                  付款
                </wd-button>
              </view>
            </view>
          </view>
        </view>
      </view>

      <!-- 空状态 -->
      <view v-if="data && data.length === 0" class="flex flex-col items-center pt100rpx">
        <StatusTip tip="暂无抵扣券" />
      </view>
    </view>
  </view>
</template>

<style lang="scss" scoped>
:deep(.use-btn) {
  border-color: #333 !important;
  color: #333 !important;
  border-radius: 32rpx !important;
}

:deep(.cancel-btn) {
  border-color: #999 !important;
  color: #999 !important;
  border-radius: 32rpx !important;
}

:deep(.pay-btn) {
  border-color: #333 !important;
  color: #333 !important;
  border-radius: 32rpx !important;
}
:deep(.wd-count-down){
  color: #1890ff !important;
}
</style>
