<template>
    <form ref="form" @submit.prevent="handleCollect">
        <div class="position-relative">
            <LoadingOverlay v-model="isLoading" />
            <!-- Danh sách đơn hàng -->
            <div class="mb-4">
                <h6 class="mb-3">Danh sách đơn hàng</h6>
                <div class="table-responsive" style="max-height: 50vh;">
                    <table class="table table-hover table-bordered mg-b-0">
                        <thead class="sticky-top bg-white">
                            <tr>
                                <th class="wd-lg-5p min-width-1">STT</th>
                                <th class="wd-lg-10p min-width-1">Mã đơn hàng</th>
                                <th class="wd-lg-25p min-width-1">Địa chỉ gửi</th>
                                <th class="wd-lg-25p min-width-1">Địa chỉ giao</th>
                                <th class="wd-lg-10p min-width-1">Cước lấy</th>
                                <th class="wd-lg-10p min-width-1">Cước giao</th>
                                <th class="wd-lg-10p min-width-1">Thu hộ</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr v-for="(order, index) in cashier?.OrderList" :key="order.id">
                                <td>{{ index + 1 }}</td>
                                <td>{{ order.Code }}</td>
                                <td>
                                    <span>{{ order.SenderName }} | {{ order.SenderPhone }}</span><br>
                                    <span>{{ order.SenderAddress }}</span>
                                </td>
                                <td>
                                    <span>{{ order.RecipientName }} | {{ order.RecipientPhone }}</span><br>
                                    <span>{{ order.RecipientAddress }}</span>
                                </td>
                                <td>{{ formatCurrency(order.SourceFee) }}</td>
                                <td>{{ formatCurrency(order.DestFee) }}</td>
                                <td>{{ formatCurrency(order.CodAmount) }}</td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            </div>

            <div class="row mb-3">
                <div class="col-md-4">
                    <label class="form-label">Số tiền mặt</label>
                    <VueNumberFormat v-model:value="collectData.cashAmount" class="form-control"
                        :options="{ prefix: '', suffix: ' VND', decimal: ',', thousand: '.', precision: 0, }"
                        required />
                </div>
                <div class="col-md-4">
                    <label class="form-label">Số tiền chuyển khoản</label>
                    <input type="text" class="form-control" :value="formatCurrency(transferAmount)" readonly>
                </div>
                <div class="col-md-4">
                    <label class="form-label">Tổng tiền cần thu</label>
                    <input type="text" class="form-control" :value="formatCurrency(totalAmountDue)" readonly>
                </div>
            </div>
            <div class="mb-3">
                <label class="form-label">Ghi chú</label>
                <textarea class="form-control" v-model="collectData.note" rows="3"></textarea>
            </div>

            <div class="d-flex justify-content-end gap-2">
                <button type="button" class="btn btn-secondary" @click="handleClose">Đóng</button>
                <button type="submit" class="btn btn-primary" :disabled="isSubmitting">
                    Xác nhận
                </button>
            </div>
        </div>
    </form>
</template>

<script setup>
import { ref, computed, watch, reactive } from 'vue'
import { formatCurrency } from '@/infrastructure/utilities/currencyHelper';
import LoadingOverlay from '@/components/loaders/LoadingOverlay.vue'
import cashierService from '@/services/cashierService'

const props = defineProps({
    cashier: {
        type: Object,
        required: true
    }
})

const emit = defineEmits(['close'])
const isLoading = ref(false)
const isSubmitting = ref(false)
const form = ref(null)

const collectData = reactive({
    cashAmount: 0,
    transferAmount: 0,
    note: ''
})

const totalAmountDue = computed(() => {
    return props.cashier?.OrderList.reduce((total, order) => {
        return total + (order.SourceFee || 0) + (order.DestFee || 0) + (order.CodAmount || 0);
    }, 0);
})

const transferAmount = computed(() => {
    console.log(totalAmountDue.value, collectData.cashAmount);
    return Math.max(0, totalAmountDue.value - (collectData.cashAmount || 0));
});

// Reset form khi cashier thay đổi
watch(() => props.cashier, () => {
    Object.assign(collectData, {
        cashAmount: 0,
        transferAmount: 0,
        note: ''
    })
}, { deep: true })

// watch(() => collectData.cashAmount, (newVal) => {
//     collectData.cashAmount = parseInt(newVal.replace(/\D/g, ''), 10) || 0;
// });

const handleClose = () => {
    emit('close')
}

const handleCollect = async () => {
    if (isSubmitting.value) return;

    try {
        if (totalAmountDue.value > (props.cashier?.shippingFee + props.cashier?.codAmount)) {
            alert('Số tiền nhận không được lớn hơn tổng tiền cần thu!')
            return
        }
        isSubmitting.value = true
        isLoading.value = true

        const collectRequest = {
            FromUserId: props.cashier.Id,
            CashAmount: collectData.cashAmount,
            TransferAmount: transferAmount.value,
            TotalAmount: totalAmountDue.value,
            Note: collectData.note,
            OrderList: props.cashier.OrderList.map(order => ({
                Id: order.Id,
                Code: order.Code,
                SourceFee: order.SourceFee,
                DestFee: order.DestFee,
                CodAmount: order.CodAmount
            }))
        }
        //console.log(collectRequest);
        await cashierService.collect(collectRequest)
        emit('close')
    } catch (error) {
        console.error('Lỗi khi nhận tiền:', error)
    } finally {
        isLoading.value = false
        isSubmitting.value = false
    }
}

defineExpose({
    handleCollect
})
</script>