<template>
    <div class="withdraw-wrapper">
        <!-- <div class="nav-bar">
            <img
                :src="require('@/assets/svg/icon-bar-arrow-left.svg')"
                class="icon"
                @click="back"
            />
            Withdraw
        </div> -->
        <template v-if="!isSubmit">
            <div class="content">
                <div class="logo-wrapper">
                    <div class="title">Withdraw to</div>
                    <img class="icon" :src="
                        require('@/assets/svg/icon-withdraw-paypal-logo.svg')
                    " />
                </div>

                <div class="form-wrapper">
                    <div class="form-item">
                        <div class="label">PayPal account</div>
                        <div class="input-wrapper">
                            <input type="text" 
                                v-model="requestWithdrawParams.withdrawReceiveAccount" placeholder="Enter PayPal account"/>
                        </div>
                    </div>
                    <div class="form-item">
                        <div class="label">Withdrawal amount<span
                                class="msg">（${{ walletWithdrawConfig.withdrawPerMinAmount }} minimum）</span></div>
                        <div class="input-wrapper amount-wrapper">
                            <input type="text" 
                                v-model="requestWithdrawParams.amountValue" 
                                placeholder="$0"
                                style="width: 220px"
                                @input="onAmountInput" 
                                @blur="onAmountBlur" />
                            <div @click="withdrawalAll" class="withdrawal-all-btn">
                                Withdrawal All
                            </div>
                        </div>
                    </div>

                    <div class="error-msg">
                        <template v-if="showWithdrawError">
                            The minimum withdrawal amount is ${{ walletWithdrawConfig.withdrawPerMinAmount }} USD
                        </template>
                        <template v-if="showWithdrawIptError">
                            The withdrawal amount exceeds the total account balance of ${{ canWithdrawBalance }} USD
                        </template>
                    </div>
                </div>

                <div class="bottom-msg">
                    <div class="top">
                        <template v-if="!calcReq">
                            final amount
                            <span>${{
                                    finalWithdrawalAmount > 0
                                        ? finalWithdrawalAmount
                                        : 0
                            }}
                            </span>
                        </template>
                        <template v-else>
                            calculating
                        </template>
                    </div>
                    <div>{{ walletWithdrawConfig.withdrawFeeDesc }}</div>
                </div>
            </div>
            <div @click="withdraw" class="confirm-btn">
                <img class="icon-loading" v-if="withdrawIng" :src="require('@/assets/svg/icon-btn-loading.svg')" />
                Confirm
            </div>
        </template>
        <template v-else>
            <div class="withdraw-status">
                <img :src="require('@/assets/svg/icon-withdraw-status.svg')" alt="" />
                <div>
                    <div class="title">Submitted successfully</div>
                    <div class="desc">
                        Please wait for a while,<br />
                        then check the balance with paypal
                    </div>
                </div>
            </div>
            <div class="confirm-btn" @click="doneWithdraw">
                Done
            </div>
        </template>
    </div>
</template>

<script setup>
/* eslint-disable */
import { defineProps, defineEmits, ref, onMounted, watch, computed, inject } from "vue";
import { withdrawRequest, getWithdrawConfig } from "@/http/account";
import { withdrawCalcFee } from "@/http/pay";
import { debounce } from "@/uilts/help"

const props = defineProps({
    amountValue: {
        type: Number,
        default: 0,
    }
});
let withdraw_info = inject('withdraw_info')

console.log('withdraw_info', withdraw_info)
let requestWithdrawParams = ref({
    amountValue: "",
    currencyCode: "USD",
    withdrawNetwork: 'paypal', // 1: paypal
    withdrawReceiveAccount: "",
});

let canWithdrawBalance = ref(withdraw_info.paypal.amount_value);

let showWithdrawError = ref(false);
let showWithdrawIptError = ref(false);
let isSubmit = ref(false);
let withdrawIng = ref(false);

let walletWithdrawConfig = ref({
        withdrawPerMinAmount: 1,
        withdrawUSDSwitch: "",
        withdrawFeeDesc: ''
    });

let finalWithdrawalAmount = ref('');
let calcReq = ref(false);

onMounted(() => {
    queryWithdrawConfig()
});
/**
 * 获取提现配置
 */
const queryWithdrawConfig = () => {
    getWithdrawConfig({
        params: {
            currencyCode: withdraw_info.currency_code || 'USD',
            withdrawNetwork: 'paypal'
        },
    }).then((res) => {
        if (res.code == 0) {
            walletWithdrawConfig.value = res.data;
        }
        console.log('queryWithdrawConfig',walletWithdrawConfig.value);
    });
};

const emits = defineEmits("back");
const back = () => {
    if (isSubmit.value) {
        isSubmit.value = false;
    } else {
        emits("back", {});
    }
};

const doneWithdraw = () => {
    isSubmit.value = false;
    emits("back", {});
};


const withdrawalAll = () => {
    console.log(canWithdrawBalance.value);
    showWithdrawIptError.value = false;
    requestWithdrawParams.value.amountValue =
        canWithdrawBalance.value;
    setWithdrawIptStatus(canWithdrawBalance.value);
    withdrawCalcAmount();
};

const withdrawCalcAmount = () => {
    calcReq.value = true;
    withdrawCalcFee({
        params: {
            amountValue: requestWithdrawParams.value.amountValue,
            currencyCode: requestWithdrawParams.value.currencyCode,
            withdrawNetwork: 'paypal'
        }
    }).then(res => {
        calcReq.value = false;
        if (res.code == 0) {
            finalWithdrawalAmount.value = res.data.finalAmountValue;
        }
    })
}

