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

 https://www.mall4j.com/

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

 版权所有，侵权必究！
-->
<template>
  <el-dialog
    v-model="isCaswithdrawal"
    :title="$t('shop.withdraw')"
    width="750px"
    class="Mallj4 withdrawal-dialog"
    :close-on-click-modal="false"
    top="8vh"
  >
    <el-form
      ref="dataFormRef"
      :model="dataForm"
      :rules="dataRule"
      label-width="120px"
      @submit.prevent
    >
      <el-form-item
        :label="$t('shop.storeName')+'：'"
        prop="supplierName"
      >
        <span class="shop-name">{{ dataForm.supplierName }}</span>
      </el-form-item>

      <el-form-item
        :label="$t('shop.withdraBala')+'：'"
        prop="withdrawalAmount"
      >
        <span class="withdrawalAmount">{{ settledAmount + $t('shop.yuan') }}</span>
      </el-form-item>

      <el-form-item
        :label="$t('shop.withdr')+'：'"
        prop="amount"
      >
        <div class="withdrawal-int">
          <el-input
            v-model="dataForm.amount"
            type="number"
            :min="0"
            :max="settledAmount"
            :placeholder="$t('shop.pleEnWithAmo')"
            @change="handleInput"
          />
          <el-button
            v-if="(paySettlementType!==1 && settledAmount >= 1) || (paySettlementType===1 && settledAmount > Number(platformWithdrawalSetting.withdrawCashLeast))"
            link
            type="primary"
            style="margin-left: 10px"
            @click="allWithdrawals"
          >
            {{ $t('shop.withdrawAll') }}
          </el-button>
        </div>
      </el-form-item>

      <el-form-item
        :label="$t('shop.debitCard')+'：'"
        prop="supplierBankCardId"
      >
        <div
          v-if="bankCardList.length"
          class="bankcard-box"
        >
          <div
            v-for="(item,index) in bankCardList"
            :key="index"
            :class="['bankcard',dataForm.supplierBankCardId == item.supplierBankCardId?'active':'']"
            @click="clickCard(item.supplierBankCardId)"
          >
            <div
              class="close-icon"
              @click="deleteBankCartById(item.cardNo, item.supplierBankCardId)"
            >
              ×
            </div>
            <div class="card-num">
              {{ item.cardNo }}
            </div>
            <div class="card-bottom">
              <div class="card-name">
                {{ item.bankName }}
              </div>
              <div
                v-if="item.isDefault"
                class="default"
              >
                {{ $t('shop.defaultBankCard') }}
              </div>
              <div
                v-if="!item.isDefault"
                class="chooseDefault"
              >
                <el-button
                  link
                  type="primary"
                  @click="setDefault(item.supplierBankCardId)"
                >
                  {{ $t('shop.setAsDefault') }}
                </el-button>
              </div>
            </div>
          </div>
        </div>
        <div
          v-if="bankCardList.length < 5"
          class="add-card"
        >
          <el-button
            link
            type="primary"
            @click="addBankCard"
          >
            {{ $t('shop.addBankCard') }}
          </el-button>
        </div>
      </el-form-item>

      <el-form-item
        :label="$t('shop.smsVerification')+'：'"
        prop="validCode"
      >
        <div class="withdrawal-int">
          <el-input
            v-model="dataForm.validCode"
          />
          <el-button
            type="primary"
            style="margin-left: 30px;"
            :loading="!!countdown"
            :disabled="!!countdown"
            @click="getVerificationCode"
          >
            {{ countdown? countdown:$t('shop.getVerificationCode') }}
          </el-button>
        </div>
      </el-form-item>
      <div
        v-if="isSendCode"
        class="yzm-tips"
      >
        {{ $t('shop.codeSupplier') }}：{{ mobile }}，{{ $t('shop.pleaseCheck') }}
      </div>
      <br>

      <el-form-item
        :label="$t('shop.remarks')+'：'"
        prop="supplierRemarks"
      >
        <el-input
          v-model="dataForm.supplierRemarks"
          type="textarea"
          :rows="4"
          :placeholder="$t('shop.remarksMaxTips')"
          maxlength="60"
          oninput="value=value.replace(/[^\a-\z\A-\Z0-9\u4E00-\u9FA5.]/g, '')"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button
          plain
          @click="isCaswithdrawal = false"
        >{{ $t('table.cancel') }}</el-button>
        <el-button
          type="primary"
          @click="submitData"
        >{{ $t('table.confirm') }}</el-button>
      </span>
    </template>

    <addBankCardPop
      v-if="showAddCardPop"
      ref="addBankCardPopRef"
      :card-number="cardNumber"
      :legal-card-number="legalCardNumber"
      @refresh-data-list="getList"
    />
  </el-dialog>
