<template>
    <section id="order-list" class="bg-[#F4F6F7] pb-20">
        <van-navBar :title="t('order.title')" :border="false">
        </van-navBar>
        <van-tabs v-model:active="active" color="#FF4900" @change="onTabChange">
            <van-tab :title="tab.title" v-for="tab in tabs" class="mt-4">
                <van-pull-refresh v-model="loading" @refresh="onRefresh" pulling-text="Pull Refresh" loosing-text="loosing"
                    loading-text="loading">
                    <van-list v-model:loading="loading" :finished="finished" finished-text="no more data"
                        loading-text="loading" :offset="10" @load="onLoad" error-text="loading error">
                        <div class="bg-white flex flex-col mt-4 mx-4 rounded-lg" v-for="(item, index) in list"
                            :key="item.orderNo">
                            <div class="flex flex-row justify-between">
                                <div class="text-ss text-[#575555] pl-4 pt-4">{{ t('order.order_no') }}: {{ item.orderNo }}</div>
                                <div class="text-ss p-1 rounded-bl-xl text-white relative w-20 h-7"
                                    :class="['active-bg-' + item.executeStatus]">
                                    <div class="text-center">{{ status[item.executeStatus] }}</div>
                                </div>
                            </div>
                            <div class="flex flex-row items-center justify-start my-4 px-4">
                                <div class="w-[50px] h-[50px] mr-4"><img :src="item.picUrl" alt=""></div>
                                <div class="flex flex-col h-[60px] w-[280px]  text-black font-bold text-sm">
                                    <span class="line-clamp-2 mt-2">{{ item.productName }}</span>
                                </div>
                            </div>
                            <div class="px-4">
                                <div>
                                    <div class="flex flex-row items-center justify-between mr-3 mt-2">
                                        <div class="text-[#575555] text-st">{{ t('order.u_p') }}:</div>
                                        <div class="text-[#575555] font-bold text-base">USDT {{ item.unitPrice }}</div>
                                    </div>
                                </div>
                                <div>
                                    <div class="flex flex-row items-center justify-between mr-3 mt-2">
                                        <div class="text-[#575555] text-st">{{ t('order.o_q') }}</div>
                                        <div class="text-[#575555] font-bold text-base">{{ item.quantity }}</div>
                                    </div>
                                </div>
                                <div>
                                    <div class="flex flex-row items-center justify-between mr-3 mt-2">
                                        <div class="text-[#575555] text-st">{{ t('order.total') }}</div>
                                        <div class="text-[#575555] font-bold text-base">${{ item.totalPrice }}</div>
                                    </div>
                                </div>
                                <div>
                                    <div class="flex flex-row items-center justify-between mr-3 mt-2">
                                        <div class="text-[#DF4418] text-st">{{ t('order.o_c') }}</div>
                                        <div class="text-[#DF4418] font-bold text-base">{{ item.commission }}</div>
                                    </div>
                                </div>
                                <div>
                                    <div
                                        class="text-st text-[#575555] flex flex-row items-center justify-between mr-3 mt-2 mb-4">
                                        <div>{{ t('order.c_t') }}</div>
                                        <div>{{ formatDate(item.orderTime) }}</div>
                                    </div>
                                </div>
                            </div>
                            <div class="mx-4 mb-4" v-if="item.executeStatus == 2">
                                <van-button block class="van-default-btn" @click="handleSubmit(item.id)"
                                    :disabled="submitDisable">
                                    <span class="text-white font-semibold text-sm">Submit</span>
                                </van-button>
                            </div>
                        </div>
                    </van-list>
                </van-pull-refresh>
            </van-tab>
        </van-tabs>
    </section>
    <Dialog ref="dialogRef" @confirm="toNext" />
    <GrabOrder ref="grabOrderRef" @success="successGrabOrder" />
    <OrderDetails ref="orderDetailsRef" @success="successSubmit" />
    <Success ref="successRef" />
</template>

