<route lang="json5" type="page">
{
  layout: 'default',
  style: {
    navigationStyle: 'custom',
    navigationBarTitleText: '%wallet.withdraw.title%',
  },
}
</route>

<script lang="ts" setup>
import { getConfigByCode } from '@/api/common'
import { withdrawAdd } from '@/api/wallet'
import { t } from '@/locale'
import { useUserStore } from '@/store'
import { formatNumber } from '@/utils'
import { goBack, toPage } from '@/utils/page'
import { toast } from '@/utils/toast'

defineOptions({
  name: 'Withdraw', // 提现
})

const userStore = useUserStore()
const userInfo = computed(() => getUserInfoHook())
const queryParams = ref<any>({})
// 表单数据
const formData = ref({
  amount: '',
  bank: userInfo.value.bank,
  bankAccountName: userInfo.value.bankAccountName,
  bankAccount: userInfo.value.bankAccount,
  currency: 'BDT',
})

const bankColumns = [
  { label: 'BKASH', value: 'BKASH' },
  { label: 'NAGAD', value: 'NAGAD' },
  { label: 'ROCKET', value: 'ROCKET' },
]

// 提现限制（从配置中获取）
const withdrawMinAmount = ref<number>(300)
const withdrawMaxAmount = ref<number>(20000)

const loading = ref<boolean>(false)
async function submit() {
  if (!formData.value.bank) {
    toast.info(t('wallet.withdraw.error.bankName'))
    return
  }
  if (!formData.value.bankAccountName) {
    toast.info(t('wallet.withdraw.error.bankAccountName'))
    return
  }
  if (!formData.value.bankAccount) {
    toast.info(t('wallet.withdraw.error.bankAccountNo'))
    return
  }
  if (!formData.value.amount) {
    toast.info(t('wallet.withdraw.error.amount'))
    return
  }

  // 校验金额是否为有效数字
  const amount = Number(formData.value.amount)
  if (Number.isNaN(amount)) {
    toast.info(t('wallet.withdraw.error.amount'))
    return
  }

  // 校验金额范围
  if (amount < withdrawMinAmount.value) {
    toast.info(t('wallet.withdraw.notes.4', [formatNumber(withdrawMinAmount.value), formatNumber(withdrawMaxAmount.value)]))
    return
  }

  if (amount > withdrawMaxAmount.value) {
    toast.info(t('wallet.withdraw.notes.4', [formatNumber(withdrawMinAmount.value), formatNumber(withdrawMaxAmount.value)]))
    return
  }

  // 校验余额是否充足
  const balance = Number(queryParams.value.balance)
  if (amount > balance) {
    toast.info(t('wallet.withdraw.error.amount'))
    return
  }

  loading.value = true
  try {
    const res = await withdrawAdd({ ...formData.value, accountType: queryParams.value.type, channel: formData.value.bank })
    console.log(res)
    if (res.code === '200') {
      userStore.getUserInfo()
      toast.success(t('wallet.withdraw.success'))
      setTimeout(() => {
        goBack()
      }, 1500)
    }
    else {
      toast.error(res.message || t('wallet.withdraw.fail'))
    }
  }
  finally {
    loading.value = false
  }
}
const withdrawRate = ref<any>()
async function getConfig() {
  try {
    // 获取提现费率
    const rateRes = await getConfigByCode({ code: queryParams.value.type === '2' ? 'earning_withdraw_rate' : 'withdraw_rate' })
    withdrawRate.value = rateRes.data.valueInfo

    // 获取最小提现金额
    const minRes = await getConfigByCode({ code: 'min_withdraw_amount' })
    if (minRes.code === '200' && minRes.data.valueInfo) {
      withdrawMinAmount.value = Number(minRes.data.valueInfo)
    }

    // 获取最大提现金额
    const maxRes = await getConfigByCode({ code: 'max_withdraw_amount' })
    if (maxRes.code === '200' && maxRes.data.valueInfo) {
      withdrawMaxAmount.value = Number(maxRes.data.valueInfo)
    }
  }
  catch {

  }
}

