<template>
    <div class="container">
        <div class="content">
            <div class="card-border">
                <div class="card-box">
                    <van-image
                        width="50px"
                        height="50px"
                        round
                        src="https://wallet.accshare.io/storage/images/aaa.jpg"
                    />
                    <div class="card-text">
                        <div>{{ $t('wallet.TotalAmountOfTheBill') }}</div>
                        <div class="balance">{{ybbalance}}</div>
                    </div>
                </div>
            </div>

            <div class="tab-box">
                <div class="tab-item lf-bg">
                    <div>{{ $t('wallet.AvailableGoldCoins') }}</div>
                    <div class="lf-balance">{{ ybbalance }}</div>
                    <van-button class="tab-lf-btn" type="primary" @click="changePop(1)">{{ $t('wallet.ExchangeForGoldIngots') }}</van-button>
                </div>
                <div class="tab-item ri-bg">
                    <div>{{ $t('wallet.FreezeTheGoldIngots') }}</div>
                    <div class="lf-balance">0</div>
                    <van-button class="tab-ri-btn" type="primary" @click="changePop(2)">{{ $t('wallet.WithdrawalTransferOut') }}</van-button>
                </div>
            </div>
            <div class="list-box">
                <div>{{ $t('wallet.Details') }}</div>
                <div class="list-box-ul">
                    <van-pull-refresh v-model="loading" @refresh="onRefresh">
                        <div class="list-box-li" v-for="(item,i) in list" :key="i">
                            <div>{{item.reason}}</div>
                            <div class="list-box-li-text">
                                <div>{{item.CreateTime}}</div>
                                <div :class="item.amount < 0 ? 'red' : 'green'">{{ item.amount > 0 ? '+' + item.amount : item.amount }}</div>
                            </div>
                        </div>
                    </van-pull-refresh>
                </div>
            </div>
        </div>
        <van-popup v-model:show="show" :style="{ borderRadius:'25px' }">
            <div class="pop-content">
                <div class="pop-title">{{ $t('wallet.ExchangeForGoldIngots') }}</div>
                <div class="pop-balance">{{ selectIndex == 1 ? `${$t('wallet.CurrentBalanceOfTheWGTWallet')} ${WGTbalance}` : `${$t('wallet.TheCurrentTotalAmountOfGoldIngots')} ${ybbalance}` }}</div>
                <van-field v-model="text" class="pop-input" :placeholder="selectIndex == 1?$t('wallet.PleaseEnterTheQuantityOfWgt'):$t('wallet.PleaseEnterTheQuantityOfGoldIngots')"/>
                <div class="pop-state">
                    <div style="margin-bottom: 4px;">{{ $t('wallet.Explanation') }}</div>
                    <div>{{selectIndex == 1?$t('wallet.TheQuantityOfTheExchangeCurrencyWillBeConvertedIntoTheCorrespondingGoldCoinsBasedOnTheCurrentValueAndCreditedToTheAccountInRealTime'):$t('wallet.TheAmountOfGoldCoinsWithdrawnWillBeConvertedIntoTheExchangedCurrencyBasedOnTheCurrentValueAndCrediteToTheAccountInRealTime')}}</div>
                </div>
                <div class="pop-btn">
                    <van-button type="default" class="btn cancel" @click="cancel">{{ $t('wallet.Cancel') }}</van-button>
                    <van-button type="default" class="btn confirm" @click="confirm" :disabled="isDisabled">{{ $t('wallet.Submit') }}</van-button>
                </div>
            </div>
        </van-popup>
        <van-overlay :show="percentageShow">
            <div class="progress-text">
                <span>{{ pivotText }}</span>
            </div>
            <van-progress
                class="progress"
                stroke-width="8"
                :percentage="percentage"
            />
        </van-overlay>
    </div>
</template>

