<template>
  <view class="Mall4j page-payment">
    <view class="pay-number">
      <view class="price">
        <block v-if="!isPurePoints">
          <view class="symbol">
            ￥
          </view>
          <view class="big">
            {{ wxs.parsePrice(totalFee)[0] }}
          </view>
          <view class="symbol">
            .{{ wxs.parsePrice(totalFee)[1] }}
          </view>
        </block>
        <view
          v-if="totalFee > 0 && orderScore > 0"
          class="big"
        >
          +
        </view>
        <view
          v-if="orderScore"
          class="big"
        >
          <text>{{ orderScore }}</text><text class="symbol">
            积分
          </text>
        </view>
      </view>
      <view class="time">
        <view class="text">
          {{ $t('payment.theRemainingTime') }}
        </view>
        <view class="num">
          {{ hou }}
        </view>
        <view class="colon">
          :
        </view>
        <view class="num">
          {{ min }}
        </view>
        <view class="colon">
          :
        </view>
        <view class="num">
          {{ sec }}
        </view>
      </view>
    </view>
    <!-- 支付方式选择器组件 -->
    <PaymentMethodSelector
      v-if="!isPurePoints"
      :total-balance="totalBalance"
      :is-pure-points="isPurePoints"
      @set-pay-type="setPayType"
    />
    <view
      class="sure-pay"
      @tap="onSurePay"
    >
      {{ $t('payment.determinePayment') }}
    </view>
    <!-- 确认弹窗 -->
    <confirm-pop
      :show-pop="showPop"
      :pop-content="popContent"
      @handle-pop-confirm="popConfirm"
      @handle-pop-cancel="onPopCancel"
    />
  </view>
</template>

<script setup>
import { PayType, PayEntry } from '@/utils/constant.js'
import Pay from '@/utils/pay.js'
import PaymentMethodSelector from '../../components/payment-method-selector/index.vue'

const wxs = number()
const domainAddress = import.meta.env.VITE_APP_DOMAIN_ADDRESS

const paySettlementType = uni.getStorageSync('cloudPaySettlementType') // 1 通联支付
let payType = PayType.ALIPAY_H5

let orderIds = '' // 订单id
let timer = '' // 定时器名称
const dvyType = 1 // 配送类型 1:快递 2:自提 3：无需快递 4:同城配送
let payStatus = null // 9 预售订单
let popConfirmType = -1 // 0：未绑定手机号 1：未实名认证 2：是否支付完成 3：未设置支付密码 4：余额不足
let isMemberInfoLoaded = false // 是否获取用户信息
let bizOrderNo = '' // 通联支付订单号

// 弹窗相关
const showPop = ref(false)
const popContent = ref({})

// 生命周期函数--监听页面加载
const isPurePoints = ref(false) // 是否纯积分
onLoad((options) => {
  if (options.orderIds) {
    orderIds = options.orderIds
  }
  if (options.isPurePoints) {
    isPurePoints.value = options.orderIds
  }
  if (options.pay_status) {
    payStatus = +options.pay_status
  }
  onGetOrderPaymentInfo()
  onQueryCurrentBalance()
})

// 生命周期函数--监听页面显示
let isClickPay = false
onShow(() => {
  if (paySettlementType === 1 && !isClickPay) {
    // 通联支付下，获取用户信息，判断用户是否为无感注册(是否有绑定用户标识)或是否绑定手机号
    onQetMemberInfo()
  }
  // #ifdef MP-WEIXIN
  // 使用余额支付后首次触发onShow，检查订单状态
  if (paySettlementType === 1 && payType === PayType.BALANCEPAY && bizOrderNo && isClickPay) {
    isClickPay = false
    onGetOrderStatus()
  }
  // #endif
})

onUnload(() => {
  clearTimeout(timer)
})

/**
 * 设置支付类型
 */
const setPayType = (paramPayType) => {
  payType = paramPayType
}

/**
 * 获取账户当前余额
 */
const totalBalance = ref(0) // 当前账户余额
const onQueryCurrentBalance = () => {
  http.request({
    url: '/tmerclub_user/user/user_info',
    method: 'GET',
    dontTrunLogin: true
  }).then(res => {
    totalBalance.value = paySettlementType === 1 ? res.allinpayActualBalance : res.actualBalance
  })
}

/**
 * 获取订单支付信息
 */
const totalFee = ref(0)
const orderScore = ref('')
let endTime = '' // 订单过期时间
const onGetOrderPaymentInfo = () => {
  http.request({
    url: '/tmerclub_order/order/order_pay_info',
    method: 'GET',
    data: {
      orderIds
    }
  }).then(res => {
    totalFee.value = res.totalFee
    orderScore.value = res.orderScore
    endTime = res.endTime
    // 生成倒计时
    onGetCountDown()
    // 是否纯积分
    isPurePoints.value = res.totalFee <= 0 && res.orderScore > 0
  })
}

