<template>
    <cwg-page-wrapper>
        <view class="page">
            <u-form ref="formRef" :rules="rules" :model="form" class="payment-form">
                <cwg-input v-model:value="form.blockchain" fkey="blockchain" type="select" :required="true"
                    :columns="blockchainList" :label="t('Blockchain.addP2')" rulesKey="blockchain"
                    @change="handleChange" />
                <cwg-input :label="t('WalletApply.p1')" v-model:value="form.address" fkey="address" type="text"
                    rulesKey="address" :placeholder="t('WalletApply.p2')" :required="true" clearable />
                <cwg-input :label="`${t('WalletApply.p3')} ${t('WalletApply.p5', { userBalance: form.userBalance })}`"
                    rulesKey="amount" v-model:value="form.amount" fkey="amount" type="number"
                    :placeholder="t('WalletApply.p4')" :required="true" @change="globalExchangeRate" clearable />

                <view>
                    <view class="code-input-wrapper">
                        <view class="code-input">
                            <cwg-input v-model:value="form.emailCode" :label="t('newSignup.item9')" fkey="emailCode"
                                type="text" :required="true" rulesKey="emailCode" :placeholder="t('newSignup.item10')"
                                @change="handleChange" />
                        </view>
                        <view class="get-code-btn1">
                            <view class="ok-button">
                                <u-button type="primary" block>{{ getCodeString }}</u-button>
                            </view>
                        </view>
                        <view class="get-code-btn">
                            <view class="cwg-button">
                                <u-button type="primary" block @click="handleGetCode">{{ getCodeString }}</u-button>
                            </view>
                        </view>
                    </view>
                </view>
            </u-form>

            <view class="fixed-btn">
                <view class="cwg-button">
                    <u-button type="primary" block @click="infoSubmit">{{ t("card.Btn.Submit") }}</u-button>
                </view>
            </view>
        </view>
        <cwg-SuccessPrompt v-model:show="showSuccessPrompt" :title="t('pages.wallet.withdraw')"
            :desc="t('Custom.Withdraw.Des1')" :btn-click="btnClick" />
    </cwg-page-wrapper>
</template>
<script setup lang="ts">
import { ref, onMounted, watch, computed, onBeforeUnmount } from "vue";
import { showToast } from "@/utils/toast";
import { useI18n } from "vue-i18n";
import { ucardApi } from "@/api/ucard";
import useUserStore from "@/stores/use-user-store";
import useRouter from "@/hooks/useRouter";
import { Validators } from "@/utils/validators";
import { onLoad } from '@dcloudio/uni-app'
onLoad((options) => {
    userBalance.value = options.allAmount
})
const userBalance = ref(0);
const router = useRouter();
const { t } = useI18n();
const userStore = useUserStore();
const userInfo = computed(() => userStore.userInfo);
const formRef = ref();
const form = ref<{
    emailCode: string;
    cardNo?: string;
    password?: string;
    country?: string;
    email?: string;
}>({
    emailCode: "",
});
const text1 = ref("");
const blockchainList = ref([]);
const timer = ref(59);
const getCodeString = ref("");
const interval = ref<NodeJS.Timeout | null>(null);
// 表单验证规则
const rules = {
    blockchain: [Validators.required(t("Blockchain.addP2"))],
    address: [Validators.required(t("WalletApply.p2"))],
    amount: [
        Validators.required(t("global.validator.v15")),
        Validators.custom(validateAmount),
    ],
};
function validateAmount(a: any, b?: any, c?: any) {
    if (typeof c === "function") {
        const value = b;
        const callback = c;
        const val = String(value ?? "").trim();
        const num = Number(val);
        const pattern = /^(?:[1-9]\d*(?:\.\d{1,2})?|0\.(?!0+$)\d{1,2})$/;
        if (!pattern.test(val)) {
            callback(new Error(t("global.validator.v15")));
            return;
        }
        if (isNaN(num) || num <= 0) {
            callback(new Error(t("global.validator.v15")));
            return;
        }
        const balance = Number(form.value.userBalance);
        if (!isNaN(balance) && num > balance) {
            const msg = t("WalletApply.p6", { userBalance: form.value.userBalance });
            callback(new Error(msg));
            return;
        }
        return callback();
    }
}
function btnClick() {
    showSuccessPrompt.value = false;
    router.push({ path: "/pages/wallet/index" })
}
// 初始化表单
function initForm() {
    const a = { uniqueId: userInfo.value.uniqueId, country: userInfo.value.country, email: userInfo.value.email }
    if (userInfo.value) {
        form.value = {
            ...a,
            userBalance: userBalance.value,
            emailCode: "",
        };
    }
    text1.value = "";
    timer.value = 59;
    getCodeString.value = t("newSignup.item11");
    if (interval.value) {
        clearInterval(interval.value);
        interval.value = null;
    }
}
// 初始化定时器
function initTimer() {
    const savedTimer = Number(localStorage.getItem("cvvTimer")) || 59;
    if (savedTimer === 59) {
        getCodeString.value = t("newSignup.item11");
    } else {
        timer.value = savedTimer;
        startTimer();
    }
}

