<template>
  <view class="container">
    <!-- 状态栏 -->
    <view class="status-bar"></view>

    <!-- 顶部导航 -->
    <uni-nav-bar
      title="支付收银台"
      left-icon="left"
      @clickLeft="goBack"
      background-color="#F5F6F9"
      color="#000"
    />

    <!-- 内容区域 -->
    <view class="content">
      <!-- 金额区域 -->
      <view class="amount-box">
        <view class="amount-text">缴费金额</view>
        <text class="amount"> <text style="font-size: 32rpx;"> ¥ </text>{{ amount }}</text>
        <view class="countdown-wrap">
          <text class="countdown">剩余支付时间 {{ countdownTime }}</text>
        </view>
      </view>

      <!-- 支付方式列表 -->
	  <view class="tip">请选择支付方式</view>
      <view class="pay-list">
        <view class="pay-item" @click="selectPayType('wx')">
          <view class="left">
            <image src="https://wuyeadmin.bugtc.com/images/home/wechat.png" class="icon" mode="widthFix" />
            <view class="pay-info">
              <text class="pay-name">微信</text>
            </view>
          </view>
          <view class="radio" :class="{ active: selectedType === 'wx' }" />
        </view>

        <view class="pay-item" @click="selectPayType('alipay')">
          <view class="left">
            <image src="https://wuyeadmin.bugtc.com/images/home/alipay.png" class="icon" mode="widthFix" />
            <view class="pay-info">
              <text class="pay-name">支付宝</text>
            </view>
          </view>
          <view class="radio" :class="{ active: selectedType === 'alipay' }" />
        </view>
      </view>

      
    </view>

    <!-- 底部支付按钮 -->
    <view class="btn-wrap">
      <view class="pay-btn" @click="handlePayClick">
        <text class="btn-text">立即支付 {{ amount }} 元</text>
      </view>
    </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'

  // 支付宝和微信支付

  const amount = ref('0.00')
  const countdownTime = ref('10:00')
  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
    // #ifndef APP-HARMONY
    uni.vibrateShort({ type: 'light' })
    // #endif
  }

  const handlePayClick = () => {
    handlePay()
  }

  const handlePay = async () => {
    try {
      uni.showLoading({ title: '发起支付中' })
      const payTypeMap = { wx: '0', alipay: '1' }
      const backendPayType = payTypeMap[selectedType.value] || '1'

      const res = await getUnionPayTn({
        amount: amount.value,
        orderDesc: (payData.value.type || '缴费') + '缴费',
        residentUserId: uni.getStorageSync('userId'),
        payType: backendPayType,
        deviceCode: payData.value.deviceCode || '',
        deviceType: '2',
        chargeTypeId: payData.value.chargeTypeId,
        chargeItemId: payData.value.chargeItemId,
        billId: payData.value.billId,
        houseId: payData.value.houseId
      })
      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

      if (payType === 'wx') {
        invokeWxPay(data.wx || data.wxPayInfo || data)
      } else if (payType === 'alipay') {
        invokeAlipay(data.alipay || data.aliPayInfo || data)
      }

    } catch (err) {
      uni.hideLoading()
      console.log('支付异常', err)
      uni.showToast({ title: '支付请求异常', icon: 'none' })
    }
  }
  
	// 微信支付
  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' })
      }
    })
  }
	
	// 支付宝支付
  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/addPaymentSuccess?type=pay'
      })
    }, 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 {
    display: flex;
    flex-direction: column;
    width: 100%;
    min-height: 100vh;
    background-color: #F5F6F9;
    padding: 0 30rpx;
    box-sizing: border-box;
  }

  /* 状态栏 */
  .status-bar {
    width: 100%;
    height: var(--status-bar-height);
  }

  /* 内容区域 */
  .content {
    /* flex: 1; */
  }

  /* 金额卡片 */
  .amount-box {
    background: #ffffff;
    border-radius: 20rpx;
    padding: 50rpx 0;
    text-align: center;
    margin: 30rpx 0;
  }

  .amount-text {
    font-size: 28rpx;
    color: #666;
    margin-bottom: 16rpx;
  }

  .amount {
    display: block;
    font-size: 52rpx;
    font-weight: bold;
    color: #333;
  }

  /* 倒计时样式 */
  .countdown-wrap {
    display: inline-block;
    margin-top: 24rpx;
    padding: 8rpx 24rpx;
    background: #F4F4F4;
    border-radius: 30rpx;
  }

  .countdown {
    font-size: 28rpx;
    color: #000;
  }

  /* 支付方式卡片 */
  .pay-list {
    background: #ffffff;
    border-radius: 20rpx;
    padding: 0 30rpx;
    margin-bottom: 30rpx;
  }

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

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

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

  .icon {
    width: 56rpx;
    height: 56rpx;
    margin-right: 24rpx;
  }

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

  /* 单选按钮 — 对勾样式 */
  .radio {
    width: 44rpx;
    height: 44rpx;
    border-radius: 50%;
    border: 3rpx solid #d0d0d0;
    display: flex;
    align-items: center;
    justify-content: center;
    box-sizing: border-box;
  }

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

  .radio.active::after {
    content: '';
    width: 12rpx;
    height: 22rpx;
    border: 4rpx solid #fff;
    border-left: 0;
    border-top: 0;
    transform: rotate(45deg) translate(-2rpx, -2rpx);
  }

  /* 提示 */
  .tip {
    font-size: 32rpx;
    color: #333;
	font-weight: 500;
    text-align: left;
    padding: 20rpx 0;
  }

  /* 底部按钮区域 */
  .btn-wrap {
    padding: 30rpx 0 60rpx;
  }

  /* 底部支付按钮 */
  .pay-btn {
    width: 100%;
    height: 96rpx;
    line-height: 96rpx;
    background: #2F77FD;
    color: #fff;
    text-align: center;
    font-size: 34rpx;
    font-weight: bold;
    border-radius: 8rpx;
    box-shadow: 0 6rpx 20rpx rgba(47, 119, 253, 0.3);
  }
</style>