const withdrawCalcAmountDebounce = debounce(function () {
    withdrawCalcAmount();
}, 1000)

/**
 * 提现
 */
const withdraw = () => {
    console.log("requestWithdrawParams.value", requestWithdrawParams.value);
    if (withdrawIng.value) {
        return;
    }

    let params = {
        ...requestWithdrawParams.value,
    };
    if (!params.amountValue || !params.withdrawReceiveAccount) {
        return;
    }
    params.withdrawReceiveAccount = params.withdrawReceiveAccount.replace(/\s*/g, "");
    params.amountValue = params.amountValue;
    if (parseInt(params.amountValue) > parseInt(canWithdrawBalance.value)) {
        return;
    }
    withdrawIng.value = true;
    withdrawRequest({
        params,
    }).then((res) => {
        withdrawIng.value = false;
        if (res.code == 0) {
            canWithdrawBalance.value =
                canWithdrawBalance.value - params.amountValue;
            requestWithdrawParams.value = {
                amountValue: "",
                currencyCode: "USD",
                withdrawNetwork: 'paypal', //  paypal
                withdrawReceiveAccount: "",
            };
            isSubmit.value = true;
        } else {
            console.log(res);
        }
    })
        .catch((err) => {
            console.log(err);
        });
};

const onAmountBlur = () => {
    withdrawCalcAmount();
}

const onAmountInput = () => {
    //限制输入数字 小数点俩位
    let value = requestWithdrawParams.value.amountValue;
    value = value
        .replace(/[^\d.]/g, "")
        .replace(/\.{2,}/g, ".")
        .replace(".", "$#$")
        .replace(/\./g, "")
        .replace("$#$", ".")
        .replace(/^(-)*(\d+)\.(\d\d).*$/, "$1$2.$3")
        .replace(/^\./g, "");
    requestWithdrawParams.value.amountValue = value;

    setWithdrawIptStatus(value);

    // 输入金额大于可提现金额
    if (parseInt(value) > parseInt(canWithdrawBalance.value)) {
        if (!showWithdrawError.value) {
            showWithdrawIptError.value = true;
        }
    } else {
        showWithdrawIptError.value = false;
    }

    withdrawCalcAmountDebounce();

    return value;
};

const setWithdrawIptStatus = (amount) => {
    //显示tips
    if (
        amount > 0 &&
        amount < walletWithdrawConfig.value.withdrawPerMinAmount
    ) {
        showWithdrawError.value = true;
    } else {
        showWithdrawError.value = false;
    }
}
</script>

<style lang="scss" scoped>
.withdraw-wrapper {
    width: 100%;
    height: 100%;
    position: relative;
    overflow: hidden;

    .nav-bar {
        padding: 14px;
        box-sizing: border-box;
        display: flex;
        align-items: center;
        font-weight: 500;
        font-size: 13px;

        .icon {
            width: 16px;
            margin-right: 6px;
            cursor: pointer;
        }
    }

    .content {
        padding: 0 20px;
        box-sizing: border-box;

        .logo-wrapper {
            .title {
                margin-top: 13px;
                font-size: 14px;
                color: #5b5b5b;
            }

            .icon {
                width: 111px;
                height: 56px;
                margin-bottom: 20px;
            }
        }

        .form-wrapper {
            .form-item {
                margin-bottom: 30px;

                .label {
                    font-size: 14px;
                    color: #5b5b5b;
                    margin-bottom: 8px;

                    .msg {
                        font-weight: 400;
                        font-size: 14px;
                        color: #FFA621;
                    }
                }

                .input-wrapper {
                    display: flex;
                    align-items: center;
                    justify-content: space-between;
                    border: 1px solid #e8e8e8;
                    border-radius: 8px;

                    .withdrawal-all-btn {
                        font-weight: 500;
                        font-size: 13px;
                        color: #1D9BF0;
                        padding-right: 10px;
                        cursor: pointer;
                    }

                    input {
                        width: 100%;
                        height: 48px;
                        border: none;
                        border-radius: 8px;
                        padding: 0 16px;
                        box-sizing: border-box;
                        outline: none;
                    }
                }
            }

            .error-msg {
                font-size: 13px;
                color: #ff0000;
                margin-top: -15px;
                height: 38px;
            }
        }

        .bottom-msg {
            font-size: 13px;
            color: #9d9d9d;
            text-align: right;
            margin-top: 52px;

            .top {
                height: 22px;

                span {
                    font-weight: 500;
                    font-size: 15px;
                    color: #000000;
                }
            }
        }
    }

    .withdraw-status {
        text-align: center;

        img {
            margin-top: 40px;
            margin-bottom: 34px;
        }

        .title {
            font-weight: 500;
            font-size: 20px;
            margin-bottom: 10px;
        }

        .desc {
            font-size: 15px;
            color: rgba($color: #000000, $alpha: 0.5);
        }
    }

    .confirm-btn {
        width: 335px;
        height: 60px;
        text-align: center;
        line-height: 60px;
        border-radius: 100px;
        background: #1D9BF0;
        font-weight: 600;
        font-size: 18px;
        color: #fff;
        position: absolute;
        left: 50%;
        bottom: 35px;
        transform: translateX(-50%);
        display: flex;
        align-items: center;
        justify-content: center;
        cursor: pointer;

        .icon-loading {
            width: 20px;
            height: 20px;
            margin-right: 3px;
        }
    }
}
</style>
