<template>
    <div class="driver-finance-form">
        <h2>Thông tin tài chính lái xe</h2>
        <div class="cash-info">
            <label>Tổng tiền lái xe đang cầm:</label>
            <span>{{ formatCurrency(cash) }}</span>
        </div>
        <div class="orders-list">
            <h3>Danh sách đơn hàng gần nhất</h3>
            <table v-if="orders.length">
                <thead>
                    <tr>
                        <th>Mã đơn hàng</th>
                        <th>Phí nguồn</th>
                        <th>Tổng tiền</th>
                        <th>Ngày tạo</th>
                        <th>Ghi chú</th>
                    </tr>
                </thead>
                <tbody>
                    <tr v-for="order in orders" :key="order.OrderId">
                        <td>{{ order.OrderCode }}</td>
                        <td>{{ formatCurrency(order.SourceFee) }}</td>
                        <td>{{ formatCurrency(order.TotalAmount) }}</td>
                        <td>{{ formatDate(order.CreatedDate) }}</td>
                        <td>{{ order.Note }}</td>
                    </tr>
                </tbody>
            </table>
            <div v-else>Không có đơn hàng nào.</div>
            <button class="all-orders-btn" @click="showAllOrders = true">Tất cả đơn hàng</button>
        </div>

        <!-- Sử dụng LadaDialog để hiển thị modal tất cả đơn hàng -->
        <LadaDialog :visible="showAllOrders" @close="showAllOrders = false">
            <template #header>
                <div class="modal-header">
                    <h3 class="modal-title">Danh sách tất cả đơn hàng</h3>
                    <button @click="showAllOrders = false" type="button" class="close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
            </template>
            <template #body>
                <form class="filter-form" @submit.prevent="onSearchAllOrders">
                    <div class="filter-row">
                        <input type="text" v-model="searchModel.Search.PredicateObject.Keyword"
                            placeholder="Từ khóa mã đơn hàng..." class="filter-input" />
                        <input type="date" v-model="searchModel.Search.PredicateObject.CreatedStart"
                            class="filter-input" />
                        <input type="date" v-model="searchModel.Search.PredicateObject.CreatedEnd"
                            class="filter-input" />
                        <select v-model="searchModel.Search.PredicateObject.Status" class="filter-input">
                            <option :value="null">Tất cả trạng thái</option>
                            <option value="1">Đã thu</option>
                            <option value="0">Chưa thu</option>
                        </select>
                        <button type="submit" class="filter-btn">Tìm kiếm</button>
                    </div>
                </form>
                <div v-if="allOrders.length">
                    <table>
                        <thead>
                            <tr>
                                <th>Mã đơn hàng</th>
                                <th>Phí nguồn</th>
                                <th>Phí đích</th>
                                <th>Tổng tiền</th>
                                <th>Trạng thái</th>
                                <th>Người thanh toán</th>
                                <th>Ngày tạo</th>
                                <th>Người tạo</th>
                                <th>Địa chỉ gửi</th>
                                <th>Địa chỉ nhận</th>
                                <th>Ghi chú</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr v-for="order in allOrders" :key="order.OrderId">
                                <td>{{ order.OrderCode }}</td>
                                <td>{{ formatCurrency(order.SourceFee) }}</td>
                                <td>{{ formatCurrency(order.DestFee) }}</td>
                                <td>{{ formatCurrency(order.TotalAmount) }}</td>
                                <td>{{ order.StatusStr }}</td>
                                <td>{{ order.PayFeeTypeStr }}</td>
                                <td>{{ order.CreatedDateStr || formatDate(order.CreatedDate) }}</td>
                                <td>{{ order.CreatedByUserName }}</td>
                                <td>{{ order.SourceAddress }}</td>
                                <td>{{ order.DestAddress }}</td>
                                <td>{{ order.Note }}</td>
                            </tr>
                        </tbody>
                    </table>
                    <!-- Phân trang -->
                    <div class="pagination-bar">
                        <span>Tổng: {{ totalRecords }} đơn hàng</span>
                        <button :disabled="searchModel.Pagination.PageIndex === 1"
                            @click="changePage(searchModel.Pagination.PageIndex - 1)">&lt;</button>
                        <span>Trang {{ searchModel.Pagination.PageIndex }} / {{ totalPages }}</span>
                        <button :disabled="searchModel.Pagination.PageIndex === totalPages"
                            @click="changePage(searchModel.Pagination.PageIndex + 1)">&gt;</button>
                        <select v-model.number="searchModel.Pagination.PageSize" @change="changePageSize">
                            <option :value="10">10</option>
                            <option :value="20">20</option>
                            <option :value="50">50</option>
                        </select>
                        <span>/ trang</span>
                    </div>
                </div>
                <div v-else>Không có đơn hàng nào.</div>
            </template>
        </LadaDialog>
    </div>
