<!--
  Copyright (c) 2018-2999 广州市蓝海创新科技有限公司 All rights reserved.

  https://www.mall4j.com/

  未经允许，不可做商业用途！

  版权所有，侵权必究！
-->

<template>
  <view class="Mall4j page-withdraw container">
    <view class="form-title">
      {{ $t('dianPuMingCheng') }}
    </view>
    <view class="form-item">
      <view style="font-size:28rpx">
        {{ dataForm.shopName }}
      </view>
    </view>
    <view class="form-title">
      {{ $t('tiXianJinE') }}<text class="form-title-desc">
        {{ $t('keTiXianYuewithdrawamount').replace('[withdrawAmount]', withdrawAmount) }}
      </text>
    </view>
    <view
      class="form-item form-item-input"
      style="height:40rpx"
    >
      <input
        v-model="dataForm.amount"
        type="number"
        :placeholder="$t('shuRuTiXianJinE')"
        @blur="onBlurAmount"
      >
      <view
        class="form-item-button"
        @tap="()=>{dataForm.amount=withdrawAmount}"
      >
        {{ $t('quanBuTiXian') }}
      </view>
    </view>
    <text class="required">
      {{ $t('key') }}
    </text><view class="form-title">
      {{ $t('daoZhangYinHangKa') }}
    </view>
    <view class="form-item bank-card">
      <text style="font-size:28rpx">
        {{ selectedBank.bankName }}
      </text><view
        class="form-item-button"
        @tap="chooseBank"
      >
        {{ $t('xuanZeYinHangKa') }}
      </view>
    </view>
    <text class="required">
      {{ $t('key-0') }}
    </text><view class="form-title">
      {{ $t('duanXinYanZheng') }} <text
        v-if="paySettlementType===1"
        class="form-title-desc"
      >
        {{ $t('shouJiWeiHaoReceivemobile').replace('[receiveMobile]', receiveMobile) }}
      </text>
    </view>
    <view class="form-item form-item-input code">
      <input
        v-model="dataForm.code"
        type="number"
        maxlength="6"
        :placeholder="$t('shuRuYanZhengMa')"
      >
      <view
        v-if="!showCount"
        class="form-item-button"
        @click="showCheck"
      >
        {{ $t('huoQuYanZhengMa') }}
      </view>
      <view
        v-else
        class="form-item-count"
      >
        {{ count }}
      </view>
    </view>
    <view
      v-if="paySettlementType===1"
      class="code-tip"
    >
      {{ $t('yanZhengMaJiangFaSongDaoYinHangKaYuLiuShouJiHaoFaSongYanZhengMaHouJiangHuiDongJieBenCiTiXianJineqieBuKeCheHuiQingJinShenCaoZuo') }}
    </view>
    <view class="form-title">
      {{ $t('beiZhu') }}
    </view>
    <view class="form-item">
      <textarea
        v-model="dataForm.shopRemarks"
        :placeholder="$t('zuiDuo_60ZiTeShuZiFuHuiBeiGuoLv')"
        :maxlength="60"
        style="height:160rpx"
        @input="handleInput"
      />
    </view>

    <view
      class="button-submit"
      @tap="dataFormSubmit"
    >
      <text>{{ $t('tiJiaoShenQing') }}</text>
    </view>
    <verify
      ref="verifyRef"
      :mode="'pop'"
      captcha-type="blockPuzzle"
      :v-space="15"
      :img-size="{ width: '320px', height: '160px' }"
      @success="sendCode"
    />
  </view>
</template>
<script setup>
import { nextTick, onMounted } from 'vue'

