<template>
  <view :class="['page-member-recharge','Mall4j', ['','vip1','vip2','vip3','vip4'][level]]">
    <view class="recharge-bg">
      <view class="head-tit">
        <view class="left-line">
          <view class="square" />
          <view class="line" />
        </view>
        <view class="txt">
          {{ purchaseOrRenewal }}付费会员
        </view>
        <view class="right-line">
          <view class="square" />
          <view class="line" />
        </view>
      </view>
      <view class="recharge-selector">
        <view
          v-for="(item, index) in rechargeOptions"
          :key="index"
          :class="['item', userLevelTermId === item.levelTermId ? 'active' : '']"
          @tap="swichDurationOption(item.levelTermId)"
        >
          <view class="left">
            ￥<text class="big">
              {{ wxs.parsePrice(item.needAmount)[0] }}.{{ wxs.parsePrice(item.needAmount)[1] }}
            </text>/{{ ['月','季','年'][item.termType ] }}
          </view>
          <view class="right">
            <view
              v-if="index !== 0&&item.discount*10 < 10&&item.discount"
              class="tag"
            >
              优惠限时{{ (item.discount*10).toFixed(1) }}折
            </view>
            <view
              v-if="item.originalPrice > item.needAmount"
              class="scribing-price"
            >
              原价￥{{ wxs.parsePrice(item.originalPrice)[0] }}.{{ wxs.parsePrice(item.originalPrice)[1] }}
            </view>
          </view>
          <view
            v-if="userLevelTermId === item.levelTermId"
            class="selected-btn"
          >
            <image src="/static/images/hook.png" />
          </view>
        </view>
      </view>

      <!-- 立即支付 -->
      <view class="confirm">
        <view
          class="btn"
          @tap="isShowPaymentSelectorPopup=true"
        >
          确认购买
        </view>
      </view>
      <!-- 支付方式选择弹窗 -->
      <view
        class="popup price-detail"
        :class="{ 'show': isShowPaymentSelectorPopup }"
      >
        <view
          class="popup-mask"
          @tap="onClosePopup"
        />
        <view class="popup-con-bottom">
          <view class="popup-tit">
            <view class="tit-text">
              选择支付方式
            </view>
            <view
              class="close"
              @tap="onClosePopup"
            >
              <image src="/static/images/close.png" />
            </view>
          </view>
          <view class="con-box">
            <!-- 支付方式选择器组件 -->
            <PaymentMethodSelector
              :total-balance="totalBalance"
              @set-pay-type="onSetPayType"
            />
            <view class="btn-box">
              <view
                class="btn"
                @tap="payNow"
              >
                立即支付
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>
    <confirm-pop
      :show-pop="showPop"
      :show-cancel="isShowCancel"
      :pop-content="popContent"
      @handle-pop-confirm="onPopConfirm"
      @handle-pop-cancel="onPopCancel"
    />
  </view>
</template>
<script setup>
import util from '@/utils/util.js'
import Pay from '@/utils/pay'
import { PayType, PayEntry } from '@/utils/constant'
import PaymentMethodSelector from '../../components/payment-method-selector/index.vue'
import { computed } from 'vue'
const wxs = number()

let userLevelId = 0
const level = ref('')
onLoad((option) => {
  userLevelId = parseInt(option.userLevelId)
  level.value = parseInt(option.level)
  onGetUserLevelTerm()
  onGetUserInfo()
  onQueryCurrentBalance()
})
const paySettlementType = uni.getStorageSync('cloudPaySettlementType') // 1:通联支付
onShow(() => {
  if (paySettlementType === 1) {
    // 通联支付下，获取用户信息，判断用户是否为无感注册(是否有绑定用户标识)或是否绑定手机号
    onGetMemberInfo()
  }
})
let userInfo = ''
let statu = ''
const purchaseOrRenewal = computed(() => {
  if (userInfo.levelType === 0) {
    statu = '购买'
  }
  if (userInfo.levelType === 1 && userInfo.userLevelId === userLevelId) {
    statu = '续费'
  } else {
    statu = '购买'
  }
  return statu
})
/**
 * 弹窗确认
 */
