<template>
  <view class="withdrawal-mian">
    <view class="withdrawal-box">
      <view class="select-card">
        <view class="tit">
          提现至
        </view>
        <view
          class="con"
          @tap="setBankCard"
        >
          <image
            class="icon-card"
            src="@/package-activities/static/images/icon-card.png"
          />
          <span v-if="selectedBankCard && selectedBankCard.bankCardNo">{{ selectedBankCard.bankName }}({{ selectedBankCard.bankCardNo.slice(-4) }})</span>
          <span v-else>请选择提现到账银行卡</span>
          <image
            class="arrow"
            src="@/static/images/arrow-right.png"
          />
        </view>
      </view>
      <view class="select-amount">
        <view class="tit">
          提现金额
        </view>
        <view class="con">
          <view class="symbol">
            ￥
          </view>
          <input
            v-model="amount"
            type="number"
            @blur="onAmountBlur"
          >
        </view>
      </view>
      <view class="canWithdrawTip">
        可提现余额￥{{ wxs.parsePrice(allAmount)[0]+'.'+wxs.parsePrice(allAmount)[1] }}，<view
          class="all"
          @tap="allWithdraw"
        >
          全部提现
        </view>
      </view>

      <view
        v-if="isAmountError"
        class="error"
      >
        <view class="icon">
          !
        </view>
        {{ isAmountError }}
      </view>

      <!-- 规则 -->
      <view class="rule-box">
        <view class="tit">
          提现须知
        </view>
        <view class="item">
          {{ $t('distribution.WithdrawalRules1') }}{{ amountMin }}{{ $t('distribution.yuan') }}{{ $t('distribution.WithdrawalRules2') }}{{ amountMax }}{{ $t('distribution.yuan') }}
        </view>
        <view
          v-if="frequency===-1"
          class="item"
        >
          {{ $t('distribution.WithdrawalRules3') }}
        </view>
        <view
          v-else
          class="item"
        >
          {{ $t('distribution.WithdrawalRules31') }}{{ frequency === 30 ? '' : frequency }}{{ frequency === 30 ? $t('distribution.WithdrawalRules34') : $t('distribution.WithdrawalRules32') }}{{ withdrawalNum }}{{ $t('distribution.WithdrawalRules33') }}
        </view>
        <view
          v-if="paymentExplain!==null"
          class="item"
        >
          3、{{ paymentExplain }}
        </view>
        <view class="item">
          {{ paymentExplain!==null?'4、':'3、' }}{{ $t('distribution.WithdrawalRules4') }}
        </view>
      </view>
    </view>
    <view
      class="btn"
      @tap="verification"
    >
      提现
    </view>

    <!-- 银行卡弹窗 -->
    <view
      v-show="showPop"
      class="popup"
    >
      <view
        class="mask"
        @tap="showPop=false"
      />
      <view class="pop-content">
        <view class="title">
          选择银行卡
          <image
            class="close"
            src="@/package-activities/static/images/icon_close.png"
            @tap="showPop=false"
          />
        </view>
        <view class="main">
          <view
            v-for="item in BankCardList"
            :key="item.bankCardNo"
            class="card-box"
            @tap="handleBankCard(item)"
          >
            <view class="con">
              <image
                class="icon-card"
                src="@/package-activities/static/images/icon-card.png"
              />
              {{ item.bankName }}({{ item.bankCardNo.slice(-4) }})
            </view>
            <image
              v-if="item===3"
              class="select"
              src="@/package-activities/static/images/icon-select.png"
            />
          </view>
          <view
            class="card-box"
            @tap="bindBankCard"
          >
            <view class="con">
              <image
                class="icon-card"
                src="@/package-activities/static/images/icon-card.png"
              />
              添加储蓄卡
            </view>
            <image
              class="select"
              src="@/package-activities/static/images/add2.png"
            />
          </view>
        </view>
      </view>
    </view>
    <!-- 验证码弹窗 -->
    <vaildCodePopup
      v-show="showCodePop"
      :show-code-pop="showCodePop"
      :amount="Number(amount)"
      :valid-code-config="validCodeConfig"
      :phone="selectedBankCard.phone"
      @get-code="getCode"
      @close-pop="showCodePop=false"
      @confirm="confirmWithdraw"
    />
  </view>
</template>

<script setup>
import Big from 'big.js'
import vaildCodePopup from '@/package-activities/components/valid-code-popup/index.vue'

const wxs = number()

Big.DP = 2

const amount = ref(0) // 提现金额
const isAmountError = ref('') // 提现金额错误提示
const showPop = ref(false) // 弹窗显示
const selectedBankCard = ref({}) // 选择的银行卡
const showCodePop = ref(false) // 验证码弹窗
let timer = ''
const validCodeConfig = reactive({
  mainText: '提现金额', // 主标题文字
  showGetCodeBtn: true, // 获取验证码按钮显隐
  isValidCodeTip: false, // 是否显示验证码提示
  count: '' // 验证码倒计时
})
let bizOrderNo = '' // 通联订单号

onLoad(() => {
  getBankCardList()
  loadWithdrawCashRule() // 提现规则
})

/**
 * 生命周期函数--监听页面加载
 */
onLoad(() => {
  getDisInfoData()
})

// 获取可提现余额（通联）
const allAmount = ref(0)
const getDisInfoData = () => {
  http.request({
    url: '/tmerclub_payment/allinpay/order/query_balance',
    method: 'GET'
  }).then(res => {
    allAmount.value = res.allAmount
  })
}

/**
 * 加载提现规则
 */
