<template>
    <div>
        <div class="breadcrumb-header justify-content-between">
            <div class="my-auto">
                <h4 class="page-title">Quản lý người cầm cước</h4>
                <ol class="breadcrumb">
                    <li class="breadcrumb-item"><a href="javascript:void(0);">Trang chủ</a></li>
                    <li class="breadcrumb-item"><a href="javascript:void(0);">Tài chính</a></li>
                    <li class="breadcrumb-item active" aria-current="page">Quản lý người cầm cước</li>
                </ol>
            </div>
        </div>

        <!-- Bảng danh sách -->
        <div class="card">
            <LoadingOverlay v-model="isLoading" />
            <div class="card-header pb-0">
                <div class="d-flex justify-content-between align-items-center">
                    <h4 class="card-title mg-b-0">Danh sách người cầm tiền</h4>
                    <button class="btn btn-sm btn-outline-primary" @click="loadCashiers">
                        <i class="fas fa-sync-alt"></i>
                    </button>
                </div>
            </div>
            <div class="card-body">
                <empty v-if="cashiers.length <= 0" />
                <div class="table-responsive" v-else>
                    <table class="table table-hover table-bordered mg-b-0">
                        <thead>
                            <tr>
                                <th>STT</th>
                                <th>Người cầm tiền</th>
                                <th>Cước lấy</th>
                                <th>Cước giao</th>
                                <th>COD</th>
                                <th>Tổng cộng</th>
                                <th>Thao tác</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr v-for="(item, index) in cashiers" :key="item.id">
                                <td>{{ index + 1 }}</td>
                                <td>
                                    <div class="fw-bold">{{ item.FullName }}</div>
                                    <small class="text-muted">{{ item.UserName }}</small>
                                </td>
                                <td>
                                    <div class="text-warning small">{{ formatCurrency(getExpectedSourceFee(item)) }}
                                    </div>
                                    <div>{{ formatCurrency(item.SourceFeeAmount) }}</div>
                                </td>
                                <td>
                                    <div class="text-warning small">{{ formatCurrency(getExpectedDestFee(item)) }}</div>
                                    <div>{{ formatCurrency(item.DestFeeAmount) }}</div>
                                </td>
                                <td>
                                    <div class="text-warning small">{{ formatCurrency(getExpectedCod(item)) }}</div>
                                    <div>{{ formatCurrency(item.CodAmount) }}</div>
                                </td>
                                <td>
                                    <div class="text-warning small">{{ formatCurrency(getTotalExpected(item)) }}</div>
                                    <div class="fw-bold">{{ formatCurrency(item.SourceFeeAmount + item.DestFeeAmount +
                                        item.CodAmount) }}</div>
                                </td>
                                <td>
                                    <button class="btn btn-sm btn-success" @click="openCollectModal(item)">
                                        <i class="fas fa-money-bill"></i> Nhận tiền
                                    </button>
                                </td>
                            </tr>
                            <!-- Dòng tổng tiền -->
                            <tr v-if="cashiers.length > 0" class="table-total-row">
                                <td colspan="2" class="text-end fw-bold">Tổng cộng:</td>
                                <td>
                                    <div class="text-warning small">{{ formatCurrency(totalExpectedSourceFee) }}</div>
                                    <div class="fw-bold text-primary">{{ formatCurrency(totalSourceFeeAmount) }}</div>
                                </td>
                                <td>
                                    <div class="text-warning small">{{ formatCurrency(totalExpectedDestFee) }}</div>
                                    <div class="fw-bold text-primary">{{ formatCurrency(totalDestFeeAmount) }}</div>
                                </td>
                                <td>
                                    <div class="text-warning small">{{ formatCurrency(totalExpectedCod) }}</div>
                                    <div class="fw-bold text-primary">{{ formatCurrency(totalCodAmount) }}</div>
                                </td>
                                <td>
                                    <div class="text-warning small">{{ formatCurrency(totalExpectedAmount) }}</div>
                                    <div class="fw-bold text-success">{{ formatCurrency(totalAmount) }}</div>
                                </td>
                                <td></td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        <!-- Modal nhận tiền -->
        <LadaDialog :visible="showCollectModal" variant="modal-full">
            <template #header>
                <div class="modal-header">
                    <h5 class="modal-title">Nhận tiền từ {{ selectedCashier.FullName + ' (' + selectedCashier.UserName +
                        ')' }}</h5>
                </div>
            </template>

            <template #body>
                <CollectMoneyModal :cashier="selectedCashier" @close="handleClose" />
            </template>
        </LadaDialog>
    </div>
</template>