</template>

<script setup>
import { ref, onMounted, watchEffect, computed } from 'vue';
import driverFinanceService from '@/services/driverFinanceService';
import { LadaDialog } from '@/components/index';

const cash = ref(0);
const orders = ref([]);
const showAllOrders = ref(false);
const allOrders = ref([]);
const totalRecords = ref(0);

// Khai báo searchModel với các trường filter cơ bản
const searchModel = ref({
    Pagination: {
        Total: 0,
        PageIndex: 1,
        PageSize: 20
    },
    Sort: {
        Predicate: '',
        Reverse: true
    },
    Search: {
        PredicateObject: {
            Keyword: '',
            CreatedStart: '',
            CreatedEnd: '',
            Status: null
        }
    }
});

const totalPages = computed(() => {
    return Math.max(1, Math.ceil(totalRecords.value / searchModel.value.Pagination.PageSize));
});

function formatCurrency(value) {
    if (!value) return '0 đ';
    return Number(value).toLocaleString('vi-VN') + ' đ';
}
function formatDate(dateStr) {
    if (!dateStr) return '';
    return new Date(dateStr).toLocaleString('vi-VN');
}

async function fetchFinanceInfo() {
    try {
        const res = await driverFinanceService.getDriverFinanceInfo();
        cash.value = res.TotalAmount || 0;
        orders.value = res.RecentOrders || [];
    } catch (e) {
        cash.value = 0;
        orders.value = [];
    }
}

async function fetchAllOrders() {
    const res = await driverFinanceService.searchAllOrders(searchModel.value);
    allOrders.value = res.Items || [];
    totalRecords.value = res.TotalRecord || 0;
}

function onSearchAllOrders() {
    searchModel.value.Pagination.PageIndex = 1;
    fetchAllOrders();
}

function changePage(page) {
    searchModel.value.Pagination.PageIndex = page;
    fetchAllOrders();
}

function changePageSize() {
    searchModel.value.Pagination.PageIndex = 1;
    fetchAllOrders();
}

onMounted(fetchFinanceInfo);

// Theo dõi showAllOrders để load dữ liệu khi mở
watchEffect(() => {
    if (showAllOrders.value) {
        fetchAllOrders();
    }
});
</script>

<style scoped>
.driver-finance-form {
    max-width: 600px;
    margin: 0 auto;
    background: #fff;
    padding: 24px;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.cash-info {
    margin-bottom: 16px;
    font-size: 18px;
}

.orders-list table {
    width: 100%;
    border-collapse: collapse;
}

.orders-list th,
.orders-list td {
    border: 1px solid #eee;
    padding: 8px 12px;
    text-align: left;
}

.orders-list th {
    background: #f5f5f5;
}

.all-orders-btn {
    margin-top: 16px;
    padding: 8px 16px;
    background: #007bff;
    color: #fff;
    border: none;
    border-radius: 4px;
    cursor: pointer;
}

.filter-form {
    margin-bottom: 16px;
}

.filter-row {
    display: flex;
    gap: 8px;
    align-items: center;
}

.filter-input {
    padding: 6px 8px;
    border: 1px solid #ccc;
    border-radius: 4px;
}

.filter-btn {
    padding: 6px 16px;
    background: #28a745;
    color: #fff;
    border: none;
    border-radius: 4px;
    cursor: pointer;
}

.pagination-bar {
    display: flex;
    align-items: center;
    gap: 8px;
    margin-top: 12px;
}
</style>