/**
 * 生成支付倒计时
 */
const hou = ref('') // 时
const min = ref('') // 分
const sec = ref('') // 秒
const onGetCountDown = () => {
  const nowTime = new Date().getTime() // 现在时间（时间戳）
  const temEndTime = new Date(endTime.replace(/-/g, '/')).getTime() // 结束时间（时间戳）
  const time = (temEndTime - nowTime) / 1000 // 距离结束的毫秒数
  // 获取时、分、秒
  let tempHou = parseInt(time % (60 * 60 * 24) / 3600)
  let tempMin = parseInt(time % (60 * 60 * 24) % 3600 / 60)
  let tempSec = parseInt(time % (60 * 60 * 24) % 3600 % 60)
  tempHou = onTimeFormin(tempHou)
  tempMin = onTimeFormin(tempMin)
  tempSec = onTimeFormin(tempSec)
  hou.value = onTimeFormat(tempHou)
  min.value = onTimeFormat(tempMin)
  sec.value = onTimeFormat(tempSec)
  // 每1000ms刷新一次
  if (time > 0) {
    timer = setTimeout(onGetCountDown, 1000)
  } else {
    clearTimeout(timer)
    uni.showToast({
      title: '订单已过期',
      duration: 2000,
      icon: 'none',
      mask: true,
      success: () => {
        setTimeout(() => {
          uni.navigateTo({
            url: '/package-user/pages/order/order?orderStatus=0'
          })
        }, 2000)
      }
    })
  }
}

// 小于10的格式化函数（2变成02）
const onTimeFormat = (num) => {
  return num < 10 ? '0' + num : num
}
// 小于0的格式化函数（不会出现负数）
const onTimeFormin = (num) => {
  return num < 0 ? 0 : num
}

// 确认支付
const onSurePay = () => {
  if (paySettlementType === 1) {
    if (!isMemberInfoLoaded) {
      // 未加载完成，不允许点击
      return
    }
    // 通联支付且未绑定用户标识，使用微信支付/支付宝支付时需要判断是否绑定手机号; 使用余额支付时需要判断是否绑定手机号
    if ((!allinpayMemberInfo.isBindPayAcct && (payType === PayType.WECHATPAY_H5 || payType === PayType.ALIPAY_H5)) || payType === PayType.BALANCEPAY) {
      if (!allinpayMemberInfo.isIdentityChecked) {
        // 通联支付且未绑定用户标识，使用微信支付/支付宝支付时需要判断是否绑定手机号
        showPop.value = true
        popConfirmType = 1
        popContent.value.content = '请先进行实名认证'
        popContent.value.confirmText = '确定'
        popContent.value.title = ''
        return
      }
      if (!allinpayMemberInfo.isPhoneChecked) {
        showPop.value = true
        popConfirmType = 0
        popContent.value.content = '请先绑定用于保障账户余额安全的手机号'
        popContent.value.confirmText = '确定'
        popContent.value.title = ''
        return
      }
    }
    if (payType === PayType.BALANCEPAY && !allinpayMemberInfo.isSetPayPwd) {
      showPop.value = true
      popConfirmType = 3
      popContent.value.content = '请先设置支付密码，以保障您的账户余额安全'
      popContent.value.confirmText = '确定'
      popContent.value.title = ''
      return
    }
  }
  const paymentData = {
    payType,
    orderIds,
    isPurePoints: isPurePoints.value,
    dvyType,
    payEntry: PayEntry.ORDER
  }
  if (payStatus === 9) paymentData.isFinalPayment = true
  if (payType === PayType.BALANCEPAY) {
    if (totalFee.value > totalBalance.value) {
      const msg = '余额不足！请先充值余额'
      showPop.value = true
      popConfirmType = 4
      popContent.value.content = ''
      popContent.value.confirmText = '确定'
      popContent.value.title = msg
      return
    }
    if (paySettlementType === 1) {
      Pay.toOrderPay(paymentData).then((res) => {
        bizOrderNo = res.bizOrderNo
        isClickPay = true
      })
    } else {
      uni.showModal({
        title: '提示',
        content: '确认使用余额支付吗？',
        success: (res) => {
          if (res.confirm) {
            Pay.toOrderPay(paymentData)
          } else if (res.cancel) {
            uni.showToast({
              title: '取消支付',
              icon: 'none',
              duration: 1500
            })
          }
        }
      })
    }
    return
  }
  if (orderScore.value > 0 && totalFee.value <= 0) {
    uni.showModal({
      title: '提示',
      content: `确认使用${orderScore.value}积分支付吗？`,
      success: (res) => {
        if (res.confirm) {
          payType = 0 // 积分支付
          paymentData.payType = payType
          Pay.toOrderPay(paymentData)
        } else if (res.cancel) {
          uni.showToast({
            title: '取消支付',
            icon: 'none',
            duration: 1500
          })
          onGetOrderPaymentInfo()
        }
      }
    })
    return
  }
  Pay.toOrderPay(paymentData).then(res => {
    if (res && paySettlementType === 1 && payType === PayType.ALIPAY_H5) {
      bizOrderNo = res.bizOrderNo
      setTimeout(() => {
        showPop.value = true
        popConfirmType = 0
        popContent.value.content = ''
        popContent.value.confirmText = '支付完成'
        popContent.value.title = '是否支付完成'
      }, 1000)
    }
  })
}

