<route lang="json5" type="page">
{
  layout: 'default',
  needLogin: true,
  style: {
    navigationBarTitleText: '%wallet.recharge.title%',
    navigationBarBackgroundColor: '#fff',
    "app-plus": {
      "titleNView": {
        "buttons": [
          {
            "text": "%wallet.recharge.record%",
            "fontSize": "28rpx",
            "width": "85px"
          }
        ]
      }
    }
  },
}
</route>

<script lang="ts" setup>
import { paymentMethod, rechargeAdd, rechargeGoodsList } from '@/api/wallet'
import { t } from '@/locale'
import { formatNumber } from '@/utils'
import { toPage } from '@/utils/page'
import { toast } from '@/utils/toast'

defineOptions({
  name: 'Recharge', // 充值
})

const orderPrice = ref(0) // 商品订单金额

const selectData = ref<any>({
  methodId: '',
  id: '',
  amount: '',
  customAmount: '',
})
const methodIconMap = {
  BKASH: '/static/icons/bkash.png',
  NAGAD: '/static/icons/nagad.png',
  ROCKET: '/static/icons/rocket.png',
}
// 触发确定按钮
onNavigationBarButtonTap((event: any) => {
  if (event.text === t('wallet.recharge.record')) {
    toPage({ url: '/pages/wallet/rechargeRecord' })
  }
})
const methodList = ref<any[]>([])

async function getMethodList() {
  const res = await paymentMethod()
  methodList.value = res.data
  await getRechargeGoodsList()
}

const dataList = ref<any[]>([])
const interval = ref<any>({
  maxPrice: 0,
  miniPrice: 0,
})
async function getRechargeGoodsList(id?: string) {
  selectData.value.methodId = id || methodList.value[0].id
  const res = await rechargeGoodsList({ id: selectData.value.methodId })
  if (res.code === '200') {
    dataList.value = res.data.list
    interval.value = {
      maxPrice: res.data.maxPrice,
      miniPrice: orderPrice.value || res.data.miniPrice,
    }
  }
}

function handleSelectAmount(item: any) {
  selectData.value.id = item.id
  selectData.value.amount = item.amount
  selectData.value.customAmount = ''
}

function focusAmount() {
  selectData.value.id = ''
  selectData.value.amount = ''
}

const loading = ref<boolean>(false)

async function submit() {
  const amount = Number(selectData.value.customAmount || selectData.value.amount)
  if (!amount) {
    toast.info(t('wallet.recharge.enterAmount'))
    return
  }
  if (amount < interval.value.miniPrice) {
    toast.info(t('wallet.recharge.minAmount', { minAmount: interval.value.miniPrice }))
    return
  }
  if (amount > interval.value.maxPrice) {
    toast.info(t('wallet.recharge.maxAmount', { maxAmount: interval.value.maxPrice }))
    return
  }

  loading.value = true
  try {
    const addRes = await rechargeAdd({ amount, methodId: selectData.value.methodId })
    if (addRes.code === '200') {
      toPage({ url: '/pages/webLink/webLink', params: { link: addRes.data.payUrl, title: t('orderDetail.payDialog.title') }, isRedirect: true })
    }
  }
  finally {
    loading.value = false
  }
}

onShow(() => {
  getMethodList()
})
onLoad((options) => {
  orderPrice.value = options.price || 0
})

// 监听自定义金额变化
watch(() => selectData.value.customAmount, (newVal) => {
  if (!newVal)
    return

  // 移除非数字字符
  const numericValue = newVal.toString().replace(/\D/g, '')
  if (numericValue !== newVal) {
    selectData.value.customAmount = numericValue
    return
  }

  const amount = Number(numericValue)
  if (amount > interval.value.maxPrice) {
    selectData.value.customAmount = interval.value.maxPrice.toString()
    toast.info(t('wallet.recharge.maxAmount', { maxAmount: interval.value.maxPrice }))
  }
})
</script>

<template>
  <z-paging>
    <view class="px-24rpx pt-36rpx">
      <view class="mb-24rpx text-24rpx font-bold">
        {{ $t('wallet.recharge.selectProvider') }}
      </view>
      <view class="grid grid-cols-3 mb-30rpx gap-20rpx">
        <view
          v-for="item in methodList" :key="item.id"
          :style="{
            borderColor: item.id === selectData.methodId ? 'var(--wot-color-theme)' : '',
          }"
          class="border-1 border-transparent rounded-16rpx border-solid bg-white py-30rpx text-center shadow-[0rpx_2rpx_8rpx_0rpx_rgba(184,184,184,0.5)]"
          @click="getRechargeGoodsList(item.id)"
        >
          <image
            :src="methodIconMap[item.methodName]"
            class="mb-20rpx h-120rpx w-120rpx"
          />
          <view class="text-28rpx">
            {{ item.methodName }}
          </view>
        </view>
      </view>
      <view class="mb-24rpx text-24rpx font-bold">
        {{ $t('wallet.recharge.depositAmount') }}
      </view>
      <view class="grid grid-cols-3 mb-20rpx gap-20rpx">
        <view
          v-for="i in dataList"
          :key="i.id"
          class="amount-item border-1 border-transparent rounded-12rpx border-solid bg-white py-22rpx text-center"
          :class="{ disabled: orderPrice && i.amount < orderPrice }"
          :style="{
            borderColor: i.id === selectData.id ? 'var(--wot-color-theme)' : '',
          }"
          @click="!orderPrice || i.amount >= orderPrice ? handleSelectAmount(i) : null"
        >
          <view>
            <text class="text-24rpx">
              ৳
            </text>
            <text class="text-36rpx">
              {{ formatNumber(i.amount) }}
            </text>
          </view>
        </view>
      </view>
      <wd-input
        v-model="selectData.customAmount"
        no-border
        :placeholder="`${t('wallet.recharge.minAmount', { minAmount: formatNumber(interval.miniPrice) })} ~ ${t('wallet.recharge.maxAmount', { maxAmount: formatNumber(interval.maxPrice) })}`"
        custom-class="bandhu-auth-input-field"
        @focus="focusAmount"
      />
    </view>

    <template #bottom>
      <view class="mb-20rpx px-24rpx text-24rpx text-#5A5A5A">
        {{ $t('wallet.recharge.reminder') }}
      </view>
      <view class="bg-white/60 px-28rpx py-30rpx backdrop-blur-20">
        <wd-button block :disabled="!selectData.amount && !selectData.customAmount" :loading="loading" @click="submit">
          {{ $t('wallet.recharge.submit') }}
        </wd-button>
      </view>
    </template>
  </z-paging>
</template>

<style lang="scss" scoped>
.amount-item {
  box-shadow: 0rpx 2rpx 8rpx 0rpx rgba(184, 184, 184, 0.5);
  &.disabled {
    cursor: not-allowed;
    background-color: rgba(184, 184, 184, 0.5);
  }
}
</style>
