<template>
    <van-nav-bar :title="t('withdrawal.title')">
        <template #left>
            <SvgIcon name="allow-left" class="w-7 h-7" @click="router.back" />
        </template>
    </van-nav-bar>
    <section class="max-w-xl m-auto min-h-[calc(100vh-46px)]">
        <div class="bg-white">
            <div class="flex flex-row items-center justify-between p-4">
                <div class="text-[#3A3A3CFF] text-base ml-2">{{ t('withdrawal.title') }}</div>
                <div class="text-base font-bold mr-2">{{ channelConfig.channelName }}</div>
            </div>
            <div class="h-[1px] bg-[#D9D9D9FF]"></div>
            <div class="px-4 py-7">
                <div class="flex flex-col">
                    <span class="text-[##9CADBF]">{{ t('withdrawal.c_b') }}</span>
                    <span class="text-black text-base font-bold mt-2">USDT {{ balance }}</span>
                </div>
            </div>
            <div class="bg-[#F4F6F7FF] p-4">{{ t('withdrawal.s_w_a') }}</div>
            <div class="grid grid-cols-3 gap-4 mx-4 mt-4">
                <div class="w-[105px] h-16  flex flex-row items-center justify-center rounded-lg"
                    v-for="(item, index) in amountList" @click="onActive(item, index)"
                    :class="[active === index ? 'bg-[#F96825] shadow-sm' : 'bg-[#1D1F241A]']">
                    <span class="font-semibold" :class="[active === index ? 'text-white' : 'text-[#1D1F24D9]']">USDT {{ item
                    }}</span>
                </div>
            </div>
            <!-- input -->
            <div class="mx-4 mt-7 pb-4">
                <div class="relative mt-2 rounded-md shadow-sm">
                    <div class="pointer-events-none absolute inset-y-0 left-0 flex items-center pl-3 font-semibold">
                        USDT
                    </div>
                    <input type="number" name="amount" id="amount" class="block w-full rounded-md border-0 py-1.5 pl-20 
                    ring-1 ring-inset ring-gray-300 placeholder:text-gray-400  placeholder:text-md
                    focus:ring-2 focus:ring-inset focus:ring-[#F96825] sm:text-sm sm:leading-6 font-semibold
                    h-14 text-[#F96825]" v-model="inputAmount" placeholder="select or type here"
                        @input="formatAmount" />
                </div>
            </div>
            <div class="bg-[#F4F6F7FF] p-4">{{ t('withdrawal.w_a') }}</div>
            <div class="mt-8 mx-4 pb-4">
                <span class="text-base font-bold text-black">{{ channelConfig.channelName }} Wallet Address</span>
                <div class="mt-4 mb-4 bg-[#EAF4FFFF] rounded-md flex items-center justify-center">
                    <span class="text-[#9CADBFFF] text-sm text-center p-3">{{ bindInfo.address }}</span>
                </div>
                <div class="flex items-start justify-start mt-4 mb-10" @click="modifyAddress">
                    <span class="text-[#F96825]">{{ t('withdrawal.m_w_a') }}</span>
                </div>
                <van-button block color="linear-gradient(90deg, #F70 0%, #FF4900 100%)" class="font-semibold btn"
                    @click="handleWithdraw" :disabled="disabled">{{ t('common.confirm') }}</van-button>
            </div>
            <div class="h-4 bg-[#F4F6F7FF] "></div>
        </div>
    </section>
    <Dialog ref="dialogRef" @Confirm="modifyAddress" />
    <Dialog ref="dialogRef2" />
    <van-dialog v-model:show="showInput" width="90%" :showConfirmButton="false" :showCancelButton="false"
        :closeOnClickOverlay="true">
        <div class="p-4">
            <div class="flex items-end justify-end">
                <SvgIcon name="close" class="w-7 h-7" @click="showInput = false" />
            </div>
            <div class="flex flex-row items-center justify-between">
                <span>{{ t('withdrawal.w_p') }}</span>
            </div>
            <form>
                <input type="password" name="password" id="password" class="block w-full rounded-md border-0 py-1.5  text-gray-900 ring-1 ring-inset
                     ring-gray-300 placeholder:text-gray-400 focus:ring-2 focus:ring-inset 
                     focus:ring-[#F96825] sm:text-sm sm:leading-6 h-12 mt-4" :placeholder="t('withdrawal.enterPassword')"
                v-model="password" :max="10" />
            </form>
            <div class="mt-8">
                <van-button block color="linear-gradient(90deg, #F70 0%, #FF4900 100%)" @click="confirmWithdraw">
                    <template #default>
                        <div class="flex flex-row items-center justify-center">
                            <SvgIcon name="keys" class="w-7 h-7 mr-2" />
                            <span class="font-semibold text-base">{{ t('common.confirm') }}</span>
                        </div>
                    </template>
                </van-button>
            </div>
        </div>
    </van-dialog>
    <Success ref="successRef" />
    <PaymentPassword ref="paymentPasswordRef" @success="setPasswordSuccess"/>
</template>

<script setup lang="ts">
import { useRouter, useRoute } from 'vue-router'
import SvgIcon from '@/components/SvgIcon.vue';
import { ref } from 'vue';
import { onMounted } from 'vue';
import { getChannelConfigById } from '@/api/channelConfig'
import { getBalanceAccount, getQuickRechargeAmount } from '@/api/balance'
import { checkBind, createWithdrawal } from '@/api/withdrawal'
import Success from '@/components/Success.vue';
import PaymentPassword from './components/PaymentPassword.vue'
import { useI18n } from 'vue-i18n';
const { t } = useI18n()


const router = useRouter()
const route = useRoute()
const configId = ref()
const channelConfig = ref({})
const active = ref()
const amountList = ref([])
const inputAmount = ref()
const balance = ref(0)
const disabled = ref(false)
const dialogRef = ref()
const dialogRef2 = ref()
const paymentPasswordRef = ref()
const showInput = ref(false)
const successRef = ref()
const bindInfo = ref({})
const password = ref()

const getChannelConfig = async () => {
    const res = await getChannelConfigById(configId.value)
    channelConfig.value = res
}

const balanceAccount = async () => {
    const res = await getBalanceAccount()
    balance.value = res.balance
}

const getBalance = async () => {
    const res = await getBalanceAccount()
    balance.value = res.balance
}


setInterval (() => {
    getBalance()
}, 2000);


const handleWithdraw = async () => {
    if (inputAmount.value > balance.value) {
        dialogRef2.value.open({
            type: 'warning',
            title: '',
            content: 'Insufficient balance',
            showConfirmButton: true,
            showCancelButton: false,
            confirmText: 'Confirm',
        })
        return
    }
    if (!inputAmount.value || inputAmount.value <= 0) {
        dialogRef2.value.open({
            type: 'warning',
            title: '',
            content: 'Please input or select amount',
            showConfirmButton: true,
            showCancelButton: false,
            confirmText: 'Confirm',
        })
        return
    }
    showInput.value = true
}

const confirmWithdraw = async () => {
    const data = {
        withdrawalType: 1,
        amount: inputAmount.value,
        configId: configId.value,
        cryptoId: bindInfo.value.id,
        password: password.value
    }
    const res = await createWithdrawal(data) as any
    password.value = ''
    if (res.code === 1004180002) {
        dialogRef2.value.open({
            type: 'warning',
            title: '',
            content: t('withdrawal.p_i'),
            showConfirmButton: true,
            showCancelButton: false,
            confirmText: 'Confirm',
        })
        disabled.value = false
        showInput.value = false
        return
    }
    if (res.code === 1004180003) {
        dialogRef2.value.open({
            type: 'warning',
            title: '',
            content: res.msg,
            showConfirmButton: true,
            showCancelButton: false,
            confirmText: 'Confirm',
        })
        disabled.value = false
        showInput.value = false
        return
    }
    if (res.code === 1004180007) {
        dialogRef2.value.open({
            type: 'error',
            title: '',
            content: t('withdrawal.p_e'),
            showConfirmButton: true,
            showCancelButton: false,
            confirmText: 'Confirm',
        })
        password.value = ''
        disabled.value = false
        showInput.value = false
        return
    }
    if (res.code === 1004180008) {
        // 需要完成今天的任务
        dialogRef2.value.open({
            type: 'error',
            title: '',
            content: t('withdrawal.t_n_c'),
            showConfirmButton: true,
            showCancelButton: false,
            confirmText: 'Confirm',
        })
        password.value = ''
        disabled.value = false
        showInput.value = false
        return
    }
  if (res.code === 1004180009) {
    // 需要完成今天的任务
    dialogRef2.value.open({
      type: 'error',
      title: '',
      content: t('withdrawal.c_s_n_m'),
      showConfirmButton: true,
      showCancelButton: false,
      confirmText: 'Confirm',
    })
    password.value = ''
    disabled.value = false
    showInput.value = false
    return
  }
    if (res.code === 0) {
        console.log('取款RSS',res)
        successRef.value.open()
        showInput.value = false
        disabled.value = false
        await balanceAccount()
        return
    }
}

const getAmountList = async () => {
    const res = await getQuickRechargeAmount()
    amountList.value = res
}


const onActive = (item: any, index: number) => {
    active.value = index
    inputAmount.value = item
}

const formatAmount = () => {
    if (inputAmount.value > balance.value) {
        inputAmount.value = balance.value
    }
}

const modifyAddress = () => {
    router.push({
        name: 'bindCrypto',
        params: {
            configId: configId.value
        }
    })
}

const checkBindStatus = async () => {
    const res = await checkBind()
    console.log(res)
    if (res.code === 1004090003) {
        paymentPasswordRef.value.open()   
        return
    }
    if (res.code === 1004090001) {
        dialogRef.value.open({
            type: 'warning',
            title: '',
            content: 'Please bind wallet address',
            showConfirmButton: true,
            showCancelButton: false,
            confirmText: 'To Bind',
        })
        return
    }
    bindInfo.value = res.data
}

const setPasswordSuccess = async ()=> {
    await checkBindStatus()
}

// 挂载时获取路由参数
onMounted(async () => {
    configId.value = route.params.configId
    await balanceAccount()
    await getChannelConfig()
    await getAmountList()
    await checkBindStatus()
})



</script>