let bizOrderNo = '' // 通联支付订单号
let popConfirmType = -1 // 弹窗确认类型 0:未绑定手机号提示 1:询问是否支付完成 2: 未实名认证提示
const onPopConfirm = () => {
  if (popConfirmType === 0) {
    // 未绑定手机号的弹窗回调
    uni.navigateTo({
      url: '/package-user/pages/bind-mobile/bind-mobile'
    })
  } else if (popConfirmType === 1) {
    // 支付发起后，确实是否完成弹窗回调
    http.request({
      url: '/tmerclub_payment/allinpay/order/get_order_status',
      method: 'GET',
      data: {
        bizOrderNo
      }
    }).then(res => {
      if (res.orderStatus === 4) {
        onPopCancel()
        uni.showToast({
          title: '支付成功',
          duration: 2000,
          icon: 'none'
        })
        setTimeout(() => {
          uni.navigateTo({
            url: '/package-activities/pages/member-center/member-center'
          })
        }, 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'
        })
      }
    })
    return
  } else if (popConfirmType === 2) {
    // 未实名认证的弹窗回调
    uni.navigateTo({
      url: '/package-user/pages/realname-verification/realname-verification'
    })
  } else if (popConfirmType === 3) {
    // 未设置支付密码的弹窗回调
    onToSetAllinpayPwd()
    return
  }
  onPopCancel()
}

// 确认弹窗取消事件
const isShowCancel = ref(false) // 是否显示取消按钮
const popContent = ref({})
const showPop = ref(false)
const onPopCancel = () => {
  showPop.value = false
  isShowCancel.value = true
  popConfirmType = -1
  popContent.value = {}
}

/**
 * 设置支付类型
 */
const payType = ref(PayType.ALIPAY_H5)
const onSetPayType = (isPayType) => {
  payType.value = isPayType
}

/**
 * 关闭弹窗
 */
const isShowPaymentSelectorPopup = ref(false)
const onClosePopup = () => {
  isShowPaymentSelectorPopup.value = false
}
const userLevelTermId = ref(0) // 当前选中
const swichDurationOption = (levelTermId) => {
  userLevelTermId.value = levelTermId
}
/**
 * 获取账户当前余额
 */
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 onGetUserInfo = () => {
  http.request({
    url: '/tmerclub_user/user_level/member_info',
    data: {
      levelType: 1
    },
    method: 'GET'
  }).then(res => {
    userInfo = res
  })
}
/**
 * 获取会员期数列表
 */
const rechargeOptions = ref([])
const onGetUserLevelTerm = () => {
  http.request({
    url: '/tmerclub_user/user_level/get_user_level_term',
    method: 'GET',
    data: {
      userLevelId
    }
  }).then(res => {
    rechargeOptions.value = res
    userLevelTermId.value = res[0].levelTermId
  })
}

/**
 * 购买付费会员
 */