const paySettlementType = uni.getStorageSync('bbcPaySettlementType')
const dataForm = reactive({
  amount: '', // 提现余额
  shopName: '', // 店铺名称
  shopRemarks: '', // 备注
  code: '', // 验证码
  shopBankCardId: '' // 当前选择的银行卡id
})
let bankList = [] // 银行列表
const selectedBank = ref({}) // 所选银行
let isSendCode = false
const withdrawAmount = ref(null) // 总
const receiveMobile = ref(null)
const count = ref(null) // 计数
const showCount = ref(false) // 计数显示
let currentIndex = null // 当前银行卡索引
onLoad(() => {
  uni.showLoading({
    title: $t('jiaZaiZhong')
  })
  // 监听选择银行事件
  uni.$on('page-withdraw-setCurrentIndex', (val) => {
    currentIndex = val
  })
  const ProMobile = new Promise((resolve) => {
    const params = {
      url: '/shop/shopDetail/info',
      method: 'GET'
    }
    http.request(params).then(({ data }) => {
      receiveMobile.value = data.adminMobile?.slice(-4)
      resolve()
    })
  }
  )

  const ProWallet = new Promise((resolve) => {
    const params = {
      url: '/shop/withdrawCash/getShopInfo',
      method: 'GET'
    }
    http.request(params).then(({ data }) => {
      withdrawAmount.value = data.amount
      dataForm.shopName = data.shopName
      resolve()
    })
  })

  const ProBank = new Promise((resolve) => {
    const params = {
      url: '/shop/shopBankCard/getShopBankCardList',
      method: 'GET'
    }
    http.request(params).then(({ data }) => {
      currentIndex = data.findIndex(item => item.isDefault)
      bankList = data
      getBankData(currentIndex)
      resolve()
    })
  })

  Promise.all([ProMobile, ProWallet, ProBank]).then(() => {
    uni.hideLoading()
  })
})

onMounted(() => {
  isFirstSend = true
  if (paySettlementType === 1) {
    getPlatformWithdrawalSetting()
  }
})
onUnload(() => {
  uni.$off('page-withdraw-setCurrentIndex')
})
onShow(() => {
  if (bankList.length !== 0 && currentIndex != null) {
    getBankData(currentIndex)
  }
  uni.setNavigationBarTitle({
    title: $t('yuetiXian')
  })
})

// 获取平台提现设置
let platformWithdrawalSetting = {} // 平台提现设置
const getPlatformWithdrawalSetting = () => {
  http.request({
    url: '/shop/withdrawCash/getWithdrawCash',
    method: 'get'
  }).then(({ data }) => {
    platformWithdrawalSetting = data
  })
}

/**
 * 根据索引得到银行名称、id
 */
const getBankData = (index) => {
  if (index < 0) {
    index = 0
  }
  const bank = bankList[index]
  selectedBank.value = bank
  dataForm.shopBankCardId = bank.shopBankCardId
}

const wxs = number()
// 金额输入处理
const onBlurAmount = () => {
  let val = wxs.checkInput(dataForm.amount)
  if (val < 0.01) {
    val = 0.01
  } else if (val > withdrawAmount.value) {
    val = withdrawAmount.value
  }
  dataForm.amount = +val
}

/**
 * 过滤特殊字符
 */
const handleInput = (value) => {
  nextTick(() => {
    dataForm.shopRemarks = value.detail.value.replace(/[^a-zA-Z0-9(\u4E00-\u9FA5)(，。（）【】{}！,.\-？?!.)]/g, '')
  })
}
const verifyRef = ref(null)
const showCheck = async () => {
  if (isSendCode) {
    return
  }

  if (paySettlementType === 1 && dataForm.amount < platformWithdrawalSetting.withdrawCashLeast) {
    uni.showToast({
      title: $t('tiXianJinebuNengShaoYuWithdrawcashleastYuan').replace('[withdrawCashLeast]', platformWithdrawalSetting.withdrawCashLeast),
      icon: 'none'
    })
    return
  }
  if (paySettlementType === 1 && !selectedBank.value.shopBankCardId) {
    uni.showToast({
      title: $t('qingXianXuanZeYinHangKa'),
      icon: 'none',
      duration: 1000
    })
    return
  }
  if (paySettlementType === 1 && !await getMissingInfo()) {
    return
  }
  verifyRef.value?.show()
}
/**
 * 发送验证码
 */