<script setup lang="ts">
import { ref } from 'vue';
import { pageOrder, submitOrder } from '@/api/order'
import { onMounted } from 'vue';
import Dialog from '@/components/Dialog.vue';
import { useRouter } from 'vue-router';
import GrabOrder from '../start/components/GrabOrder.vue';
import OrderDetails from '../start/components/OrderDetails.vue';
import Success from '@/components/Success.vue';
import type { OrderItem } from '../start/types';
import {formatDate} from '@/utils/formatTime'
import { useI18n } from 'vue-i18n'

const { t } = useI18n()


const active = ref(0);
const loading = ref(false)
const finished = ref(false)
const submitDisable = ref(false)
const dialogRef = ref()
const grabOrderRef = ref()
const orderDetailsRef = ref()
const successRef = ref()

const isContinue = ref(false)

const router = useRouter()
const status = {
    '0': t('order.completed'),
    '2': t('order.pending'),
    '4': t('order.frozen')
}

const params = ref({
    pageNo: 0,
    pageSize: 10,
    executeStatus: undefined
})

const list = ref([])

const listOrder = async () => {
    finished.value = false
    loading.value = true
    params.value.pageNo += 1
    const res = await pageOrder(params.value)
    loading.value = false;
    return res
}

const onRefresh = async () => {
    list.value = []
    finished.value = false
    params.value.pageNo = 0
    await onLoad()
}

const onLoad = async () => {
    if (finished.value) {
        loading.value = false;
        return
    }
    loading.value = true
    const res = await listOrder()
    const listData = res.list;
    if (!listData || listData.length <= 0) {
        finished.value = true;
        loading.value = false;
        return
    }
    list.value = list.value.concat(listData)
    loading.value = false
    finished.value = list.value.length >= res.total
}
const onTabChange = async (index: number) => {
    params.value.pageNo = 0
    finished.value = false
    list.value = []
    if (index === 0) {
        params.value.executeStatus = undefined
    }
    if (index === 1) {
        params.value.executeStatus = 2 as any
    }
    if (index === 2) {
        params.value.executeStatus = 4 as any
    }
    if (index === 3) {
        params.value.executeStatus = 0 as any
    }
    await onLoad()
}

const tabs = ref([
    { title: t('order.all'), status: '' },
    { title: t('order.pending'), status: '2' },
    { title: t('order.frozen'), status: '4' },
    { title: t('order.completed'), status: '0' },
])

const successGrabOrder = (item: OrderItem) => {
    if (item.combo == 1) {
        isContinue.value = true
    } else {
        isContinue.value = false
    }
    orderDetailsRef.value.open(item)
}

const successSubmit = async (data: any) => {
    if (isContinue.value) {
        grabOrderRef.value.open()
    } else {
        successRef.value.open()
        await onRefresh()
    }
}

const handleSubmit = async (id: string) => {
    submitDisable.value = true
    const data = { id }
    const res = await submitOrder(data) as any
    if (res.code === 1004008003) {
        dialogRef.value.open({
            type: 'warning',
            title: '',
            content: 'Insufficient balance',
            showConfirmButton: true,
            showCancelButton: false,
            confirmText: 'To Recharge',
        })
    }
    if (res.code === 1004008004) {
        dialogRef.value.open({
            type: 'warning',
            title: '',
            content: 'The order has been submitted',
            showConfirmButton: true,
            showCancelButton: false,
            confirmText: 'Confirm',
        })
    }
    if (res.data) {
        grabOrderRef.value.open()
    } else {
        if (res.code === 0) {
            successRef.value.open()
        }
        
        await onRefresh()
    }
    submitDisable.value = false
}

const toNext = () => {
    router.push({ name: 'channelSelect', params: { scenario: 1 } })
}


</script>


<style scoped>
.active-bg-0 {
    background-color: #FF4900;
}

.active-bg-2 {
    background-color: #19CA19;
}

.active-bg-4 {
    background-color: #FFA900;
}
</style>