let allinpayMemberInfo = {} // 通联支付用户信息
let isMemberInfoLoaded = false // 通联支付下，用户信息是否已加载
const payNow = util.debounce(function () {
  if (paySettlementType === 1) {
    if (!isMemberInfoLoaded) {
      // 用户信息未加载完成，不允许点击
      return
    }
    if ((!allinpayMemberInfo.isBindPayAcct && (payType.value === PayType.WECHATPAY_H5 || payType.value === PayType.ALIPAY_H5)) || payType.value === PayType.BALANCEPAY) {
      if (!(allinpayMemberInfo && allinpayMemberInfo.isIdentityChecked)) {
        // 通联支付且未绑定用户标识，使用微信支付/支付宝支付时需要判断是否绑定手机号
        showPop.value = true
        isShowCancel.value = true
        popConfirmType = 2
        popContent.value.content = '请先进行实名认证'
        popContent.value.confirmText = '确定'
        popContent.value.title = ''
        return
      }
      if (!allinpayMemberInfo.isPhoneChecked) {
        showPop.value = true
        isShowCancel.value = true
        popConfirmType = 0
        popContent.value.content = '请先绑定用于保障账户余额安全的手机号'
        popContent.value.confirmText = '确定'
        popContent.value.title = ''
        return
      }
    }
    if (payType.value === PayType.BALANCEPAY && !allinpayMemberInfo.isSetPayPwd) {
      showPop.value = true
      isShowCancel.value = true
      popConfirmType = 3
      popContent.value.content = '请先设置支付密码，以保障您的账户余额安全'
      popContent.value.confirmText = '确定'
      popContent.value.title = ''
    }
  }
  http.request({
    url: '/tmerclub_user/user_level/buy_vip',
    method: 'POST',
    data: {
      levelTermId: userLevelTermId.value,
      userLevelId
    }
  }).then(res => {
    // 唤起支付
    const paymentData = {
      payType: payType.value,
      orderIds: String(res),
      payEntry: PayEntry.VIP
    }
    // promise未执行resolve函数，则.then不会执行（通联才会返回promise）
    Pay.toOrderPay(paymentData).then(res => {
      if (res && paySettlementType === 1) {
        bizOrderNo = res.bizOrderNo
        // #ifndef MP-WEIXIN
        setTimeout(() => {
          // 延迟打开确定是否支付完成弹窗，并隐藏支付方式选择器组件
          isShowPaymentSelectorPopup.value = false
          showPop.value = true
          isShowCancel.value = true
          popConfirmType = 1
          popContent.value.content = ''
          popContent.value.confirmText = '支付完成'
          popContent.value.title = '是否支付完成'
        }, 1000)
        // #endif
      }
    }).catch(errMsg => {
      showPop.value = true
      isShowCancel.value = false
      popContent.value.title = ''
      popContent.value.confirmText = ''
      popContent.value.content = errMsg.msg
    })
  })
})
// 获取会员信息（通联支付）
const onGetMemberInfo = () => {
  uni.showLoading()
  isMemberInfoLoaded = false
  http.request({
    url: '/tmerclub_payment/allinpay/member/get_user_info',
    method: 'GET'
  }).then(res => {
    isMemberInfoLoaded = true
    allinpayMemberInfo = res
    uni.hideLoading()
  }).catch(errMsg => {
    isMemberInfoLoaded = true
    uni.hideLoading()
    uni.showToast({
      title: errMsg.msg,
      duration: 2000,
      icon: 'none'
    })
  })
}
const onToSetAllinpayPwd = () => {
  // 跳转到设置支付密码页面
  const data = {
    jumpUrl: `${import.meta.env.VITE_APP_DOMAIN_ADDRESS}/package-activities/pages/member-recharge/member-recharge?level=${level.value}&userLevelId=${userLevelId}`,
    errorJumpUrl: `${import.meta.env.VITE_APP_DOMAIN_ADDRESS}/package-activities/pages/member-recharge/member-recharge?level=${level.value}&userLevelId=${userLevelId}`,
    jumpPageType: 1
  }
  // #ifdef APP-PLUS
  // 如果是app打开，则需要在url后面拼接isSetPayPwd=1，用于判断是否是设置或修改支付密码成功后返回的页面
  data.jumpUrl = import.meta.env.VITE_APP_DOMAIN_ADDRESS + '/package-user/pages/redirect/redirect?isSetPayPwd=1'
  data.errorJumpUrl = import.meta.env.VITE_APP_DOMAIN_ADDRESS + '/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
    // eslint-disable-next-line no-undef
    plus.runtime.openURL(res)
    // #endif
  }).catch(err => {
    uni.hideLoading()
    uni.showToast({
      title: err.msg,
      icon: 'none'
    })
  })
}

</script>

<style lang="scss" scoped>
@use "./member-recharge.scss";
@use "@/popup.scss";
</style>