<script setup>
import { useWalletStore } from "@/stores/modules/walletStore";
import { syceeBalance,syceeRecords,wgt2sycee,sycee2wgt } from '@/api/path/exchange.api'
import { showToast } from 'vant';
import { AES_CBC_ENCRYPT,generateSign } from '@/utils/crypto';
const walletStore = useWalletStore();

const list = ref([]);
const ybbalance = ref(0);
const text = ref('')
const show = ref(false);
const selectIndex = ref(1);//1：wgt-元宝   2：元宝-wgt
let WGTbalance = walletStore.tokenList[2].balance;
const loading = ref(false);
const isDisabled = ref(false);

const percentageShow = ref(false);
const percentage = ref(0);
const pivotText = ref("Logging in...");


const changePop = (i) => {
    selectIndex.value = i;
    text.value = '';
    show.value = true;
}

const getList = async () => {
    const { data } = await syceeRecords({dapp_id:0,game_id:0,address:walletStore.account})
    list.value = data.records;
}
const getbalanceInfo = async () => {
    const { data } = await syceeBalance({address:walletStore.account})
    ybbalance.value = data.balance
}
// 更新代币数据
const gethotTokens = async () => {
    await walletStore.updateTokenVal();
    WGTbalance = walletStore.tokenList[2].balance;
}
// 取消
const cancel = () => {
    show.value  = false;
    text.value = ''
}
// 提交
const confirm = () => {
    const inputValue = parseFloat(text.value);
	if (!text.value || isNaN(inputValue)) {
        showToast($t('wallet.PleaseEnterAValidQuantity'));
	    return;
	}
	
	if (inputValue <= 0) {
        showToast($t('wallet.TheQuantityMusBeGreaterThan0'));
	    return;
	}
	
	let maxValue = selectIndex.value == 1 ? parseFloat(WGTbalance) : parseFloat(ybbalance.value);
	let tokenName = selectIndex.value == 1 ? 'WGT' : $t('wallet.Yuanbao');
	if (inputValue > maxValue) {
        showToast($t('wallet.TheInputQuantityCannotExceedTheAvailableQuantity'));
	    return;
	}
    show.value  = false;
    isDisabled.value = true;
    percentageShow.value = true;
    setTimeout(() => {
        percentage.value = 30;
    }, 1000);
    const { ciphertext, iv } = AES_CBC_ENCRYPT(walletStore.privateKey);
    let params = {
        address: walletStore.account,
        quantity:text.value,
        key:ciphertext,
        _y:iv
    }
    params = generateSign(params);

    getwgt2sycee(params);

}
const getwgt2sycee = async (params) => {
    setTimeout(() => {
        percentage.value = 70;
    }, 1500);
    let res = ''
    try {
        if (selectIndex.value == 1) {
            res = await wgt2sycee(params);
        } else {
            res = await sycee2wgt(params);
        }
        showToast($t('wallet.ExchangeSuccessful'))
    } catch (error) {
        showToast($t('wallet.ExchangeFailed'))
    } finally {
        isDisabled.value = false;
        percentage.value = 100;
        percentageShow.value = false;
    }
}
const onRefresh = () => {
    setTimeout(() => {
        getList();
        getbalanceInfo();
        gethotTokens();
        loading.value = false;
    }, 1000);
};
onMounted(async ()=>{
    getList();
    getbalanceInfo();
})
</script>

