<template>
  <view class="Mall4j page-recharge">
    <view class="recharge-con">
      <!-- 充值金额 -->
      <view class="tit">
        充值金额
      </view>
      <view class="price-box">
        <view
          v-for="(item,index) in rechargeList"
          :key="item.rechargeId"
          :class="['item', rechargeId === item.rechargeId?'active' : '']"
          @tap="changeRechargeId(item.rechargeId, item.rechargeAmount,index)"
        >
          <view
            v-if="item.presAmount && paySettlementType!==1"
            class="send"
          >
            送{{ wxs.parsePrice(item.presAmount)[0] }}.{{ wxs.parsePrice(item.presAmount)[1] }}元
          </view>
          <view
            v-if="item.rechargeAmount"
            class="text"
          >
            <view class="number">
              {{ wxs.parsePrice(item.rechargeAmount)[0] }}.{{ wxs.parsePrice(item.rechargeAmount)[1] }}元
            </view>
          </view>
          <view
            v-if="item.presScore && paySettlementType!==1"
            class="des"
          >
            <text>送</text><text v-if="item.presGrowth">
              {{ item.presGrowth }}成长值+
            </text><text v-if="item.presScore">
              {{ item.presScore }}积分
            </text>
          </view>
        </view>
        <view
          style="margin-left:0rpx"
          :class="['item recharge-free',rechargeId===-1? 'active':''] "
          @tap="changeRechargeId(-1, '',-1)"
        >
          <view class="text">
            自定义充值（元）
          </view>
          <input
            v-model="customAmount"
            type="digit"
            class="recharge-input"
            placeholder="单次最多可充值10万元"
            @focus="rechargeId===-1 && rechargeList.length"
            @input="handleInput"
          >
        </view>
      </view>

      <!-- 充值说明 -->
      <view
        v-if="paySettlementType!==1 && selectIndex !== -1 && desList.length"
        class="tit"
      >
        充值说明
      </view>
      <view
        v-if="paySettlementType!==1 && selectIndex !== -1 && desList.length"
        class="des-box"
      >
        <view
          v-for="(item,index) in desList"
          :key="index"
          class="item"
        >
          <view>{{ index+1 }}、</view>
          <view>{{ item }}</view>
        </view>
      </view>

      <!-- 支付方式 -->
      <view class="tit">
        支付方式
      </view>
      <radio-group
        v-if="paySettlementType !== 1"
        class="pay-way"
        @change="chagePayType"
      >
        <!-- #ifndef MP-WEIXIN -->
        <label
          v-if="appType > 2"
          :class="['item', payTypeStr === 'aliPay' ? 'active' : '']"
        >
          <view class="pay-name">
            <view class="img">
              <image src="../../static/images/alipay.png" />
            </view>
            <view class="name">支付宝</view>
          </view>
          <radio
            value="aliPay"
            color="#008aff !important"
            :checked="payTypeStr === 'aliPay'"
          />
        </label>
        <!-- #endif -->
        <label :class="['item', payTypeStr === 'wechatPay' ? 'active' : '']">
          <view class="pay-name">
            <view class="img">
              <image src="@/package-activities/static/images/wxpay.png" />
            </view>
            <view class="name">微信支付</view>
          </view>
          <radio
            value="wechatPay"
            color="#008aff !important"
            :checked="payTypeStr === 'wechatPay'"
          />
        </label>
      </radio-group>
      <radio-group
        v-if="paySettlementType === 1"
        class="pay-way"
        @change="chagePayType"
      >
        <!-- #ifndef MP-WEIXIN -->
        <label
          v-if="!isWeChat"
          :class="['item', payTypeStr === 'aliPay' ? 'active' : '']"
        >
          <view class="pay-name">
            <view class="img">
              <image src="../../static/images/alipay.png" />
            </view>
            <view class="name">支付宝</view>
          </view>
          <radio
            value="aliPay"
            color="#008aff"
            :checked="payTypeStr === 'aliPay'"
          />
        </label>
        <!-- #endif -->
        <!-- #ifdef MP-WEIXIN -->

        <label :class="['item', payTypeStr === 'wechatPay' ? 'active' : '']">
          <view class="pay-name">
            <view class="img">
              <image src="@/package-activities/static/images/wxpay.png" />
            </view>
            <view class="name">微信支付</view>
          </view>
          <radio
            value="wechatPay"
            color="#008aff"
            :checked="payTypeStr === 'wechatPay'"
          />
        </label>
        <!-- #endif -->
        <!-- #ifdef H5 -->
        <label
          v-if="isWeChat"
          :class="['item', payTypeStr === 'wechatPay' ? 'active' : '']"
        >
          <view class="pay-name">
            <view class="img">
              <image src="@/package-activities/static/images/wxpay.png" />

            </view>
            <view class="name">微信支付</view>
          </view>
          <radio
            value="wechatPay"
            color="#008aff"
            :checked="payTypeStr === 'wechatPay'"
          />
        </label>
        <!-- #endif -->
      </radio-group>

      <!-- 底部 -->
      <view class="btn-box">
        <view class="text">
          充值金额
          <text
            v-if="rechargeId!==-1"
            class="number"
          >
            ￥{{ wxs.parsePrice(rechargeAmount)[0] }}.{{ wxs.parsePrice(rechargeAmount)[1] }}
          </text>
          <text
            v-else
            class="number"
          >
            ￥{{ showCustomAmount }}
          </text>
        </view>
        <view
          class="btn"
          @tap="rechargeNow"
        >
          立即充值
        </view>
      </view>
    </view>
    <!-- 确认弹窗 -->
    <confirm-pop
      :show-pop="showPop"
      :pop-content="popContent"
      @handle-pop-cancel="popCancel"
      @handle-pop-confirm="popConfirm"
    />
  </view>
