<template>
  <view class="pay-page">

    <!-- 加载状态 -->
    <view v-if="loading" class="loading-container">
      <u-loading mode="circle" size="60"></u-loading>
      <text class="loading-text">加载中...</text>
    </view>

    <!-- 支付内容 -->
    <view v-else-if="payInfo" class="pay-content">
      <!-- 已支付状态 -->
      <view v-if="payInfo.status === PayStatus.PAYED.value" class="pay-result-section">
        <view class="result-icon success">
          <u-icon name="checkmark" size="60" color="#fff"></u-icon>
        </view>
        <view class="result-text">支付成功</view>
        <view class="result-desc">{{ countDown > 0 ? countDown + 's 后自动关闭' : '即将关闭...' }}</view>
      </view>

      <!-- 已取消/过期状态 -->
      <view v-else-if="payInfo.status === PayStatus.CANCELED.value" class="pay-result-section">
        <view class="result-icon fail">
          <u-icon name="close" size="60" color="#fff"></u-icon>
        </view>
        <view class="result-text">支付单已关闭</view>
        <view class="result-desc hint-desc">请重新发起支付</view>
        <view hover-class="app-tap-hover" class="close-btn" @click="exitMiniProgram">关闭小程序</view>
      </view>

      <!-- 待支付 / 支付中：展示待支付内容 -->
      <view v-else class="pay-main">
        <!-- 金额展示 -->
        <view class="amount-section">
          <text class="amount-label">支付金额</text>
          <view class="amount-value-row">
            <text class="amount-currency">¥</text>
            <text class="amount-value">{{ payInfo.amount }}</text>
          </view>
        </view>

        <!-- 订单信息 -->
        <view class="info-section">
          <view class="info-item" v-if="payInfo.description">
            <text class="info-label">订单描述</text>
            <text class="info-value">{{ payInfo.description }}</text>
          </view>
        </view>

        <!-- 支付按钮 -->
        <view class="btn-section">
          <button hover-class="app-tap-hover"
            class="pay-btn"
            :class="{ disabled: paying }"
            @click="handlePay"
            :disabled="paying"
          >
            <u-icon v-if="!paying" name="weixin-fill" size="36" color="#fff" style="margin-right: 12rpx;"></u-icon>
            {{ paying ? '支付中...' : '微信支付' }}
          </button>
        </view>
      </view>
    </view>

    <!-- 错误状态 -->
    <view v-else class="error-container">
      <view class="error-icon">
        <u-icon name="info-circle" size="80" color="#ccc"></u-icon>
      </view>
      <view class="error-text">{{ errorMsg || '支付单不存在' }}</view>
      <button hover-class="app-tap-hover" class="retry-btn" @click="loadPayDetail">重试</button>
    </view>
  </view>
</template>

<script>
import { PayStatus } from '@/common/enums/pay';