/**
 * 弹窗确认
 */
const popConfirm = () => {
  if (popConfirmType === 2) {
    // 是否支付完成确认
    onGetOrderStatus()
    return
  } else if (popConfirmType === 0) {
    // 未绑定手机号的弹窗回调
    uni.navigateTo({
      url: '/package-user/pages/bind-mobile/bind-mobile'
    })
  } else if (popConfirmType === 1) {
    // 未实名认证的弹窗回调
    uni.navigateTo({
      url: '/package-user/pages/realname-verification/realname-verification'
    })
  } else if (popConfirmType === 3) {
    // 未设置支付密码的弹窗回调
    onToSetAllinpayPwd()
    return
  } else if (popConfirmType === 4) {
    uni.navigateTo({
      url: '/package-activities/pages/recharge/recharge'
    })
  }
  onPopCancel() // 关闭弹窗
}

const onGetOrderStatus = () => {
  http.request({
    url: '/tmerclub_payment/allinpay/order/get_order_status',
    method: 'GET',
    data: {
      bizOrderNo
    }
  }).then(res => {
    if (res.orderStatus === 4) {
      if (showPop.value) {
        onPopCancel() // 关闭弹窗
      }
      uni.showToast({
        title: '支付成功',
        duration: 2000,
        icon: 'none'
      })
      setTimeout(() => {
        uni.navigateTo({
          url: '/package-user/pages/order/order?orderStatus=0'
        })
      }, 2000)
    } else if (res.orderStatus === 99 || res.orderStatus === 1) {
      uni.showToast({
        title: '暂未支付完成，请稍后再试',
        duration: 2000,
        icon: 'none'
      })
    } else if (res.orderStatus === 3) {
      uni.showToast({
        title: '交易失败，请稍后重新提交支付订单',
        duration: 2000,
        icon: 'none'
      })
    }
  })
}

// 确认弹窗取消事件
const onPopCancel = () => {
  showPop.value = false
  popContent.value = {}
  popConfirmType = -1
}

// 获取会员信息（通联支付）
let allinpayMemberInfo = {}
const onQetMemberInfo = () => {
  isMemberInfoLoaded = false
  http.request({
    url: '/tmerclub_payment/allinpay/member/get_user_info',
    method: 'GET'
  }).then(res => {
    isMemberInfoLoaded = true
    allinpayMemberInfo = res
  }).catch(errMsg => {
    uni.hideLoading()
    isMemberInfoLoaded = true
    uni.showToast({
      title: errMsg.msg,
      duration: 2000,
      icon: 'none'
    })
  })
}

const onToSetAllinpayPwd = () => {
  // 跳转到设置支付密码页面
  const data = {
    jumpUrl: `${domainAddress}/package-activities/pages/payment/payment?orderIds=${orderIds}&isPurePoints=${isPurePoints.value}&pay_status=${payStatus}`,
    errorJumpUrl: `${domainAddress}/package-activities/pages/payment/payment?orderIds=${orderIds}&isPurePoints=${isPurePoints.value}&pay_status=${payStatus}`,
    jumpPageType: 1
  }
  // #ifdef APP-PLUS
  // 如果是app打开，则需要在url后面拼接isSetPayPwd=1，用于判断是否是设置或修改支付密码成功后返回的页面
  data.jumpUrl = domainAddress + '/package-user/pages/redirect/redirect?isSetPayPwd=1'
  data.errorJumpUrl = domainAddress + '/package-user/redirect/redirect?isSetPayPwd=1'
  // #endif
  // #ifdef MP-WEIXIN
  data.jumpPageType = 2
  // #endif
  uni.showLoading()
  http.request({
    url: '/tmerclub_payment/allinpay/member/set_pay_pwd',
    method: 'POST',
    dontTrunLogin: true,
    data
  }).then(res => {
    uni.hideLoading()
    onPopCancel()
    // #ifdef H5
    window.location.href = res
    // #endif
    // #ifdef MP-WEIXIN
    util.toAllinPay({
      targetUrl: res
    })
    // #endif
    // #ifdef APP-PLUS
    plus.runtime.openURL(res)
    // #endif
  }).catch(err => {
    uni.hideLoading()
    uni.showToast({
      title: err.msg,
      icon: 'none'
    })
  })
}

</script>

<style lang="scss" scoped>
@use "./payment.scss";
</style>