<script setup>
import { ref, onMounted, reactive, computed } from 'vue'
import CollectMoneyModal from './components/CollectMoneyModal.vue'
import cashierService from '@/services/cashierService'
// Khai báo state
const cashiers = reactive([])
const selectedCashier = ref(null)
const showCollectModal = ref(false)
const collectForm = ref(null)
const isLoading = ref(false)
const searchModel = reactive({
    Pagination: {
        Total: 0,
        PageIndex: 1,
        PageSize: 25
    },
    Sort: {
        Predicate: '',
        Reverse: true
    },
    Search: {
        PredicateObject: {
            Keyword: ''
        }
    }
});

// Computed - Tổng tiền cước lấy hàng
const totalSourceFeeAmount = computed(() => {
    return cashiers.reduce((sum, item) => sum + (item.SourceFeeAmount || 0), 0)
})

// Computed - Tổng tiền cước giao hàng
const totalDestFeeAmount = computed(() => {
    return cashiers.reduce((sum, item) => sum + (item.DestFeeAmount || 0), 0)
})

// Computed - Tổng tiền COD
const totalCodAmount = computed(() => {
    return cashiers.reduce((sum, item) => sum + (item.CodAmount || 0), 0)
})

// Computed - Tổng tiền tất cả
const totalAmount = computed(() => {
    return cashiers.reduce((sum, item) => {
        return sum + (item.SourceFeeAmount || 0) + (item.DestFeeAmount || 0) + (item.CodAmount || 0)
    }, 0)
})

// Helper functions to calculate expected amounts from OrderList
const getExpectedSourceFee = (cashier) => {
    if (!cashier.OrderList || cashier.OrderList.length === 0) return 0
    return cashier.OrderList.reduce((sum, order) => sum + (order.ExpectedSourceFee || 0), 0)
}

const getExpectedDestFee = (cashier) => {
    if (!cashier.OrderList || cashier.OrderList.length === 0) return 0
    return cashier.OrderList.reduce((sum, order) => sum + (order.ExpectedDestFee || 0), 0)
}

const getExpectedCod = (cashier) => {
    if (!cashier.OrderList || cashier.OrderList.length === 0) return 0
    return cashier.OrderList.reduce((sum, order) => sum + (order.ExpectedCod || 0), 0)
}

// Computed - Tổng tiền dự kiến
const totalExpectedSourceFee = computed(() => {
    return cashiers.reduce((sum, item) => sum + getExpectedSourceFee(item), 0)
})

const totalExpectedDestFee = computed(() => {
    return cashiers.reduce((sum, item) => sum + getExpectedDestFee(item), 0)
})

const totalExpectedCod = computed(() => {
    return cashiers.reduce((sum, item) => sum + getExpectedCod(item), 0)
})

// Helper function to get total expected amount for an item
const getTotalExpected = (cashier) => {
    return getExpectedSourceFee(cashier) + getExpectedDestFee(cashier) + getExpectedCod(cashier)
}

// Computed - Tổng tiền dự kiến tất cả
const totalExpectedAmount = computed(() => {
    return totalExpectedSourceFee.value + totalExpectedDestFee.value + totalExpectedCod.value
})

// Khởi tạo
onMounted(() => {
    loadCashiers()
})

// Load danh sách
const loadCashiers = async () => {
    try {
        // TODO: Gọi API lấy danh sách
        isLoading.value = true
        cashiers.splice(0, cashiers.length);
        var searchResult = await cashierService.search(searchModel);
        if (searchResult.Items != null && searchResult.Items.length > 0) {
            searchResult.Items.forEach(cashier => {
                cashiers.push(cashier);
            });
        }
        searchModel.Pagination.Total = searchResult.TotalRecord;
        isLoading.value = false
    } catch (error) {
        console.error('Lỗi khi tải danh sách:', error)
    }
}

// Mở modal nhận tiền
const openCollectModal = async (cashier) => {
    try {

        selectedCashier.value = cashier
        showCollectModal.value = true
    } catch (error) {
        console.error('Lỗi khi lấy thông tin chi tiết:', error)
    }
}

// Đóng modal nhận tiền và reload dữ liệu
const handleClose = async () => {
    await loadCashiers()
    closeCollectModal()
}

// Đóng modal nhận tiền
const closeCollectModal = () => {
    showCollectModal.value = false
    selectedCashier.value = null
}

// Helper functions
const formatCurrency = (value) => {
    return new Intl.NumberFormat('vi-VN', { style: 'currency', currency: 'VND' }).format(value)
}
</script>

<style scoped>
.badge {
    padding: 0.5em 1em;
}

.table-total-row {
    background-color: #f8f9fa;
    border-top: 2px solid #dee2e6;
}

.table-total-row td {
    font-size: 1.05rem;
}
</style>