export default {
  data() {
    return {
      loading: true,
      paying: false,
      payNo: '',
      redirect: '',
      payInfo: null,
      errorMsg: '',
      countDown: 3,
      countDownTimer: null,
      PayStatus // 暴露给模板使用
    }
  },
  onLoad(options) {
    console.log('支付页面参数：', options)
    this.payNo = options.no || ''
    this.redirect = options.redirect ? decodeURIComponent(options.redirect) : ''

    if (this.payNo) {
      this.loadPayDetail()
    } else {
      this.loading = false
      this.errorMsg = '缺少支付单号'
    }
  },
  onUnload() {
    if (this.countDownTimer) {
      clearInterval(this.countDownTimer)
      this.countDownTimer = null
    }
  },
  methods: {
    /**
     * 加载支付单详情
     */
    loadPayDetail() {
      this.loading = true
      this.errorMsg = ''
      this.$u.get('/app/pay/detail', { no: this.payNo }).then(res => {
        if (res.code === 200 && res.data) {
          this.payInfo = res.data
          // 已支付成功，启动倒计时自动关闭
          if (res.data.status === PayStatus.PAYED.value) {
            this.startCountDown()
          }
        } else {
          this.errorMsg = res.msg || '获取支付单失败'
        }
      }).catch(error => {
        console.error('获取支付单失败', error)
        this.errorMsg = '网络错误，请重试'
      }).finally(() => {
        this.loading = false
      })
    },
    /**
     * 刷新支付单信息
     */
    refreshPayInfo() {
      this.$u.put('/app/pay/refreshPayResult', { no: this.payNo });
    },

    /**
     * 点击支付按钮：根据支付单状态决定调用激活支付还是重新支付
     */
    handlePay() {
      if (this.paying) return
      this.paying = true

      // 1. 获取微信登录 code
      uni.login({
        provider: 'weixin',
        success: (loginRes) => {
          const loginCode = loginRes.code
          if (!loginCode) {
            uni.showToast({ title: '获取登录信息失败', icon: 'none' })
            this.paying = false
            return
          }

          // 2. 根据支付单状态选择接口
          const isRepay = this.payInfo.status === PayStatus.PAYING.value
          const apiUrl = isRepay ? '/app/pay/repay' : '/app/pay/activePay'
          console.log('this.payInfo', this.payInfo, 'isRepay', isRepay)

          this.$u.put(apiUrl, {
            no: this.payNo,
            loginCode: loginCode,
            appType: '1'
          }).then(res => {
            if (res.code !== 200) {
              uni.showToast({ title: res.msg || '支付失败', icon: 'none' })
              this.paying = false
              return
            }

            const payData = res.data
            if (!payData || !payData.payParams) {
              uni.showToast({ title: '获取支付参数失败', icon: 'none' })
              this.paying = false
              return
            }

            // 3. 用返回的新支付单信息覆盖当前数据
            if (payData.pay) {
              this.payInfo = payData.pay
              if (payData.pay.no) {
                this.payNo = payData.pay.no
              }
            }

            // 4. 调起微信支付
            const payParams = payData.payParams
            wx.requestPayment({
              timeStamp: payParams.timeStamp,
              nonceStr: payParams.nonceStr,
              package: payParams.packageVal,
              signType: payParams.signType,
              paySign: payParams.paySign,
              success: () => {
                // 支付回调成功，刷新获取最新状态
                this.refreshPayInfo();
                this.handleSuccess();
              },
              fail: () => {
                // 支付失败/取消，也刷新获取最新状态（可能实际已成功）
                this.refreshPayInfo()
              },
              complete: () => {
                this.paying = false
              }
            })
          }).catch(error => {
            console.error('支付接口调用失败', error)
            uni.showToast({ title: '支付失败，请重试', icon: 'none' })
            // 接口失败也刷新一下支付单状态
            this.refreshPayInfo()
            this.paying = false
          })
        },
        fail: () => {
          uni.showToast({ title: '微信登录失败', icon: 'none' })
          this.paying = false
        }
      })
    },
    handleSuccess() {
      this.payInfo.status = PayStatus.PAYED.value;
      this.startCountDown();
    },

    /**
     * 启动倒计时，自动关闭小程序
     */
    startCountDown() {
      this.countDown = 3
      this.countDownTimer = setInterval(() => {
        this.countDown--
        if (this.countDown <= 0) {
          clearInterval(this.countDownTimer)
          this.countDownTimer = null
          this.exitMiniProgram()
        }
      }, 1000)
    },

    /**
     * 退出小程序
     */
    exitMiniProgram() {
      // #ifdef MP-WEIXIN
      wx.exitMiniProgram({
        success: () => {
          console.log('已退出小程序')
        },
        fail: () => {
          console.log('退出小程序失败')
        }
      })
      // #endif
    }
  }
}
</script>