</template>

<script setup>
import addBankCardPop from '../../setting/components/add-or-update/index.vue'
import { deleteBankCart } from '@/api/multishop/shop-process'
import { getWithdrawalSetting } from '@/api/rbac/web-config'
import { validNoEmptySpace } from '@/utils/validate'
import { getBankCardList, setPrimary, sendWithdrawCode, shopWithdrawCash, withdrawCashApply, withdrawCashSendCode, withdrawCashConfirmPay } from '@/api/multishop/shop_wallet_log'
import { Debounce } from '@/utils/debounce'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useAllinpayStore } from '@/stores/modules/allinpay.js'
import Big from 'big.js'

const emit = defineEmits('getShopWallet')

const paySettlementType = reactive(useAllinpayStore.paySettlementType)
const showAddCardPop = ref(false) // 添加银行卡弹框
const isCaswithdrawal = ref(true)
const dataForm = reactive({
  supplierName: '',
  supplierBankCardId: '', // 当前选择的银行卡id
  amount: 0, // 提现金额
  validCode: '', // 验证码
  supplierRemarks: '' // 备注
})
const mobile = ref('')
const settledAmount = ref(0) // 全部可提现余额
const isSendCode = ref(false)
const dataFormRef = ref(null)
// eslint-disable-next-line no-unused-vars
const valiShopRemarks = reactive((rule, value, callback) => {
  if (value === null || value === '') {
    dataFormRef.value?.clearValidate('supplierRemarks')
    callback()
  } else if (validNoEmptySpace(value)) {
    callback(new Error($t('shop.allEmpty')))
  } else {
    callback()
  }
})
const bankCardList = ref([]) // 银行卡列表
const currentCard = reactive({}) // 当前银行卡
const countdown = ref(0)
const legalCardNumber = ref(0) // 法人账户数量
const cardNumber = ref(0) // 非法人账户数量
const bizOrderNo = ref('') // 提现订单号
const platformWithdrawalSetting = reactive({}) // 平台提现设置

const dataRule = computed(() => {
  return {
    amount: [
      { required: true, message: $t('shop.amountEmpty'), trigger: 'blur' }
    ],
    settledAmount: [
      { required: true, message: $t('shop.withdrawaEmpty'), trigger: 'blur' }
    ],
    validCode: [
      { required: true, message: $t('shop.pleaseEnteCode'), trigger: 'blur' }
    ],
    supplierBankCardId: [
      { required: true, message: $t('shop.pleSelTheBankCard'), trigger: 'blur' }
    ],
    supplierRemarks: [
      { validator: valiShopRemarks, trigger: 'blur' }
    ]
  }
}
)
onMounted(() => {
  dataForm.supplierName = useUserStore().name
})

const init = (_settledAmount) => {
  if (dataFormRef.value != null) {
    dataFormRef.value.resetFields() // 每次打开都清空表单
  }
  isCaswithdrawal.value = true
  settledAmount.value = new Big(_settledAmount).div(100).valueOf()

  if (paySettlementType === 1) {
    getPlatformWithdrawalSetting()
  }
  getList()
}
defineExpose({ init })
// 点击添加银行卡
const addBankCardPopRef = ref('')
const addBankCard = () => {
  showAddCardPop.value = true
  nextTick(() => {
    addBankCardPopRef.value?.init()
  })
}
// 获取银行卡列表
const getList = () => {
  getBankCardList().then(res => {
    res.sort(function (a, b) {
      return b.isDefault - a.isDefault
    })
    bankCardList.value = res
    bankCardList.value.forEach(item => {
      if (item.isDefault) {
        dataForm.supplierBankCardId = item.supplierBankCardId
      }
    })
    if (paySettlementType === 1) {
      legalCardNumber.value = res.filter(item => item.bankCardPro === 0).length
      cardNumber.value = res.length - legalCardNumber
    }
  })
}
// 设置默认银行卡
const setDefault = (id) => {
  setPrimary(id).then(() => [
    getList()
  ])
}
// 选择银行卡
const clickCard = (cardId) => {
  bankCardList.value.forEach(element => {
    if (element.supplierBankCardId === cardId) {
      currentCard.value = element
    }
  })
  dataForm.supplierBankCardId = cardId
}