// 计算服务费
const serviceFee = computed(() => {
  const amount = Number(formData.value.amount)
  if (!amount || Number.isNaN(amount) || !withdrawRate.value) {
    return '0.00'
  }
  const rate = Number(withdrawRate.value)
  return formatNumber(amount * (rate / 100))
})

onLoad((options) => {
  queryParams.value = options
  getConfig()
})
</script>

<template>
  <view class="min-h-100vh flex flex-col bg-#FEE750">
    <wd-navbar
      custom-class="bg-#FEE750!"
      :bordered="false"
      safe-area-inset-top placeholder fixed
      :title="t('wallet.withdraw.title')"
    >
      <template #left>
        <wd-icon name="thin-arrow-left" size="32rpx" @click="() => goBack()" />
      </template>
      <template #right>
        <text class="text-28rpx" @click="toPage({ url: '/pages/wallet/withdrawRecord', params: { type: queryParams.type } })">
          {{ $t('wallet.withdraw.record') }}
        </text>
      </template>
    </wd-navbar>
    <view class="px-28rpx pb-28rpx pt-40rpx">
      <view class="text-28rpx">
        {{ $t(queryParams.type === '2' ? 'wallet.withdraw.balanceRevenue' : 'wallet.withdraw.balanceWallet') }}
      </view>
      <view>
        <text class="text-28rpx">
          ৳
        </text>
        <text class="text-48rpx font-bold">
          {{ formatNumber(queryParams.balance) }}
        </text>
      </view>
    </view>
    <view class="flex-1 rounded-t-24rpx bg-white p-24rpx">
      <view class="mb-28rpx text-32rpx">
        {{ $t('wallet.withdraw.info') }}
      </view>
      <wd-form ref="form" :model="formData" custom-class="mb-28rpx">
        <view class="mb-40rpx space-y-32rpx">
          <wd-picker v-model="formData.bank" :disabled="Boolean(userInfo.bank)" :columns="bankColumns" use-default-slot>
            <wd-input
              v-model="formData.bank"
              :placeholder="t('wallet.withdraw.form.bankName')"
              no-border
              readonly
              custom-class="bandhu-auth-input-field"
              :disabled="Boolean(userInfo.bank)"
            />
          </wd-picker>

          <wd-input
            v-model="formData.bankAccountName"
            :placeholder="t('wallet.withdraw.form.bankAccountName')"
            no-border
            custom-class="bandhu-auth-input-field"
            :disabled="Boolean(userInfo.bankAccountName)"
          />
          <wd-input
            v-model="formData.bankAccount"
            :placeholder="t('wallet.withdraw.form.bankAccountNo')"
            no-border
            custom-class="bandhu-auth-input-field"
            :disabled="Boolean(userInfo.bankAccountName)"
          />
          <view class="flex items-center gap-20rpx">
            <wd-input
              v-model="formData.amount"
              :placeholder="t('wallet.withdraw.form.amount')"
              no-border
              custom-class="flex-1 bandhu-auth-input-field"
              type="digit"
            />
            <wd-button
              type="error"
              plain
              custom-class="bandhu-auth-secondary-btn"
              @click="formData.amount = queryParams.balance"
            >
              {{ $t('wallet.withdraw.form.allAmount') }}
            </wd-button>
          </view>
          <view class="text-24rpx">
            Service Fee：৳{{ serviceFee }}
          </view>
        </view>
        <wd-button plain block custom-class="h-80rpx!" :loading="loading" @click="submit">
          {{ $t('wallet.withdraw.form.submit') }}
        </wd-button>
      </wd-form>
      <view class="text-24rpx text-#5A5A5A line-height-48rpx">
        {{ $t('wallet.withdraw.notes.title') }}
        <br>
        {{ $t('wallet.withdraw.notes.1') }}
        <br>
        {{ $t('wallet.withdraw.notes.2') }}
        <br>
        {{ $t('wallet.withdraw.notes.3') }}
        <br>
        {{ t('wallet.withdraw.notes.4', [formatNumber(withdrawMinAmount), formatNumber(withdrawMaxAmount)]) }}
        <br>
        {{ t('wallet.withdraw.notes.5', [withdrawRate]) }}
      </view>
    </view>
  </view>
</template>

<style lang="scss" scoped>
//
</style>
