<script setup lang="ts">
import type { wxpay } from '@/api/globals'
import router from '@/router'

definePage({ name: 'smqjh-threePay', islogin: false, style: { navigationBarTitleText: '支付', navigationStyle: 'custom' } })

const { token } = storeToRefs(useUserStore())
const { tenantCode } = storeToRefs(useSysStore())
const orderNumber = ref()
onLoad((options: any) => {
  orderNumber.value = options.orderNumber
  tenantCode.value = options.tenantCode
  token.value = ''
  handleLogin(options.phone)
  console.log(options, '============options=======')
})
const priceInfo = ref<wxpay>()
function handleLogin(phoneCode: string) {
  uni.showLoading({ mask: true })
  uni.login({
    provider: 'weixin',
    success: async (res) => {
      const data = await Apis.sys.auth({
        params: {
          grant_type: 'wechat',
          code: res.code,
          phoneCode,
        },
      })
      console.log(data, '============data=======')

      token.value = `Bearer ${data.data.access_token}`
      useUserStore().getUserInfo()
      handlePay()
    },
    complete: () => {
      uni.hideLoading()
    },
  })
}

async function handlePay() {
  const res = await useUserStore().handleCommonPayMent(orderNumber.value)
  priceInfo.value = res
  console.log(priceInfo.value, '=========================')
}
async function handleGoPay() {
  if (priceInfo.value?.payType !== 1) {
    try {
      await useUserStore().getWxCommonPayment(priceInfo.value as wxpay)
      router.push({ name: 'common-threePayRes', params: { price: String(priceInfo.value?.price), type: '1' } })
    }
    catch (error: any) {
      console.log(error, '=========================')

      router.push({ name: 'common-threePayRes', params: { price: String(priceInfo.value?.price), type: '0', error: error.errMsg } })
      // console.log(111)
    }
  }
}

// 倒计时：15分钟 = 900秒
const COUNTDOWN_SECONDS = 15 * 60
const countdown = ref(COUNTDOWN_SECONDS)
const countdownTimer = ref<ReturnType<typeof setInterval> | null>(null)

// 模块级变量：记录倒计时结束的时间戳，离页后回来可继续
// 页面卸载(onUnload)时重置，保证下次进入是全新的15分钟
let endTimestamp: number | null = null

// 格式化为 MM:SS
const countdownText = computed(() => {
  const m = Math.floor(countdown.value / 60).toString().padStart(2, '0')
  const s = (countdown.value % 60).toString().padStart(2, '0')
  return `${m}:${s}`
})

function updateCountdown() {
  if (!endTimestamp)
    return
  const remaining = Math.max(0, Math.ceil((endTimestamp - Date.now()) / 1000))
  countdown.value = remaining
  if (remaining <= 0) {
    stopCountdown()
    // TODO: 倒计时结束后的跳转逻辑
    router.push({ name: 'common-threePayRes', params: { price: String(priceInfo.value?.price), type: '0' } })
  }
}

function startCountdown() {
  // 首次进入：初始化结束时间戳
  if (!endTimestamp) {
    endTimestamp = Date.now() + COUNTDOWN_SECONDS * 1000
  }
  // 立即同步一次剩余时间（防止回来时短暂显示旧值）
  updateCountdown()
  stopCountdown()
  countdownTimer.value = setInterval(updateCountdown, 1000)
}

function stopCountdown() {
  if (countdownTimer.value) {
    clearInterval(countdownTimer.value)
    countdownTimer.value = null
  }
}

// 页面显示时启动/恢复倒计时（含首次进入和从其他页面返回）
onShow(() => {
  startCountdown()
})

// 离开页面时暂停定时器，但保留 endTimestamp
onHide(() => {
  stopCountdown()
})

// 页面卸载时清理，下次进入重新开始
onUnload(() => {
  stopCountdown()
  endTimestamp = null
})
</script>

<template>
  <view>
    <wd-navbar title="支付" :bordered="false" :z-index="99" safe-area-inset-top placeholder fixed />
    <view v-if="priceInfo" class="px20rpx pt20rpx">
      <view class="text-center text-48rpx text-#FF4A39">
        ￥{{ (priceInfo?.price / 100).toFixed(2) }}
      </view>
      <view class="mb20rpx mt24rpx text-center text-26rpx text-[#999]">
        支付剩余时间：<text class="text-[#FF4A39] font-semibold">
          {{ countdownText }}
        </text>
      </view>
      <wd-button block @click="handleGoPay">
        确认支付
      </wd-button>
    </view>
  </view>
</template>

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