// 开始倒计时
function startTimer() {
    if (interval.value) {
        return;
    }
    getCodeString.value = `${t("signup.form.waitCode1")}${timer.value}${t(
        "signup.form.waitCode2"
    )}`;
    interval.value = setInterval(() => {
        timer.value--;
        localStorage.setItem("cvvTimer", timer.value.toString());
        if (timer.value > 0) {
            getCodeString.value = `${t("signup.form.waitCode1")}${timer.value}${t(
                "signup.form.waitCode2"
            )}`;
        } else {
            getCodeString.value = t("newSignup.item11");
            if (interval.value) {
                clearInterval(interval.value);
                interval.value = null;
            }
            timer.value = 59;
            localStorage.setItem("cvvTimer", "59");
        }
    }, 1000);
}
const showSuccessPrompt = ref(false);
// 提交表单
async function infoSubmit() {
    try {
        await formRef.value?.validate();
        let res = await ucardApi.getBlockchainWithdrawApply({
            ...form.value,
        });
        if (res.code == 200) {
            showSuccessPrompt.value = true;
        } else {
            showToast(res.msg);
        }
    } catch (error) {
        console.log(error, 1111);

    }
}
//获取区块链
async function getBlockchainDropdown() {
    let res = await ucardApi.getBlockchainDropdown({
        ...form.value,
        type: '2'
    });
    if (res.code == 200) {
        res.data.map((item: any) => {
            item.text = item.alias;
            item.value = item.blockchain;
        });
        blockchainList.value = res.data;
    } else {
        blockchainList.value = []
        showToast(res.msg);
    }
}

// 发送邮箱验证码
async function sendEmailCode() {
    try {
        if (!form.value.country) {
            showToast(t("vaildate.country.empty"));
            return false;
        }
        if (!form.value.email) {
            showToast(t("vaildate.email.empty"));
            return false;
        }

        const res = await ucardApi.getBlockchainWithdrawSendEmailCode({
            ...form.value,
        });

        if (res.code === 200) {
            showToast(t("Msg.CodeSuccess"));
            startTimer();
            return true;
        } else {
            showToast(t("Msg.CodeFail"));
            return false;
        }
    } catch (error: any) {
        console.log(error, 12);

        showToast(t("Msg.CodeFail"));
        return false;
    }
}

// 获取验证码按钮点击
async function handleGetCode() {
    if (timer.value > 0 && timer.value < 59) {
        return;
    }
    text1.value = "";
    await sendEmailCode();
}

// 表单字段变化
function handleChange(value: any) {
    if (value.key === "emailCode") {
        form.value.emailCode = value.value;
    }
}


onMounted(() => {
    initForm();
    initTimer();
    getBlockchainDropdown();
});

// 组件卸载时清理
onBeforeUnmount(() => {
    if (interval.value) {
        clearInterval(interval.value);
        interval.value = null;
    }
});
</script>

<style lang="scss" scoped>
@import "@/uni.scss";

.no-button {
    width: 100%;
    margin: px2rpx(12) 0;

    .u-button {
        background-color: #ffbdc8 !important;
    }
}


.code-input-label {
    font-size: var(--font-size-16);
    line-height: px2rpx(44);
    letter-spacing: px2rpx(1);
    color: #474747;
}

.code-input-wrapper {
    position: relative;
    display: flex;
    align-items: center;
}

.code-input {
    flex: 1;
}

.get-code-btn1 {
    min-width: px2rpx(100);
    margin-left: px2rpx(8);

    .ok-button {

        .u-button {
            background-color: #fff;
            opacity: 0;
        }
    }

}

.get-code-btn {
    position: absolute;
    right: 0;
    bottom: px2rpx(12);
    min-width: px2rpx(100);
    background-color: #fff;
    z-index: 1;
    margin-left: px2rpx(8);

    .cwg-button {
        margin: 0;
    }

    .cwg-button .u-button {
        border-radius: px2rpx(8);
        height: px2rpx(46) !important;
    }
}

.submit-section {
    margin: px2rpx(20) 0;
}

.submit-btn {
    width: 100%;
}
</style>