<template>
    <!-- Header Start -->
    <header class="header">
        <div class="logo-wrap">
            <i class="icon-arrow-left-bold-box icli" @click="$router.push('/user/info')"></i>
            <h1 class="title-color font-md">餘額管理</h1>
        </div>
    </header>
    <!-- Header End -->

    <!-- Main Start -->
    <main class="main-wrap order-history mb-xxl">
        <!-- Account Info  Start -->
        <div class="info-section">
            可提領餘額: ${{ accInfo.user_money }}<br/>
            未入帳餘額: ${{ accInfo.frozen_money }}<br/>
            總餘額: ${{ parseInt(accInfo.user_money) + parseInt(accInfo.frozen_money) }}
        </div>
        <!-- Account Info  End -->

        <!-- Action:  Start -->
        <div class="action-section">
            <van-button type="success" size="small" @click="showWithdraw = true">我要提領</van-button>
        </div>
        <!-- Action:  End -->

        <!-- Tab Content Start -->
        <section class="tab-content ratio2_1" id="pills-tabContent">
            <!-- Catagories Content Start -->
            <div class="tab-pane fade show active" id="catagories1" role="tabpanel" aria-labelledby="catagories1-tab">
                <van-pull-refresh v-model="refreshing" @refresh="onRefresh">                
                <van-list 
                v-model:loading="loading" 
                :finished="finished" 
                finished-text="没有更多了" 
                @load="onLoad">
                    <div class="order-box" v-for="(v, i) in list" :key="v.id">
                        <div class="media">
                            <div class="content-box">
                                <h2 class="font-sm title-color">操作時間: {{ v.add_time }}</h2>
                                <h2 class="font-sm title-color">類型: {{ v.process_type }}</h2>
                                <div class="content-color font-xs">
                                    金額: <span class="font-theme">${{ v.amount }}</span>
                                </div>
                                <p class="font-xs content-color">會員備註：{{ v.user_note }}</p>
                                <p class="font-xs content-color">管理員備註：{{ v.admin_note }}</p>
                                <div></div>
                            </div>
                        </div>
                        <div class="bottom-content">
                            <a class="title-color font-sm fw-600"> {{ v.is_paid }} </a>
                            <a 
                            @click="handleCancel(v.id)" 
                            v-if="v.is_paid == '未支付'"
                            class="give-rating content-color font-sm"> 取消</a>
                        </div>
                    </div>
                </van-list>
                </van-pull-refresh>
            </div>
            <!-- Catagories Content End -->
        </section>
        <!-- Tab Content End -->
    </main>
    <!-- Main End -->

    <!-- Add New Withdraw Start -->
    <van-popup v-model:show="showWithdraw" round closeable position="bottom">
        <div class="offcanvas-header">
            <h5 class="title-color font-md fw-600">餘額提領</h5>
        </div>
        <van-form @submit="onSubmit" ref="addrForm">
            <div class="offcanvas-body small">
                <van-cell-group inset>
                    <van-field
                        v-model="form.amount"
                        name="amount"
                        label="提領金額"
                        placeholder="金額最少為1000"
                        :rules="[{ required: true, message: '提領金額' }]"
                    />
                    <van-field v-model="form.user_note" name="user_note" label="提領備註" />
                </van-cell-group>
            </div>
            <div style="margin: 16px">
                <van-button round block type="success" native-type="submit"> 確認送出 </van-button>
            </div>
        </van-form>
    </van-popup>
    <!-- Add New Withdraw End -->
</template>

<script setup>
import { ref, onMounted, watch } from "vue";
import { getUserAccInfo, getUserAccounts, addUserAccount, delUserAccount } from "@/services/user";
import { showToast } from "vant";
import "vant/es/toast/style";
import { showConfirmDialog } from 'vant';
import { load } from "@liff/extensions";

const accInfo = ref({
    user_money: 0,
    frozen_money: 0,
});

const list = ref([]);

const page = ref(1);

const loading = ref(false);

const finished = ref(false);

const refreshing = ref(false);

onMounted(async() => {
    // let res = await getUserAccInfo();
    // if(res.code === 200){
    //     accInfo.value = res.data;
    // }
});

const onLoad = async ()=>{

    if (refreshing.value) {
        page.value = 1;
        list.value = [];
        refreshing.value = false;
    }

    let res = await getUserAccounts(page.value);

    if (res.code === 200) {
        //將返回的res.data添加到list array中
        list.value.push(...res.data.data);

        // list.value.push(res.data);
        page.value += 1
    }

    loading.value = false;

    if (list.value.length == res.data.total) {
        finished.value = true;
    }
}

const onRefresh = async () =>{
    finished.value = false;
    loading.value = true;
    onLoad();
}

//提領
const showWithdraw = ref(false);

const form = ref({
    amount: null,
    user_note: "",
});

const onSubmit = async () => {
    if(form.value.amount < 1000){
        showToast("提領金額最少為1000");
        return;
    }
    if(form.value.amount > accInfo.value.user_money){
        showToast("提領金額不足，您目前可提領的金額為" + accInfo.value.user_money);
        return;
    }
    let res = await addUserAccount(form.value);
    if (res.code === 200) {
        showToast("申請成功，請等待管理員審核撥款");
        list.value = res.data;
        form.value = {};
    } else {
        showToast("操作失敗,重新發送");
    }
    showWithdraw.value = false;
};

//取消
const handleCancel = (id) => {
    showConfirmDialog({
        title: "確認取消",
        message: "您確定要取消此筆提領嗎？",
        confirmButtonText: "確認",
        cancelButtonText: "取消",
    })
    .then(async () => {
        let res = await delUserAccount(id);
        if (res.code === 200) {
            showToast("取消成功");
            //移除list.value中,id為id的項目
            list.value = list.value.filter((v) => v.id !== id);
        } else {
            showToast("取消失敗");
        }
    })
    .catch(() => {
        showToast("取消操作");
    });
};
</script>

<style lang="less" scoped>
.action-section {
    //靠右
    text-align: right;
}
</style>