/**
 * 校验
 */
const handleValidate = async () => {
  if (!settledAmount.value) {
    ElMessage({
      message: $t('shop.settledAmountTips'),
      type: 'error',
      duration: 1000
    })
    return false
  }
  if (!dataForm.amount) {
    ElMessage({
      message: $t('shop.amountEmpty') + '！',
      type: 'error',
      duration: 1000
    })
    return false
  }
  // dataForm.amount > settledAmount.value
  if (new Big(dataForm.amount).gt(new Big(settledAmount.value))) {
    ElMessage({
      message: $t('shop.amountMoreSettledAmount'),
      type: 'error',
      duration: 1000
    })
    return false
  }
  // 暂时禁用，后台未合并代码
  /* const checkPriceRes = await checkPrice()
  if (!checkPriceRes) {
    return false
  } */
  if (!bankCardList.value.length) {
    ElMessage({
      message: $t('shop.addABank'),
      type: 'error',
      duration: 1000
    })
    return false
  }
  return true
}
// 校验提现金额
// const checkPrice = () => {
//   return new Promise((resolve) => {
//     const amount = new Big(dataForm.amount).times(100).valueOf()
//     checkDrawCashAmount(amount).then(data => {
//       resolve(data)
//     }).catch(() => {
//       resolve(false)
//     })
//   })
// }

// 获取验证码
const getVerificationCode = async () => {
  if (!(await handleValidate())) {
    return
  }
  let request = ''
  if (paySettlementType === 1) {
    // 通联支付获取验证码并存储订单号
    const data = {
      bankCardNo: currentCard.cardNo,
      amount: dataForm.amount * 100,
      bizOrderNo
    }
    // 首次发送验证码为申请提现，非首次为重新发送验证码
    if (!isSendCode) {
      request = withdrawCashApply(data)
    } else {
      request = withdrawCashSendCode(data)
    }
    return
  } else {
    request = sendWithdrawCode()
  }
  request.then(data => {
    countdown.value = 60
    // 非通联支付获取验证码返回手机号
    if (paySettlementType !== 1) {
      mobile.value = data
    }
    // 通联支付获取验证码返回订单号
    if (paySettlementType === 1) {
      bizOrderNo.value = data.bizOrderNo
    }
    isSendCode.value = true
    getCountdown()
  })
}
// 倒计时1分钟

const getCountdown = () => {
  const timer = setInterval(() => {
    countdown.value--
    if (countdown.value === 0) {
      clearInterval(timer)
    }
  }, 1000)
}
// 全部提现
const allWithdrawals = () => {
  dataForm.amount = settledAmount.value
}
// 输入事件
const handleInput = () => {
  if (Number(dataForm.amount) > Number(settledAmount.value)) {
    dataForm.amount = settledAmount.value
  }
  // const str = /^[0-9]+(.[0-9])?$/
  const str = /^(([1-9]{1}\d*)|(0{1}))(\.\d{1,2})?$/
  if (!str.test(dataForm.amount) || dataForm.amount > 999999) {
    dataForm.amount = ''
  }
}

// 删除银行卡
const deleteBankCartById = (cardNo, supplierBankCardId) => {
  const tailNumber = cardNo.substring(cardNo.length - 4)
  ElMessageBox.confirm(`${$t('multishop.shopInformation.delBrankBefore') + tailNumber + $t('multishop.shopInformation.delBrankAfter')}?`, $t('table.tips'), {
    confirmButtonText: $t('table.confirm'),
    cancelButtonText: $t('table.cancel'),
    type: 'warning'
  }).then(() => {
    deleteBankCart(supplierBankCardId).then(() => {
      ElMessage({
        message: $t('table.delSuccess'),
        type: 'success',
        duration: 1000
      })
      getList()
    })
  }).catch(() => {})
}