</template>
<script setup>
import { PayType, PayEntry } from '@/utils/constant.js'
import Pay from '@/utils/pay.js'

const wxs = number()
const paySettlementType = uni.getStorageSync('cloudPaySettlementType')
const rechargeId = ref(0)
const rechargeList = ref([])
const rechargeAmount = ref(0)
const customAmount = ref('')
const payTypeStr = ref('wechatPay') // 默认支付类型  aliPay 支付宝   wechatPay 微信支付
const selectIndex = ref(0)
const desList = ref([])
const isWeChat = ref(false)

let payType = PayType.ALIPAY_H5
const appType = uni.getStorageSync('cloudAppType')
let presAmount = 0
let presScore = 0
let presGrowth = 0
let couponTotalNum = 0
let couponList = []
// 确认弹窗
const showPop = ref(false)
const popContent = {
  title: '是否完成支付',
  content: '',
  cancelText: '取消',
  confirmText: '已完成支付'
}
let bizOrderNo = ''

const showCustomAmount = computed(() => Number(customAmount.value < 100000 ? customAmount.value : 100000).toFixed(2))

onLoad(() => {
  // 判断是否是微信浏览器
  // #ifdef H5
  if (paySettlementType === 1) {
    const ua = window.navigator.userAgent.toLowerCase()
    if (ua.match(/MicroMessenger/i) === 'micromessenger') {
      isWeChat.value = true // 微信中打开
    } else {
      isWeChat.value = false // 普通浏览器中打开
      payTypeStr.value = 'aliPay'
    }
  }
  // #endif
  // #ifdef APP-PLUS
  if (paySettlementType === 1) {
    // 通联支付下，app中只有支付宝支付
    payTypeStr.value = 'aliPay'
  }
  // #endif
  // 获取余额充值级别列表
  getRechargeList()
  // 设置支付方式
  setPayType()
})

// 设置支付方式
const setPayType = () => {
  payType = util.setDefaultPayType(payTypeStr.value)
}

const handleInput = (e) => {
  let price = e.detail.value
  price = price.replace(/(\d)(\.)(\d*)(\2*)(\d*)/g, '$1$2$3$5')
  price = price.replace(/^(-)*(\d+)\.(\d\d).*$/, '$1$2.$3')
  if (parseFloat(price) > 100000) {
    price = '100000'
  }
  nextTick(() => {
    customAmount.value = price
  })
}