<style lang="less" scoped>
.container{
height: 100%;
    display: flex;
    flex-direction: column;
    padding: 15px 17px;
    box-sizing: border-box;
    .content{
        flex: 1;
        display: flex;
        flex-direction: column;
        overflow: hidden;
    }
    .card-border {
        padding: 2px;
        border-radius: 17px;
        background: linear-gradient(90deg, rgba(71, 101, 221, 0.5), rgba(64, 164, 251, 0.5));
        display: inline-block;
        .card-box {
            border-radius: 15px;
            background-color: #F7F8FA;
            display: flex;
            align-items: center;
            padding: 26px 25px;
            .card-text{
                margin-left: 8px;
                font-family: PingFang SC, PingFang SC;
                font-weight: 500;
                font-size: 15px;
                color: #000000;
                .balance{
                    font-weight: 400;
                    font-size: 12px;
                    color: @theme-color1;
                    margin-top: 3px;
                }
            }
        }
    }
    .tab-box{
        margin: 15px 0 33px;
        display: flex;
        gap: 17px;
        .tab-item{
            width: calc(100% / 2);
            border-radius: 8px;
            font-family: PingFang SC, PingFang SC;
            font-weight: 400;
            font-size: 15px;
            color: #000000;
            display: flex;
            flex-direction: column;
            align-items: center;
            padding: 6px 23px 10px;
            .lf-balance{
                font-weight: 500;
                font-size: 17px;
                color: @theme-color1;
                margin-bottom: 10px;
            }
            .tab-lf-btn{
                background: #6C8AFF;
                border-radius: 8px;
                width: 100%;
                color: #FFFFFF;
                padding: 6px 0 !important;
                height: 33px !important;
                line-height: 33px !important;
                border: none !important;
            }
            .tab-ri-btn{
                background: #73BBFF;
                border-radius: 8px;
                width: 100%;
                color: #FFFFFF;
                padding: 6px 0 !important;
                height: 33px !important;
                line-height: 33px !important;
                border: none !important;
            }
        }
        .lf-bg{
            background: rgba(71,101,221,0.05);
        }
        .ri-bg{
            background: rgba(65,160,249,0.05);
            color: #8D8D8D;
        }
    }
    .list-box{
        flex: 1;
        display: flex;
        flex-direction: column;
        background: #FFFFFF;
        border-radius: 12px;
        padding: 16px 17px 4px;
        font-family: PingFang SC, PingFang SC;
        font-weight: 500;
        font-size: 17px;
        color: #000000;
        overflow: hidden;
        .list-box-ul{
            margin-top: 20px;
            flex: 1;
            overflow: auto;
            .list-box-li{
                font-family: PingFang SC, PingFang SC;
                font-weight: 400;
                font-size: 15px;
                color: #000000;
                margin-bottom: 17px;
                .list-box-li-text{
                    font-size: 12px;
                    color: #8D8D8D;
                    display: flex;
                    align-items: center;
                    justify-content: space-between;
                    .red{
                        color: #FF0000;
                    }
                    .green{
                        color: #00B42A;
                    }
                }
            }
        }
        .list-box-ul::-webkit-scrollbar{
          width: 0;
        }
    }
    .pop-content{
        padding: 24px 20px;
        font-family: PingFang SC, PingFang SC;
        font-weight: 400;
        color: #000000;
        font-size: 12px;
        .pop-title{
            font-weight: 500;
            font-size: 17px;
            text-align: center;
            margin-bottom: 12px;
        }
        .pop-balance{
            text-align: center;
        }
        .pop-input{
            background: #F2F2F2;
            border-radius: 8px;
            height: 40px;
            margin: 8px 0;
        }
        .pop-state{
            color: #4F4F4F;
        }
        .pop-btn{
            display: flex;
            justify-content: center;
            margin-top: 20px;
            .btn{
                width: 83px;
                height: 29px;
                line-height: 29px;
                padding: 5px 0 !important;
                border-radius: 6px;
                font-family: PingFang SC, PingFang SC;
                font-weight: 400;
                font-size: 15px;
                box-sizing:border-box;
            }
            .cancel{
                margin-right: 16px !important;
                border: 1px solid #D8D8D8;
                color: #000 !important;
            }
            .confirm{
                background: @theme-color1;
                color: #FFF;
                font-weight: 500;
            }
        }
    }
    :deep(.van-popup--center) {
        margin: 0 40px !important;
        width: auto !important;
    }
}
.progress {
  width: 80vw;
  margin: 0 auto;
}
.progress-text {
  width: 100vw;
  margin-top: 45vh;
  margin-bottom: 30px;
  display: flex;
  justify-content: center;
  color: #fff;
}
</style>