/**
 *  提交提现申请 Debounce:防抖函数
 */
const submitData = Debounce(() => {
  dataFormRef.value?.validate(async valid => {
    if (valid) {
      if (!(await handleValidate())) {
        return
      }
      let data = null
      let request = null
      if (paySettlementType === 1) {
        data = {
          bankCardNo: currentCard.cardNo,
          amount: new Big(dataForm.amount).times(100).valueOf(),
          bizOrderNo,
          verificationCode: dataForm.validCode
        }
        request = withdrawCashConfirmPay(data)
      } else {
        data = JSON.parse(JSON.stringify(dataForm))
        data.amount = new Big(data.amount).times(100).valueOf()
        request = shopWithdrawCash(data)
      }
      request.then(() => {
        ElMessage({
          message: $t('table.actionSuccess'),
          type: 'success',
          duration: 1000,
          onClose: () => {
            isCaswithdrawal.value = false
            dataForm.value = {
              supplierName: '',
              supplierBankCardId: '',
              amount: 0,
              validCode: null,
              supplierRemarks: ''
            }
            emit('getShopWallet')
          }
        })
      })
    }
  })
}, 1500)

// 获取平台提现设置
const getPlatformWithdrawalSetting = () => {
  getWithdrawalSetting().then(data => {
    platformWithdrawalSetting.value = data
    platformWithdrawalSetting.withdrawCashLeast = new Big(data.withdrawCashLeast).div(100).toFixed(2).valueOf()
  })
}

</script>

<style lang="scss" scoped>
:deep(.el-form-item__content){
  display:block;
}
.withdrawal-dialog :deep(.el-dialog) {
  min-width: 700px;
}
.shop-name {
  font-size: 15px;
}
:deep(.el-input .el-input--suffix input.el-input__inner) {
  height: 30px !important;
  line-height: 30px !important;
}
:deep(.el-textarea__inner) {
  width: 60%;
  min-width: 277px;
}
:deep(.el-input ){
  width: 35%;
  min-width: 277px;
}

.withdrawal-int{
  width: 100%;
  display: flex;
  align-items: center;

  :deep(.el-input) {
    width: 290px;
  }
}
.withdrawal-int :deep(.el-input__inner) {
  padding-right: 0;
}
.yzm-tips {
  display: block;
  color: #aaa;
  margin-left: 120px;
  line-height: 2em;
  margin-bottom: 10px;
}

.add-card {
  display: block;

  line-height: 1em;
}
:deep(.el-dialog__header) {
  padding-bottom: 0 !important;
}
:deep(.el-dialog__body) {
  padding: 10px 20px !important;
}
/* 银行卡 */
.bankcard {
  position: relative;
  display: inline-block;
  width: 270px;
  height: 90px;
  border: 1px solid #eee;
  padding: 10px;
  margin-right: 20px;
  cursor: pointer;
  margin-top: 10px;
  border-radius: 5px;
  background: #fff;
}
.bankcard:hover {
  box-shadow: 0 2px 8px rgb(200 201 204 / 50%);
}
.close-icon {
  display: block;
  position: absolute;
  top: 8px;
  right: 8px;
  width: 15px;
  height: 15px;
  line-height: 15px;
  text-align: center;
  font-size: 16px;
  color: #999;
  cursor: pointer;
  z-index: 11;
}
.close-icon:hover {
  color: #155BD4;
}
.card-num {
  font-size: 15px;
  line-height: 1.5em;
  color: #333;
  text-align: left;
  margin-bottom: 30px;
  width: 210px;
}
.card-name {
  width: 150px;
}
.card-bottom {
  position: absolute;
  bottom: 10px;
  font-size: 14px;
  display: flex;
  align-items: center;
  width: 90%;
  justify-content: space-between;
  line-height: 1.5em;
}
.chooseDefault :deep(.el-button--medium) {
  padding: 0;
}
.default {
  color: #999;
  cursor: auto;
}
.active {
  border: 1px solid #57A9FB;
  background: #f5f9ff;
}
.bankcard-box{
  display: flex;
  flex-wrap: wrap;
  margin-bottom: 10px;
}
</style>
