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

definePage({
  name: 'voucherDetail',
  islogin: true,
  style: {
    navigationBarTitleText: '抵扣券详情',
    navigationStyle: 'custom',
  },
})

const StaticUrl = import.meta.env.VITE_STATIC_BASE_URL
const couponId = ref('')
const couponInfo = ref<Api.AppCouponDetailsVO>()

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

const { send } = useRequest(
  (id: string) => Apis.app.get_smqjh_system_app_api_membercoupon_findbyid({ params: { id } }),
  { immediate: false },
).onSuccess((res) => {
  couponInfo.value = res.data.data
})

onLoad((options: any) => {
  couponId.value = options.id || ''
  if (couponId.value) {
    send(couponId.value)
  }
})

// 计算剩余天数
const remainingDays = computed(() => {
  if (!couponInfo.value?.expirationTime)
    return ''
  const expire = new Date(couponInfo.value.expirationTime).getTime()
  const now = Date.now()
  const diff = expire - now
  if (diff <= 0)
    return '已过期'
  const days = Math.floor(diff / (1000 * 60 * 60 * 24))
  const hours = Math.floor((diff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60))
  return `${days}天${hours}小时`
})

// 计算支付倒计时
function getCountdownTime(orderCreateTime?: string): number {
  if (!orderCreateTime)
    return 0
  const createTime = new Date(orderCreateTime).getTime()
  const expireTime = createTime + 30 * 60 * 1000 // 30分钟
  const remaining = expireTime - Date.now()
  return remaining > 0 ? remaining : 0
}

// 去使用
function handleUse() {
  router.pushTab({ name: 'home' })
  useTabbar().setTabbarItemActive('home')
}

// 查看订单详情
function handleViewOrder() {
  router.pushTab({ name: 'order' })
  useTabbar().setTabbarItemActive('order')
}

// 取消订单（占位）
async function handleCancelOrder() {
  // useGlobalToast().show('功能开发中')
  await useUserStore().handleCommonCancelOrderJY(couponInfo.value?.orderNumber as string)
  send(couponId.value)
}

// 付款（占位）
function handlePay() {
  // useGlobalToast().show('功能开发中')
  useUserStore().handleCommonGoXiaoJuPay(couponInfo.value?.orderNumber as string)
}
</script>