const showDes = () => {
  desList.value = []
  if (presAmount) {
    desList.value.push(`每充值${(rechargeAmount.value / 100).toFixed(2)}元额外赠送${(presAmount / 100).toFixed(2)}元，多充多送，优惠多多；`)
  }
  if (presScore) {
    desList.value.push(`每充值${(rechargeAmount.value / 100).toFixed(2)}元送${presScore}积分，海量商品，等你抵扣；`)
  }
  if (presGrowth) {
    desList.value.push(`每充值${(rechargeAmount.value / 100).toFixed(2)}元送${presGrowth}成长值；`)
  }
  if (couponTotalNum) {
    desList.value.push(`一次性充值${(rechargeAmount.value / 100).toFixed(2)}元以上可额外获赠${couponTotalNum}张优惠券
      【` + couponList.join('、') + '】，优惠券将在24小时内发送到您的账户，请在“我的优惠券”里查看。')
  }
}

// 切换支付方式
const chagePayType = (val) => {
  payTypeStr.value = val.detail.value
  payType = util.setDefaultPayType(val.detail.value)
}

/**
 * 变更充值级别
 * @param {Number} id 余额充值项id: -1为自定义金额
 * @param {Number} amount 余额充值金额
 * @param {Number} index 当前选中的索引值
 */
const changeRechargeId = (id, amount, index) => {
  rechargeId.value = id
  selectIndex.value = index
  rechargeAmount.value = id !== -1 ? amount : ''
  customAmount.value = id === -1 ? customAmount.value : ''
  if (index >= 0 && index < rechargeList.value.length) {
    presAmount = rechargeList.value[index].presAmount
    presScore = rechargeList.value[index].presScore
    presGrowth = rechargeList.value[index].presGrowth
    couponTotalNum = rechargeList.value[index].couponTotalNum
    couponList = rechargeList.value[index].couponList.map(item => item.couponName)
  }
  showDes()
}

/**
     * 获取余额充值级别列表
     */
const getRechargeList = () => {
  http.request({
    url: '/tmerclub_user/user_recharge/list',
    method: 'GET'
  }).then(res => {
    if (res.length) {
      rechargeList.value = res
      rechargeList.value = rechargeList.value.sort(function (a, b) {
        return a.seq - b.seq
      })
      rechargeId.value = res[0].rechargeId
      rechargeAmount.value = res[0].rechargeAmount
      changeRechargeId(res[0].rechargeId, res[0].rechargeAmount, 0)
    } else {
      rechargeId.value = -1
    }
  })
}

/**
 * 立即充值-生成余额充值订单
 */
const rechargeNow = () => {
  const customAmountTemp = Number(customAmount.value.trim())
  if ((rechargeId.value === -1 && customAmountTemp <= 0) || !rechargeId.value || customAmount.value > 100000) {
    uni.showToast({
      title: '请输入正确的充值金额',
      duration: 2000,
      icon: 'none'
    })
    return
  }
  http.request({
    url: '/tmerclub_user/user_recharge/recharge',
    method: 'POST',
    data: {
      rechargeId: rechargeId.value !== -1 ? rechargeId.value : '',
      amount: rechargeId.value !== -1 ? rechargeAmount.value : Number(customAmount.value)
    }
  }).then(res => {
    const paymentData = {
      payType,
      orderIds: res,
      payEntry: PayEntry.RECHARGE
    }
    // 唤起支付
    if (paySettlementType !== 1) {
      Pay.toOrderPay(paymentData)
    } else {
      // #ifndef MP-WEIXIN
      Pay.toOrderPay(paymentData).then((res) => {
        setTimeout(() => {
          showPop.value = true
        }, 2000)
        bizOrderNo = res.bizOrderNo
      })
      // #endif
      // #ifdef MP-WEIXIN
      Pay.toOrderPay(paymentData)
      // #endif
    }
  })
}

// 确认弹窗取消事件
const popCancel = () => {
  showPop.value = false
}

// 确认弹窗确认事件
const popConfirm = () => {
  showPop.value = false
  http.request({
    url: '/tmerclub_payment/allinpay/order/get_order_status',
    method: 'GET',
    data: {
      bizOrderNo
    }
  }).then(res => {
    if (res.orderStatus === 4) {
      uni.showToast({
        title: '支付成功',
        duration: 2000,
        icon: 'none'
      })
      setTimeout(() => {
        uni.navigateTo({
          url: '/package-activities/pages/my-balance/my-balance'
        })
      }, 2000)
    } else {
      uni.showToast({
        title: '支付失败',
        duration: 2000,
        icon: 'none'
      })
    }
  })
}
</script>

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