<template>
    <section class="max-w-xl m-auto">
        <van-nav-bar :title="t('bindCrypto.title')" :border="false">
            <template #left>
                <SvgIconVue name="allow-left" class="w-7 h-7" @click="$router.back" />
            </template></van-nav-bar>
        <div>
            <label for="address" class="block text-sm font-medium leading-6 text-gray-900 mx-4">{{ channelConfig.channelName
            }}</label>
            <div class="relative mt-4 rounded-md shadow-sm mx-4">
                <input type="text" name="address" id="address" class="block w-full rounded-md border-0 py-1.5  pr-20 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" :placeholder="t('bindCrypto.enterAddress')"
                    v-model="address" />
            </div>
            <div class="mt-8 mx-4">
                <van-button block color="linear-gradient(90deg, #F70 0%, #FF4900 100%)" class="font-semibold btn"
                    @click="handleSubmit" :disabled="disabled">{{ t('common.confirm') }}</van-button>
            </div>
        </div>
    </section>
    <Dialog ref="dialogRef" @Confirm="toNext" />
</template>

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

const route = useRoute()
const router = useRouter()
const disabled = ref(false)
const dialogRef = ref()
const address = ref('')
const configId = ref()
const bindInfo = ref({})
const channelConfig = ref({
    channelName: ''
})

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

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

const handleSubmit = async () => {
    const data = {
        address: address.value,
        configId: configId.value
    }
    const res = await bindCryptoAddress(data) as any
    if (res.code === 0) {
        dialogRef.value.open({
            type: 'success',
            content: 'Bind Success',
            confirmText: 'Continue'
        })
    }
}

const checkBindStatus = async () => {
    const res = await checkBind()
    if (res) {
        bindInfo.value = res
        address.value = bindInfo.value.address
    }

}

// 挂载时获取渠道配置
onMounted(async () => {
    configId.value = route.params.configId
    await getChannelConfig()
    await checkBindStatus()
})

</script>