let timer = null
let isFirstSend = true // 是否首次请求验证码
let bizOrderNo = '' // 通联提现订单号
const sendCode = (verifyResult) => {
  let url = '/shop/shopDetail/sendCode'
  let data = {}
  if (paySettlementType === 1) {
    data = {
      shopBankCardId: selectedBank.value.shopBankCardId,
      bankCardNo: selectedBank.value.bankCardNo,
      amount: dataForm.amount + '' || '0',
      captchaVerification: verifyResult.captchaVerification
    }
    // 首次发送验证码为申请提现，非首次为重新发送验证码
    if (isFirstSend) {
      url = '/shop/withdrawCash/allinpayApply'
    } else {
      data.bizOrderNo = bizOrderNo
      url = '/shop/withdrawCash/resendPaySms'
    }
  }
  data.captchaVerification = verifyResult.captchaVerification
  const params = {
    url,
    method: 'post',
    data: paySettlementType === 1 ? data : { captchaVerification: verifyResult.captchaVerification }
  }
  http.request(params).then(({ data }) => {
    isSendCode = true
    uni.showToast({
      title: $t('faSongChengGong'),
      duration: 2000
    })
    if (isFirstSend) {
      isFirstSend = false
    }
    // 通联支付接口返回的提现订单号，保存提现订单号
    if (paySettlementType === 1) {
      bizOrderNo = data
    }
    const timeCount = 60
    if (!showCount.value) {
      count.value = timeCount
      showCount.value = true
      timer = setInterval(() => {
        if (count.value > 0 && count.value <= timeCount) {
          count.value--
        } else {
          clearInterval(timer)
          isSendCode = false
          showCount.value = false
        }
      }, 1000)
    }
  })
}
const getMissingInfo = () => {
  return new Promise((resolve) => {
    http.request({
      url: '/shop/shopDetail/info',
      method: 'get'
    }).then(({ data }) => {
      const tips = []
      if (selectedBank.value.bankCardPro !== 0 && (data.companyAcctProtocolNo === null || data.companyAcctProtocolNo === '')) {
        tips.push($t('shiFouYiQianYueDuiGongHuTiXianXieYi'))
      }
      if (selectedBank.value.bankCardPro !== 1 && (data.legalAcctProtocolNo === null || data.legalAcctProtocolNo === '')) {
        tips.push($t('shiFouYiQianYueFaRenTiXianXieYi'))
      }
      if (data.isBindPhone !== 1) {
        tips.push($t('shiFouYiBangDingShouJi'))
      }
      if (data.isCreateMember !== 1) {
        tips.push($t('shiFouYiChuangJianDianPuHuiYuan'))
      }
      if (data.companyInfoProcessStatus !== 2) {
        tips.push($t('qiYeXinXiShenHeZhuangTaiShiFouZhengChang'))
      }
      if (data.idCardCollectProcessStatus !== 4) {
        tips.push($t('yingYinJianZhuangTaiShiFouZhengChang'))
      }
      if (tips.length > 0) {
        uni.showToast({
          title: $t('qingQueRenTips').replace('[tips]', tips.join('、')),
          icon: 'none',
          duration: 1500
        })
        resolve(false)
      }
      resolve(true)
    })
  })
}
/**
 * 表单提交
 */
const dataFormSubmit = () => {
  if (!dataForm.amount) {
    // console.log('codeerror')
    uni.showToast({
      title: $t('yuebuWeiKong'),
      duration: 2000,
      icon: 'none'
    })
    return
  }
  if (paySettlementType === 1 && dataForm.amount < platformWithdrawalSetting.withdrawCashLeast) {
    uni.showToast({
      title: $t('tiXianJinebuNengShaoYuWithdrawcashleastYuan').replace('[withdrawCashLeast]', platformWithdrawalSetting.withdrawCashLeast),
      icon: 'none'
    })
    return
  }
  if (dataForm.amount < 1 && paySettlementType !== 1) {
    uni.showToast({
      title: $t('tiXianJinebuNengShaoYu_100Yuan'),
      duration: 2000,
      icon: 'none'
    })
    return
  }
  if (!dataForm.code || (paySettlementType === 1 && !bizOrderNo)) {
    uni.showToast({
      title: $t('yanZhengMaBuWeiKong'),
      duration: 2000,
      icon: 'none'
    })
    return
  }
  let data = {}
  let url = '/shop/withdrawCash/apply'
  if (paySettlementType === 1) {
    url = '/shop/withdrawCash/confirmWithdrawPay'
    data = {
      bankCardNo: selectedBank.value.bankCardNo,
      amount: (dataForm.amount + '') || '0',
      bizOrderNo,
      verificationCode: dataForm.code
    }
  }
  const params = {
    url,
    method: 'post',
    data: paySettlementType === 1 ? data : dataForm
  }
  http.request(params).then((res) => {
    if (res.code === '00000') {
      uni.navigateBack({
        delta: 1
      })
    } else {
      uni.showToast({
        title: res.msg,
        icon: 'none'
      })
    }
  })
}
/**
 * 选择银行卡
 */
const chooseBank = () => {
  uni.navigateTo({ url: '/pages/bank-select/bank-select?currentIndex=' + currentIndex })
}

</script>

<style lang="scss" scoped>
@import './withdraw.scss';
</style>