<template>
  <view v-if="couponInfo" class="min-h-100vh bg-#f5f5f5 pb200rpx pt20rpx">
    <!-- 顶部券信息 -->
    <view class="mx24rpx rounded-16rpx bg-white px28rpx py32rpx">
      <view class="flex items-center">
        <image :src="`${StaticUrl}/smqjh-reful-juan.png`" class="mr12rpx h32rpx w32rpx" />
        <view class="text-30rpx font-semibold">
          抵扣{{ couponInfo.discountMoney }}元（满{{ couponInfo.amountMoney }}可用）
        </view>
      </view>
    </view>

    <!-- 券信息卡片 -->
    <view class="mx24rpx mt20rpx rounded-16rpx bg-white px28rpx py32rpx">
      <view class="mb20rpx text-30rpx font-semibold">
        券信息
      </view>
      <view class="text-26rpx text-#666 leading-48rpx">
        <view>券ID：{{ couponInfo.allowanceId || couponInfo.id }}</view>
        <view>批次号：{{ couponInfo.batchId || '-' }}</view>
        <view>状态：{{ couponInfo.lockStatus === 1 ? '已冻结' : statusMap.get(couponInfo.useStatus as number) || '-' }}</view>
        <view>面值：￥{{ couponInfo.discountMoney }}</view>
      </view>
    </view>

    <!-- 有效期卡片 -->
    <view class="mx24rpx mt20rpx rounded-16rpx bg-white px28rpx py32rpx">
      <view class="mb20rpx text-30rpx font-semibold">
        有效期
      </view>
      <view class="text-26rpx text-#666 leading-48rpx">
        <view>开始：{{ couponInfo.getTime || '-' }}</view>
        <view>结束：{{ couponInfo.expirationTime || '-' }}</view>
        <view v-if="couponInfo.useStatus === 1">
          使用：{{ couponInfo.orderPayTime || '-' }}
        </view>
        <view v-else>
          剩余：{{ remainingDays }}
        </view>
      </view>
    </view>

    <!-- 使用记录（已使用状态） -->
    <view v-if="couponInfo.useStatus === 1" class="mx24rpx mt20rpx rounded-16rpx bg-white px28rpx py32rpx">
      <view class="mb20rpx text-30rpx font-semibold">
        使用记录
      </view>
      <view class="text-26rpx text-#666 leading-48rpx">
        <view>订单号：{{ couponInfo.orderNumber || '-' }}</view>
        <view>油站：{{ couponInfo.storeName || '-' }}</view>
        <view>油号：{{ couponInfo.itemName || '-' }}</view>
        <view>枪号：{{ couponInfo.gunNo ? `${couponInfo.gunNo}号枪` : '-' }}</view>
        <view>订单金额：￥{{ couponInfo.totalMoney ? (couponInfo.totalMoney) : 0 }}</view>
        <view>抵扣金额：￥{{ couponInfo.discountMoney }}</view>
        <view>实付金额：￥{{ couponInfo.realMoney ? (couponInfo.realMoney) : 0 }}</view>
      </view>
    </view>

    <!-- 冻结信息（已冻结状态） -->
    <view v-if="couponInfo.lockStatus === 1 && couponInfo.useStatus === 2" class="mx24rpx mt20rpx rounded-16rpx bg-white px28rpx py32rpx">
      <view class="mb20rpx text-30rpx font-semibold">
        冻结信息
      </view>
      <view class="mb16rpx flex items-center text-26rpx text-#ff4d3a">
        <wd-icon name="info-circle" size="28rpx" color="#ff4d3a" class="mr8rpx" />
        当前券被订单占用
      </view>
      <view class="text-26rpx text-#666 leading-48rpx">
        <view>订单号：{{ couponInfo.orderNumber || '-' }}</view>
        <view>下单时间：{{ couponInfo.orderCreateTime || '-' }}</view>
        <view class="flex items-center">
          支付剩余时间：<wd-count-down :time="getCountdownTime(couponInfo.orderCreateTime)" format="mm分ss秒" />
        </view>
        <view>订单金额：￥{{ couponInfo.totalMoney ? (couponInfo.totalMoney) : 0 }}</view>
        <view>抵扣金额：￥{{ couponInfo.discountMoney }}</view>
      </view>
    </view>

    <!-- 无效原因（无效状态） -->
    <view v-if="couponInfo.useStatus === 7" class="mx24rpx mt20rpx rounded-16rpx bg-white px28rpx py32rpx">
      <view class="mb20rpx text-30rpx font-semibold">
        无效原因
      </view>
      <view class="mb16rpx flex items-center text-26rpx text-#ff4d3a">
        <wd-icon name="info-circle" size="28rpx" color="#ff4d3a" class="mr8rpx" />
        此券无法使用
      </view>
      <view class="text-26rpx text-#666">
        原因：油站已下线
      </view>
    </view>

    <!-- 使用规则卡片 -->
    <view class="mx24rpx mt20rpx rounded-16rpx bg-white px28rpx py32rpx">
      <view class="mb20rpx text-30rpx font-semibold">
        使用规则
      </view>
      <view class="text-26rpx text-#666 leading-44rpx">
        <view>·订单满{{ couponInfo.amountMoney }}元可用</view>
        <view>·抵扣金额：{{ couponInfo.discountMoney }}元</view>
        <view>·每单限用1张，不与其他优惠同享</view>
        <view>·使用全部合作油站</view>
        <view>·不支持部分特殊油站</view>
      </view>
    </view>

    <!-- 状态说明卡片 -->
    <view class="mx24rpx mt20rpx rounded-16rpx bg-white px28rpx py32rpx">
      <view class="mb20rpx text-30rpx font-semibold">
        状态说明
      </view>
      <view class="text-26rpx text-#666">
        <template v-if="couponInfo.lockStatus === 1 && couponInfo.useStatus === 2">
          此券已被当前订单占用，如需使用其他抵扣券，请先取消订单或完成支付
        </template>
        <template v-else-if="couponInfo.useStatus === 2">
          当前状态正常，可在下单时使用
        </template>
        <template v-else-if="couponInfo.useStatus === 1">
          此抵扣券已使用，您可以在活动期间关注新抵扣券
        </template>
        <template v-else-if="couponInfo.useStatus === 7">
          此抵扣券因合作变动无法使用，您可以联系客服处理。
        </template>
        <template v-else>
          此券当前不可用
        </template>
      </view>
    </view>

    <!-- 底部按钮 -->
    <FixedLayout>
      <!-- 可用状态 -->
      <wd-button
        v-if="couponInfo.useStatus === 2 && couponInfo.lockStatus !== 1"
        block
        size="large"
        @click="handleUse"
      >
        去使用
      </wd-button>

      <!-- 已使用状态 -->
      <wd-button
        v-else-if="couponInfo.useStatus === 1"
        block
        size="large"
        @click="handleViewOrder"
      >
        查看订单详情
      </wd-button>

      <!-- 已冻结状态 -->
      <view v-else-if="couponInfo.lockStatus === 1 && couponInfo.useStatus === 2" class="flex items-center gap-24rpx">
        <wd-button plain block size="large" custom-class="flex-1 cancel-btn" @click="handleCancelOrder">
          取消订单
        </wd-button>
        <wd-button block size="large" custom-class="flex-1" @click="handlePay">
          付款
        </wd-button>
      </view>
    </FixedLayout>
  </view>
</template>

<style lang="scss" scoped>
:deep(.cancel-btn) {
  border-color: var(--them-color) !important;
  color: var(--them-color) !important;
}
</style>