<style lang="scss" scoped>
.pay-page {
  width: 100%;
  min-height: 100vh;
  background: #f5f5f5;
  display: flex;
  flex-direction: column;

  // 自定义导航栏
  .nav-bar {
    width: 100%;
    background: #fff;
    padding-top: var(--status-bar-height);

    .nav-bar-inner {
      height: 88rpx;
      display: flex;
      align-items: center;
      justify-content: center;

      .nav-title {
        font-size: 34rpx;
        font-weight: 600;
        color: #333;
      }
    }
  }

  // 加载状态
  .loading-container {
    flex: 1;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding-top: 200rpx;

    .loading-text {
      margin-top: 20rpx;
      font-size: 28rpx;
      color: #999;
    }
  }

  // 支付内容
  .pay-content {
    flex: 1;
    display: flex;
    flex-direction: column;
  }

  // 结果展示（已支付/已取消）
  .pay-result-section {
    flex: 1;
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 100rpx 60rpx;

    .result-icon {
      width: 120rpx;
      height: 120rpx;
      border-radius: 50%;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-bottom: 32rpx;

      &.success {
        background: #07c160;
      }

      &.fail {
        background: #ee0a24;
      }
    }

    .result-text {
      font-size: 36rpx;
      font-weight: 600;
      color: #333;
      margin-bottom: 16rpx;
    }

    .result-desc {
      font-size: 26rpx;
      color: #999;

      &.hint-desc {
        margin-top: 12rpx;
        color: #666;
        line-height: 1.6;
      }
    }

    .close-btn {
      margin-top: 48rpx;
      width: 60%;
      height: 80rpx;
      line-height: 80rpx;
      background: #fff;
      color: #666;
      border-radius: 40rpx;
      font-size: 28rpx;
      font-weight: 500;
      border: none;
      text-align: center;

      &:active {
        background: #e8e8e8;
        transform: scale(0.98);
      }
    }
  }

  // 待支付主内容
  .pay-main {
    flex: 1;
    display: flex;
    flex-direction: column;
    padding: 40rpx 30rpx;
  }

  // 金额展示区域
  .amount-section {
    background: #fff;
    border-radius: 24rpx;
    padding: 60rpx 40rpx;
    display: flex;
    flex-direction: column;
    align-items: center;
    margin-bottom: 24rpx;
    box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.04);

    .amount-label {
      font-size: 28rpx;
      color: #999;
      margin-bottom: 20rpx;
    }

    .amount-value-row {
      display: flex;
      align-items: baseline;

      .amount-currency {
        font-size: 40rpx;
        font-weight: 600;
        color: #333;
        margin-right: 8rpx;
      }

      .amount-value {
        font-size: 72rpx;
        font-weight: 700;
        color: #333;
        line-height: 1;
      }
    }
  }

  // 订单信息区域
  .info-section {
    background: #fff;
    border-radius: 24rpx;
    padding: 8rpx 32rpx;
    margin-bottom: 60rpx;
    box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.04);

    .info-item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 28rpx 0;
      border-bottom: 1rpx solid #f5f5f5;

      &:last-child {
        border-bottom: none;
      }

      .info-label {
        font-size: 28rpx;
        color: #999;
        flex-shrink: 0;
      }

      .info-value {
        font-size: 28rpx;
        color: #333;
        text-align: right;
        margin-left: 20rpx;
        word-break: break-all;
      }
    }
  }

  // 支付按钮区域
  .btn-section {
    margin-top: auto;
    padding-bottom: calc(40rpx + env(safe-area-inset-bottom));

    .pay-btn {
      width: 100%;
      height: 96rpx;
      background: #07c160;
      color: #fff;
      border-radius: 48rpx;
      font-size: 32rpx;
      font-weight: 600;
      border: none;
      display: flex;
      align-items: center;
      justify-content: center;
      transition: all 0.3s;

      &:active {
        background: #06ad56;
        transform: scale(0.98);
      }

      &.disabled {
        background: #ccc;
      }
    }
  }

  // 错误状态
  .error-container {
    flex: 1;
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 200rpx 60rpx;

    .error-icon {
      margin-bottom: 24rpx;
    }

    .error-text {
      font-size: 28rpx;
      color: #999;
      margin-bottom: 40rpx;
      text-align: center;
    }

    .retry-btn {
      padding: 20rpx 80rpx;
      background: #07c160;
      color: #fff;
      border-radius: 40rpx;
      font-size: 28rpx;
      border: none;

      &:active {
        opacity: 0.8;
      }
    }
  }
}
</style>
