<template>
  <view class="container">
    <view class="status-bar"></view>
    <!-- 顶部导航 -->
    <uni-nav-bar title="支付收银台" left-icon="left" @clickLeft="goBack" />

    <!-- 金额区域 -->
    <view class="amount-box">
      <text class="amount">¥{{ amount }}</text>
      <text class="countdown">剩余支付时间：{{ countdownTime }}</text>
    </view>

    <!-- 支付方式列表 -->
    <view class="pay-list">
      <view class="pay-item" @click="selectPayType('wx')">
        <view class="left">
          <image src="/static/wechat.png" class="icon" mode="widthFix" />
          <view class="pay-info">
            <text class="pay-name">微信支付</text>
            <text class="pay-desc">微信快捷支付</text>
          </view>
        </view>
        <view class="radio" :class="{ active: selectedType === 'wx' }" />
      </view>

      <view class="pay-item" @click="selectPayType('alipay')">
        <view class="left">
          <image src="/static/alipay.png" class="icon" mode="widthFix" />
          <view class="pay-info">
            <text class="pay-name">支付宝支付</text>
            <text class="pay-desc">支付宝快捷支付</text>
          </view>
        </view>
        <view class="radio" :class="{ active: selectedType === 'alipa··y' }" />
      </view>

      <view class="pay-item" @click="selectPayType('union')">
        <view class="left">
          <image src="/static/union.png" class="icon" mode="widthFix" />
          <view class="pay-info">
            <text class="pay-name">银联支付</text>
            <text class="pay-desc">云闪付/银行卡</text>
          </view>
        </view>
        <view class="radio" :class="{ active: selectedType === 'union' }" />
      </view>
    </view>

    <view class="tip">请选择支付方式完成缴费</view>

    <!-- 底部支付按钮 -->
    <view class="pay-btn" @click="handlePayClick">
      <text class="btn-text">立即支付 {{ amount }} 元</text>
    </view>
  </view>
</template>

<script setup>
  import { ref, onUnmounted } from 'vue'
  import { onLoad } from '@dcloudio/uni-app'
  import { getUnionPayTn } from '/pageSubPack/api/apiSub.js'
  import { getPushSingle } from '/pageSubPack/api/api.js'

  // #ifdef APP
  import { startPay, checkWalletInstalled } from '@/uni_modules/unionpay-full'
  // #endif

  const amount = ref('0.00')
  const countdownTime = ref('29:57')
  let timer = null
  const payData = ref({})

  // 读取支付数据
  onLoad(() => {
    const data = uni.getStorageSync('payData')
    if (data) {
      payData.value = data
      amount.value = Number(data.amount || 0).toFixed(2)
    }
    startCountdown()
  })

  onUnmounted(() => {
    if (timer) clearInterval(timer)
  })

  const startCountdown = () => {
    let [min, sec] = countdownTime.value.split(':')
    let totalSec = parseInt(min) * 60 + parseInt(sec)
    timer = setInterval(() => {
      totalSec--
      if (totalSec <= 0) {
        clearInterval(timer)
        uni.showToast({ title: '支付超时', icon: 'none' })
        setTimeout(() => uni.navigateBack(), 1500)
        return
      }
      const newMin = Math.floor(totalSec / 60).toString().padStart(2, '0')
      const newSec = (totalSec % 60).toString().padStart(2, '0')
      countdownTime.value = `${newMin}:${newSec}`
    }, 1000)
  }

  // 选中的支付类型（默认微信）
  const selectedType = ref('wx')

  // 返回
  const goBack = () => uni.navigateBack()

  // 选择支付方式
  const selectPayType = (type) => {
    selectedType.value = type
    uni.vibrateShort({ type: 'light' })
  }

  // 点击底部支付按钮
  const handlePayClick = () => {
    handlePay()
  }

  // ==================== 统一支付入口 ====================
  const handlePay = async () => {
    try {
      uni.showLoading({ title: '发起支付中' })

      // 向后端请求获取支付参数
      const res = await getUnionPayTn({
        amount: amount.value,
        orderDesc: (payData.value.type || '缴费') + '缴费',
        residentUserId: uni.getStorageSync('userId'),
        devicecode: payData.value.deviceCode || '',
        deviceType: '2'
      })
	   console.log('支付接口返回:', JSON.stringify(res.data))
      uni.hideLoading()

      if (res.code !== 200 || !res.data) {
        uni.showToast({ title: res.msg || '获取支付参数失败', icon: 'none' })
        return
      }

      const payType = selectedType.value
      const data = res.data

      // 根据支付方式调起对应 SDK
      if (payType === 'union') {
        // 银联：UMS SDK
        invokeUmsPay('unionpay', data.union?.tn || data.union || data)
      } else if (payType === 'wx') {
        // 微信：plus.payment（等申请微信SDK后切到UMS）
        invokeWxPay(data.wx || data.wxPayInfo || data)
      } else if (payType === 'alipay') {
        // 支付宝：UMS SDK
        invokeUmsPay('alipay', data.alipay || data.aliPayInfo || data)
      }

    } catch (err) {
      uni.hideLoading()
      console.log('支付异常', err)
      uni.showToast({ title: '支付请求异常', icon: 'none' })
    }
  }

  // ==================== UMS 统一支付（银联/支付宝）====================
  const invokeUmsPay = (channel, data) => {
    // #ifdef APP
    const tn = typeof data === 'string' ? data : (data.tn || JSON.stringify(data))

    // 银联渠道检查是否安装云闪付
    if (channel === 'unionpay') {
      const installed = checkWalletInstalled()
      if (!installed) {
        uni.showModal({
          title: '未安装云闪付',
          content: '请先下载安装云闪付App后再进行支付',
          showCancel: false,
          confirmText: '知道了'
        })
        return
      }
    }

    // 调起 UMS 支付
    startPay({
      channel: channel,
      tn: tn,
      mode: '00',
      callback: (result) => {
        console.log('UMS支付结果[' + channel + ']：', JSON.stringify(result))
        const code = result?.code
        if (code === 0) {
          paySuccess()
        } else if (code === 1) {
          uni.showModal({
            title: '支付处理中',
            content: '银行正在处理支付结果，请勿重复支付。您可在「缴费记录」中查看最终状态。',
            showCancel: false,
            confirmText: '我知道了',
            success: () => {
              uni.redirectTo({ url: '/pageSubPack/payment-list/paymentIndex' })
            }
          })
        } else if (code === -2) {
          uni.showToast({ title: '支付已取消', icon: 'none' })
        } else {
          uni.showToast({ title: result?.msg || '支付失败', icon: 'none' })
        }
      }
    })
    // #endif

    // #ifndef APP
    uni.showToast({ title: '支付仅支持App端', icon: 'none' })
    // #endif
  }

  // ==================== 微信支付（uni.requestPayment）====================
  const invokeWxPay = (data) => {
    const orderInfo = {
      appid: data.appId,
      partnerid: data.partnerId || data.partnerid || '',
      prepayid: data.prepayId || data.prepayid || (data.package || '').replace('prepay_id=', ''),
      package: 'Sign=WXPay',
      noncestr: data.nonceStr,
      timestamp: data.timeStamp,
      sign: data.paySign
    }

    uni.requestPayment({
      provider: 'wxpay',
      orderInfo: orderInfo,
      success: (res) => {
        console.log('微信支付成功', res)
        paySuccess()
      },
      fail: (err) => {
        console.error('微信支付失败或取消', err)
        uni.showToast({ title: '支付取消或失败', icon: 'none' })
      }
    })
  }

  // ==================== 支付宝支付（uni.requestPayment）====================
  const invokeAlipay = (data) => {
    const orderInfo = data.orderInfo || data

    uni.requestPayment({
      provider: 'alipay',
      orderInfo: orderInfo,
      success: (res) => {
        console.log('支付宝支付成功', res)
        paySuccess()
      },
      fail: (err) => {
        console.error('支付宝支付失败或取消', err)
        uni.showToast({ title: '支付取消或失败', icon: 'none' })
      }
    })
  }

  // ==================== 支付成功 ====================
  const paySuccess = () => {
    sendPaySuccessPush()
    uni.showToast({ title: '支付成功', icon: 'success' })
    uni.setStorageSync('paySuccess', true)
    setTimeout(() => {
      uni.redirectTo({
        url: '/pageSubPack/payment-list/arrearsPayment'
      })
    }, 1500)
  }

  // 缴费成功推送通知
  const sendPaySuccessPush = () => {
    const userId = uni.getStorageSync('userId')
    if (userId) {
      getPushSingle({
        userId: userId,
        channel: 'resident',
        title: '缴费成功',
        content: `您已成功缴纳${payData.value.type || ''}费用 ¥${amount.value}元`
      }).catch(err => console.log('推送发送失败', err))
    }
  }