// 提现须知
const frequency = ref(0) // 天数
const withdrawalNum = ref(0) // 提现次数
const amountMax = ref(0) // 最大金额
const amountMin = ref(0) // 最低金额
const paymentExplain = ref(null) // 其他提示
const loadWithdrawCashRule = () => {
  http.request({
    url: '/tmerclub_marketing/distribution_set/info',
    method: 'GET',
    dontShowLogin: true
  }).then(res => {
    frequency.value = res.frequency
    withdrawalNum.value = res.number
    amountMax.value = res.amountMax
    amountMin.value = res.amountMin
    paymentExplain.value = res.paymentExplain
  })
}

// 金额输入判断
const onAmountBlur = (e) => {
  amount.value = e.detail.value.replace(/^(-)*(\d+)\.(\d\d).*$/, '$1$2.$3') // 只能输入两个小数
  if (!amount.value || Number(amount.value) <= 0) {
    isAmountError.value = '请输入正确金额'
  } else if (Number(amount.value) > new Big(allAmount.value).div(100).valueOf()) {
    isAmountError.value = '输入金额已超过可提现金额'
  } else {
    isAmountError.value = ''
  }
}

const allWithdraw = () => {
  isAmountError.value = ''
  amount.value = new Big(allAmount.value).div(100).valueOf()
}

// 打开验证码弹窗前验证金额是否正确，是否选择银行卡
const verification = () => {
  if (isAmountError.value) {
    return
  }
  if (!amount.value || Number(amount.value) <= 0) {
    isAmountError.value = '请输入正确金额'
    return
  } else if (Number(amount.value) > new Big(allAmount.value).div(100).valueOf()) {
    isAmountError.value = '输入金额已超过提现金额'
    return
  }

  if (!(selectedBankCard.value && selectedBankCard.value.bankCardNo)) {
    showCodePop.value = false
    uni.showToast({
      title: '请选择提现到账银行卡',
      icon: 'none'
    })
    return
  }
  showCodePop.value = true
}

/**
 * 获取验证码
 */
const getCode = () => {
  if (isAmountError.value) {
    showCodePop.value = false
    return
  }
  amount.value = Number(amount.value)
  /**
   *  不可提现的几个判断
   *  1：输入框输入的值为空 || 值小于或等于0的数字（提示：请输入正确金额！）
   *  2：输入框输入的值，大于可提现余额（提示：余额不足）
   */
  if (!amount.value || amount.value <= 0) {
    showCodePop.value = false
    isAmountError.value = '请输入正确金额'
    return
  } else if (amount.value > allAmount.value) {
    showCodePop.value = false
    isAmountError.value = '输入金额已超过提现金额'
    return
  }
  http.request({
    url: '/tmerclub_user/user_withdraw/apply',
    method: 'POST',
    data: {
      amount: String(amount.value),
      bankCardNo: selectedBankCard.value.bankCardNo
    }
  }).then(res => {
    validCodeConfig.isValidCodeTip = true
    bizOrderNo = res.bizOrderNo
    const timeCount = 60
    if (!timer) {
      validCodeConfig.count = timeCount
      validCodeConfig.showGetCodeBtn = false
      timer = setInterval(() => {
        if (validCodeConfig.count > 0 && validCodeConfig.count <= timeCount) {
          validCodeConfig.count--
        } else {
          clearInterval(timer)
          timer = null
          validCodeConfig.showGetCodeBtn = true
        }
      }, 1000)
    }
  }).catch(err => {
    uni.showToast({
      title: err.msg,
      icon: 'none'
    })
  })
}

/**
 * 确认提现
 */
const confirmWithdraw = (validCode) => {
  if (isAmountError.value) {
    return
  }
  /**
   *  不可提现的几个判断
   *  1：输入框输入的值为空 || 值小于或等于0的数字（提示：请输入正确金额！）
   *  2：输入框输入的值，大于该分销员的可提现余额（提示：余额不足）
   */
  if (!amount.value || amount.value <= 0) {
    isAmountError.value = '请输入正确金额'
    return
  } else if (amount.value > allAmount.value) {
    isAmountError.value = '输入金额已超过提现金额'
    return
  }
  if (!validCode) {
    uni.showToast({
      title: '请输入验证码',
      icon: 'none'
    })
    return
  }
  uni.showLoading()
  http.request({
    url: '/tmerclub_user/user_withdraw/pay_confirm',
    method: 'POST',
    data: {
      amount: amount.value,
      bankCardNo: selectedBankCard.value.bankCardNo,
      bizOrderNo,
      verificationCode: validCode
    }
  }).then(() => {
    uni.showModal({
      content: $t('distribution.withdrawalApplicationSubmitted'),
      showCancel: false,
      cancelText: $t('distribution.cancel'),
      confirmText: $t('distribution.confirm'),
      complete () {
        uni.navigateTo({
          url: '/package-activities/pages/withdrawal-record/withdrawal-record'
        })
      }
    })
  })
}
// 更改选择的银行卡
const setBankCard = () => {
  showPop.value = true
}
// 获取银行卡列表
const BankCardList = ref([]) // 银行卡列表
const getBankCardList = () => {
  http.request({
    url: '/tmerclub_payment/allinpay/member/query_bank_card',
    method: 'GET'
  }).then(res => {
    if (res.length) {
      BankCardList.value = res
    }
  })
}
// 更换银行卡
const handleBankCard = (item) => {
  selectedBankCard.value = item
  isAmountError.value = ''
  showPop.value = false
}
// 前往绑定银行卡
const bindBankCard = () => {
  uni.navigateTo({
    url: 'package-user/pages/bind-bank-card/bind-bank-card'
  })
}

</script>
<style  lang="scss" scoped>
@use "./allinpay-withdrawal.scss";
</style>