</script>

<style scoped>
  /* 全局容器 */
  .container {
    width: 100%;
    height: 100vh;
    background-color: #f5f5f5;
    display: flex;
    flex-direction: column;
  }

  /* 金额区域 */
  .amount-box {
    background: #2F77FD;
    color: #fff;
    padding: 60rpx 20rpx;
    text-align: center;
  }

  .amount {
    font-size: 72rpx;
    font-weight: bold;
    display: block;
    margin-bottom: 16rpx;
  }

  .countdown {
    font-size: 26rpx;
    opacity: 0.9;
  }

  /* 支付方式列表 */
  .pay-list {
    margin-top: 20rpx;
    background-color: #fff;
    padding: 0 20rpx;
  }

  .pay-item {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 30rpx 20rpx;
    border-bottom: 1rpx solid #f0f0f0;
  }

  .pay-item:last-child {
    border-bottom: none;
  }

  .left {
    display: flex;
    align-items: center;
  }

  .icon {
    width: 56rpx;
    height: 56rpx;
    margin-right: 20rpx;
    border-radius: 8rpx;
  }

  .pay-info {
    display: flex;
    flex-direction: column;
  }

  .pay-name {
    font-size: 32rpx;
    color: #333;
    font-weight: 500;
  }

  .pay-desc {
    font-size: 24rpx;
    color: #999;
    margin-top: 4rpx;
  }

  /* 单选按钮 — 对勾样式 */
  .radio {
    width: 36rpx;
    height: 36rpx;
    border-radius: 50%;
    border: 2rpx solid #ccc;
    display: flex;
    align-items: center;
    justify-content: center;
    transition: all 0.2s;
  }

  .radio.active {
    border-color: #2F77FD;
    background-color: #2F77FD;
  }

  .radio.active::after {
    content: '';
    width: 10rpx;
    height: 18rpx;
    border: 3rpx solid #fff;
    border-left: none;
    border-top: none;
    transform: rotate(45deg) translate(-2rpx, -2rpx);
  }

  /* 底部提示 */
  .tip {
    font-size: 24rpx;
    color: #999;
    text-align: center;
    padding: 30rpx 0;
    margin-bottom: 120rpx;
  }

  /* 底部按钮 — 圆角胶囊 */
  .pay-btn {
    position: fixed;
    bottom: 40rpx;
    left: 30rpx;
    right: 30rpx;
    height: 90rpx;
    line-height: 90rpx;
    background: #2F77FD;
    color: #fff;
    text-align: center;
    font-size: 32rpx;
    font-weight: bold;
    border-radius: 45rpx;
  }
  .status-bar {
    width: 100vw;
    height: 46px;
  }
</style>
