<template>
    <div>
        <!-- Breadcrumb -->
        <div class="breadcrumb-header justify-content-between">
            <div class="my-auto">
                <h4 class="page-title">Báo cáo đổ dầu theo lái xe</h4>
                <ol class="breadcrumb">
                    <li class="breadcrumb-item"><a href="/">Trang chủ</a></li>
                    <li class="breadcrumb-item"><a href="javascript:void(0);">Báo cáo</a></li>
                    <li class="breadcrumb-item active" aria-current="page">Đổ dầu theo lái xe</li>
                </ol>
            </div>
        </div>

        <!-- Bộ lọc tìm kiếm -->
        <div class="row row-sm">
            <div class="col-sm-12 col-md-12 col-lg-12 col-xl-12 grid-margin">
                <div class="card card-search shadow-none mb-3">
                    <form class="card-body" @submit.prevent="search">
                        <div class="row">
                            <div class="col-lg-3 col-md-6 mb-3">
                                <label>Khoảng thời gian</label>
                                <VueDatePicker ref="dateRangePicker" v-model="date" :enable-time-picker="false" range
                                    multi-calendars auto-apply :format="format" @update:model-value="handleDateRange">
                                    <template #left-sidebar>
                                        <DateRangeSidebar @change-date="onChangeDate"></DateRangeSidebar>
                                    </template>
                                </VueDatePicker>
                            </div>
                            <div class="col-lg-3 col-md-6 mb-3">
                                <label>Lái xe</label>
                                <v-select label="UserName" :options="drivers"
                                    v-model="searchModel.Search.PredicateObject.DriverIds"
                                    :reduce="(option) => option.Id" multiple placeholder="Chọn lái xe..."
                                    :filterable="false" @search="searchDrivers">
                                    <template v-slot:no-options="{ search, searching }">
                                        <template v-if="searching">
                                            Không có kết quả cho <em>{{ search }}</em>.
                                        </template>
                                        <span v-else style="opacity: 0.8">Gõ để tìm kiếm lái xe...</span>
                                    </template>
                                    <template v-slot:option="option">
                                        {{ option.UserName }} ({{ option.FullName }})
                                    </template>
                                    <template v-slot:selected-option="option">
                                        {{ option.UserName }} ({{ option.FullName }})
                                    </template>
                                </v-select>
                            </div>
                            <div class="col-lg-3 col-md-6 mb-3">
                                <label>Xe</label>
                                <v-select label="LicensePlate" :options="trucks"
                                    v-model="searchModel.Search.PredicateObject.TruckIds"
                                    :reduce="(option) => option.Id" multiple placeholder="Chọn xe..."
                                    :filterable="false" @search="searchTrucks">
                                    <template v-slot:no-options="{ search, searching }">
                                        <template v-if="searching">
                                            Không có kết quả cho <em>{{ search }}</em>.
                                        </template>
                                        <span v-else style="opacity: 0.8">Gõ để tìm kiếm xe...</span>
                                    </template>
                                    <template v-slot:option="option">
                                        {{ option.LicensePlate }}
                                    </template>
                                    <template v-slot:selected-option="option">
                                        {{ option.LicensePlate }}
                                    </template>
                                </v-select>
                            </div>
                            <div class="col-lg-3 col-md-6 mb-3">
                                <label>&nbsp;</label>
                                <div>
                                    <button type="submit" class="btn btn-dark" :disabled="loading">
                                        <i v-show="!loading" class="fe fe-search"></i>
                                        <span v-show="loading" class="spinner-border spinner-border-sm"></span>
                                        <span>Tìm kiếm</span>
                                    </button>
                                    <button @click="exportExcel" type="button" class="btn btn-success ms-2"
                                        :disabled="loading">
                                        <i class="fe fe-download"></i>
                                        <span>Xuất Excel</span>
                                    </button>
                                </div>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>

        <!-- Số liệu tổng quan -->
        <div class="row row-sm" v-if="reportData.TotalItem">
            <div class="col-sm-12 col-md-12 col-lg-12 col-xl-12 grid-margin">
                <div class="card shadow-none mb-3">
                    <div class="card-header">
                        <h5 class="card-title mb-0">
                            <i class="fas fa-chart-pie me-2"></i>
                            Tổng quan
                        </h5>
                    </div>
                    <div class="card-body">
                        <div class="row">
                            <!-- Tổng km chạy -->
                            <div class="col-lg-2 col-md-4 mb-3">
                                <div class="card bg-primary text-white">
                                    <div class="card-body">
                                        <h4 class="mb-1">{{
                                            formatNumber(reportData.TotalItem.TotalDistanceKm) }} km
                                        </h4>
                                        <div class="mt-2">
                                            <strong>Tổng km chạy</strong>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <!-- Số lít đổ thực tế -->
                            <div class="col-lg-2 col-md-4 mb-3">
                                <div class="card bg-info text-white">
                                    <div class="card-body">
                                        <h4 class="mb-1">{{
                                            formatDecimal(reportData.TotalItem.TotalActualLiters) }} L
                                        </h4>
                                        <div class="mt-2">
                                            <strong>Số lít đổ thực tế</strong>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <!-- Tiền đổ thực tế -->
                            <div class="col-lg-2 col-md-4 mb-3">
                                <div class="card bg-secondary text-white">
                                    <div class="card-body">
                                        <h4 class="mb-1">{{
                                            formatCurrency(reportData.TotalItem.TotalActualAmount) }}
                                        </h4>
                                        <div class="mt-2">
                                            <strong>Tiền đổ thực tế</strong>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <!-- Số lít khoán -->
                            <div class="col-lg-2 col-md-4 mb-3">
                                <div class="card bg-teal text-white">
                                    <div class="card-body">
                                        <h4 class="mb-1">{{
                                            formatDecimal(reportData.TotalItem.TotalQuotaLiters) }} L
                                        </h4>
                                        <div class="mt-2">
                                            <strong>Số lít khoán</strong>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <!-- Tiền khoán -->
                            <div class="col-lg-2 col-md-4 mb-3">
                                <div class="card bg-purple text-white">
                                    <div class="card-body">
                                        <h4 class="mb-1">{{
                                            formatCurrency(reportData.TotalItem.TotalQuotaAmount) }}
                                        </h4>
                                        <div class="mt-2">
                                            <strong>Tiền khoán</strong>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <!-- Thu nhập dầu -->
                            <div class="col-lg-2 col-md-4 mb-3">
                                <div class="card text-white"
                                    :class="reportData.TotalItem.TotalFuelIncome >= 0 ? 'bg-success' : 'bg-danger'">
                                    <div class="card-body">
                                        <h4 class="mb-1">{{
                                            formatCurrency(reportData.TotalItem.TotalFuelIncome) }}
                                        </h4>
                                        <div class="mt-2">
                                            <strong>Thu nhập dầu</strong>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Bảng danh sách chi tiết -->
        <div class="row row-sm">
            <div class="col-sm-12 col-md-12 col-lg-12 col-xl-12 grid-margin">
                <div class="card shadow-none">
                    <div class="card-header">
                        <h5 class="card-title mb-0">
                            <i class="fas fa-table me-2"></i>
                            Chi tiết theo lái xe
                        </h5>
                    </div>
                    <div class="card-body">
                        <div class="table-responsive">
                            <table class="table table-hover mg-b-0 text-md-nowrap">
                                <thead>
                                    <tr>
                                        <th class="wd-3p"></th>
                                        <th class="wd-5p">STT</th>
                                        <th class="wd-15p">Lái xe</th>
                                        <th class="wd-8p text-end">Tổng km</th>
                                        <th class="wd-12p text-end">Thực tế</th>
                                        <th class="wd-12p text-end">Khoán</th>
                                        <th class="wd-15p text-end">Thu nhập dầu</th>
                                        <th class="wd-8p text-center">Thao tác</th>
                                    </tr>
                                </thead>
                                <tbody v-if="loading">
                                    <tr>
                                        <td colspan="11" class="tx-semibold text-center text-default">
                                            <span class="spinner-border spinner-border-sm"></span>
                                        </td>
                                    </tr>
                                </tbody>
                                <tbody v-if="!loading && (!reportData.Items || reportData.Items.length <= 0)">
                                    <tr>
                                        <td colspan="11" class="tx-semibold text-center text-danger">
                                            Không tìm thấy dữ liệu!
                                        </td>
                                    </tr>
                                </tbody>
                                <tbody v-if="!loading && reportData.Items && reportData.Items.length > 0">
                                    <template v-for="(item, index) in reportData.Items" :key="item.DriverId">
                                        <!-- Driver row -->
                                        <tr class="driver-row" :class="{ 'expanded': expandedDrivers.includes(item.DriverId) }">
                                            <td class="text-center">
                                                <button v-if="item.TruckDetails && item.TruckDetails.length > 0"
                                                    class="btn btn-sm btn-link p-0" @click="toggleExpand(item.DriverId)">
                                                    <i class="fe" :class="expandedDrivers.includes(item.DriverId) ? 'fe-chevron-down' : 'fe-chevron-right'"></i>
                                                </button>
                                            </td>
                                            <td>{{ index + 1 + ((searchModel.Pagination.PageIndex - 1) *
                                                searchModel.Pagination.PageSize) }}</td>
                                            <td>
                                                <strong>{{ item.DriverUserName }}</strong>
                                                <div class="text-muted small">{{ item.DriverFullName }}</div>
                                            </td>
                                            <td class="text-end">
                                                <span class="text-primary">{{ formatNumber(item.TotalDistanceKm) }}</span>
                                            </td>
                                            <td class="text-end">
                                                <span class="text-info">{{ formatDecimal(item.TotalActualLiters) }} L</span>
                                                <div class="text-secondary small">{{ formatCurrency(item.TotalActualAmount) }}</div>
                                            </td>
                                            <td class="text-end">
                                                <span class="text-teal">{{ formatDecimal(item.TotalQuotaLiters) }} L</span>
                                                <div class="text-purple small">{{ formatCurrency(item.TotalQuotaAmount) }}</div>
                                            </td>
                                            <td class="text-end">
                                                <span class="text-muted">{{ formatDecimal(item.TotalQuotaLiters - item.TotalActualLiters) }} L</span>
                                                <div>
                                                    <strong :class="item.TotalFuelIncome >= 0 ? 'text-success' : 'text-danger'">
                                                        {{ formatCurrency(item.TotalFuelIncome) }}
                                                    </strong>
                                                </div>
                                            </td>
                                            <td class="text-center">
                                                <button class="btn btn-sm btn-success" @click="exportExcelByDriver(item)"
                                                    :disabled="exportingDriverId === item.DriverId" title="Xuất Excel">
                                                    <i v-if="exportingDriverId !== item.DriverId" class="fe fe-download"></i>
                                                    <span v-else class="spinner-border spinner-border-sm"></span>
                                                </button>
                                            </td>
                                        </tr>
                                        <!-- Truck details rows -->
                                        <template v-if="expandedDrivers.includes(item.DriverId) && item.TruckDetails">
                                            <tr v-for="(truck, truckIndex) in item.TruckDetails" :key="truck.TruckId" class="truck-detail-row">
                                                <td></td>
                                                <td class="text-muted ps-4">{{ index + 1 }}.{{ truckIndex + 1 }}</td>
                                                <td class="text-muted">
                                                    <i class="fe fe-truck me-1"></i>
                                                    {{ truck.TruckPlate }}
                                                    <div class="small">{{ truck.TruckName }}</div>
                                                </td>
                                                <td class="text-end text-muted">{{ formatNumber(truck.TotalDistanceKm) }}</td>
                                                <td class="text-end text-muted">
                                                    {{ formatDecimal(truck.TotalActualLiters) }} L
                                                    <div class="small">{{ formatCurrency(truck.TotalActualAmount) }}</div>
                                                </td>
                                                <td class="text-end text-muted">
                                                    {{ formatDecimal(truck.TotalQuotaLiters) }} L
                                                    <div class="small">{{ formatCurrency(truck.TotalQuotaAmount) }}</div>
                                                </td>
                                                <td class="text-end">
                                                    <span class="text-muted">{{ formatDecimal(truck.TotalQuotaLiters - truck.TotalActualLiters) }} L</span>
                                                    <div>
                                                        <span :class="truck.TotalFuelIncome >= 0 ? 'text-success' : 'text-danger'">
                                                            {{ formatCurrency(truck.TotalFuelIncome) }}
                                                        </span>
                                                    </div>
                                                </td>
                                                <td></td>
                                            </tr>
                                        </template>
                                    </template>
                                    <!-- Dòng tổng cộng -->
                                    <tr v-if="reportData.TotalItem" class="table-warning">
                                        <td></td>
                                        <td colspan="2"><strong>{{ reportData.TotalItem.DriverFullName }}</strong></td>
                                        <td class="text-end">
                                            <strong class="text-primary">{{ formatNumber(reportData.TotalItem.TotalDistanceKm) }}</strong>
                                        </td>
                                        <td class="text-end">
                                            <strong class="text-info">{{ formatDecimal(reportData.TotalItem.TotalActualLiters) }} L</strong>
                                            <div class="text-secondary small">{{ formatCurrency(reportData.TotalItem.TotalActualAmount) }}</div>
                                        </td>
                                        <td class="text-end">
                                            <strong class="text-teal">{{ formatDecimal(reportData.TotalItem.TotalQuotaLiters) }} L</strong>
                                            <div class="text-purple small">{{ formatCurrency(reportData.TotalItem.TotalQuotaAmount) }}</div>
                                        </td>
                                        <td class="text-end">
                                            <span class="text-muted">{{ formatDecimal(reportData.TotalItem.TotalQuotaLiters - reportData.TotalItem.TotalActualLiters) }} L</span>
                                            <div>
                                                <strong :class="reportData.TotalItem.TotalFuelIncome >= 0 ? 'text-success' : 'text-danger'">
                                                    {{ formatCurrency(reportData.TotalItem.TotalFuelIncome) }}
                                                </strong>
                                            </div>
                                        </td>
                                        <td></td>
                                    </tr>
                                </tbody>
                            </table>
                        </div>

                        <!-- Pagination -->
                        <pager ref="ctrlPager" v-show="!loading && reportData.Items && reportData.Items.length > 0"
                            @PageSizeChanged="PageSizeChanged" @PageIndexChanged="PageIndexChanged"
                            :Total="searchModel.Pagination.Total"
                            :TotalCurrent="reportData.Items ? reportData.Items.length : 0"></pager>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import reportService from "@/services/reportService";
import staffService from "@/services/staffService";
import truckService from "@/services/truckService";
import VueDatePicker from '@vuepic/vue-datepicker';
import { DateRangeSidebar, Pager } from '@/components/index';
import { useToast } from "vue-toastification";
import _ from 'lodash';

const toast = useToast();

//#region DATA
const loading = ref(false);
const exportingDriverId = ref(null);
const expandedDrivers = reactive([]);
const date = ref();
const dateRangePicker = ref(VueDatePicker);
const ctrlPager = ref(Pager);

const drivers = reactive([]);
const trucks = reactive([]);

const reportData = reactive({
    Items: [],
    TotalItem: null,
    TotalRecord: 0,
    Result: 0,
    Message: ""
});

// Search model
const searchModel = reactive({
    Pagination: {
        Total: 0,
        PageIndex: 1,
        PageSize: 25
    },
    Sort: {
        Predicate: 'DriverFullName',
        Reverse: false
    },
    Search: {
        PredicateObject: {
            StartDate: null,
            EndDate: null,
            DriverIds: [],
            TruckIds: []
        }
    }
});
//#endregion

//#region FUNCTIONS
function formatNumber(value) {
    if (value == null || value == undefined) return '0';
    return new Intl.NumberFormat('vi-VN').format(value);
}

function formatDecimal(value) {
    if (value == null || value == undefined) return '0.00';
    return new Intl.NumberFormat('vi-VN', {
        minimumFractionDigits: 2,
        maximumFractionDigits: 2
    }).format(value);
}

function formatCurrency(value) {
    if (value == null || value == undefined) return '0 ₫';
    return new Intl.NumberFormat('vi-VN', {
        style: 'currency',
        currency: 'VND'
    }).format(value);
}

const format = (dates) => {
    if (!dates || dates.length !== 2) return '';
    const start = dates[0];
    const end = dates[1];
    const dayStart = start.getDate();
    const monthStart = start.getMonth() + 1;
    const yearStart = start.getFullYear();
    const dayEnd = end.getDate();
    const monthEnd = end.getMonth() + 1;
    const yearEnd = end.getFullYear();

    return `${dayStart}/${monthStart}/${yearStart} - ${dayEnd}/${monthEnd}/${yearEnd}`;
}

async function search() {
    searchModel.Pagination.PageIndex = 1;
    if (ctrlPager.value && ctrlPager.value.Refresh) {
        ctrlPager.value.Refresh();
    }
    await loadData();
}

async function loadData() {
    loading.value = true;
    try {
        const result = await reportService.getFuelRefillReportByDriver(searchModel);
        if (result && result.Result === 1) {
            // Clear existing data
            reportData.Items.splice(0, reportData.Items.length);

            // Update data
            if (result.Items && result.Items.length > 0) {
                result.Items.forEach(item => {
                    reportData.Items.push(item);
                });
            }

            reportData.TotalItem = result.TotalItem;
            reportData.TotalRecord = result.TotalRecord;
            reportData.Result = result.Result;
            reportData.Message = result.Message;
            searchModel.Pagination.Total = result.TotalRecord;
        } else {
            toast.error('Lỗi: ' + (result.Message || 'Không thể tải dữ liệu'));
        }
    } catch (error) {
        console.error('Error loading report data:', error);
        toast.error('Có lỗi xảy ra khi tải dữ liệu');
    } finally {
        loading.value = false;
    }
}

function handleDateRange(modelData) {
    if (modelData != null) {
        const endDate = modelData[1];
        const startDate = modelData[0];

        searchModel.Search.PredicateObject.StartDate = startDate;
        searchModel.Search.PredicateObject.EndDate = endDate;
    } else {
        searchModel.Search.PredicateObject.StartDate = null;
        searchModel.Search.PredicateObject.EndDate = null;
    }
}

async function onChangeDate(newDates) {
    date.value = newDates;
    dateRangePicker.value.closeMenu();
    handleDateRange(newDates);
}

async function exportExcel() {
    loading.value = true;
    try {
        const result = await reportService.exportFuelRefillReportByDriver(searchModel);
        if (result && result.Result === 1) {
            toast.success('Xuất file Excel thành công');
            // Download file
            if (result.DownloadUrl) {
                window.open(result.DownloadUrl, '_blank');
            }
        } else {
            toast.error('Lỗi: ' + (result.Message || 'Không thể xuất file Excel'));
        }
    } catch (error) {
        console.error('Error exporting Excel:', error);
        toast.error('Có lỗi xảy ra khi xuất file Excel');
    } finally {
        loading.value = false;
    }
}

async function exportExcelByDriver(driver) {
    exportingDriverId.value = driver.DriverId;
    try {
        // Create search model for specific driver
        const exportModel = JSON.parse(JSON.stringify(searchModel));
        exportModel.Search.PredicateObject.DriverIds = [driver.DriverId];
        
        const result = await reportService.exportFuelRefillReportByDriver(exportModel);
        if (result && result.Result === 1) {
            toast.success(`Xuất file Excel cho ${driver.DriverFullName} thành công`);
            if (result.DownloadUrl) {
                window.open(result.DownloadUrl, '_blank');
            }
        } else {
            toast.error('Lỗi: ' + (result.Message || 'Không thể xuất file Excel'));
        }
    } catch (error) {
        console.error('Error exporting Excel by driver:', error);
        toast.error('Có lỗi xảy ra khi xuất file Excel');
    } finally {
        exportingDriverId.value = null;
    }
}

function toggleExpand(driverId) {
    const index = expandedDrivers.indexOf(driverId);
    if (index === -1) {
        expandedDrivers.push(driverId);
    } else {
        expandedDrivers.splice(index, 1);
    }
}

function PageSizeChanged(pagesize) {
    searchModel.Pagination.PageSize = pagesize;
    searchModel.Pagination.PageIndex = 1;
    loadData();
}

function PageIndexChanged(pageIndex) {
    searchModel.Pagination.PageIndex = pageIndex;
    loadData();
}

const searchDrivers = async (keyword, loading) => {
    if (keyword && keyword.length > 0) {
        if (loading) loading(true);
        await searchDriversDebounce(loading, keyword);
    }
};

const searchDriversDebounce = _.debounce(async (loading, keyword) => {
    try {
        const result = await staffService.sugDriver(keyword);
        if (result != null && result.length > 0) {
            drivers.splice(0, drivers.length);
            result.forEach(driver => {
                drivers.push(driver);
            });
        }
    } catch (error) {
        console.error('Error searching drivers:', error);
    } finally {
        if (loading) loading(false);
    }
}, 500);

const searchTrucks = async (keyword, loading) => {
    // Filter trucks locally from pre-loaded list
    if (keyword && keyword.length > 0 && allTrucks.length > 0) {
        const filteredTrucks = allTrucks.filter(truck => 
            truck.LicensePlate.toLowerCase().includes(keyword.toLowerCase())
        );
        trucks.splice(0, trucks.length);
        filteredTrucks.forEach(truck => {
            trucks.push(truck);
        });
    }
};

// Store all trucks for local filtering
const allTrucks = reactive([]);

async function loadTrucks() {
    try {
        const result = await truckService.getTrucksByAgency();
        if (result != null && result.length > 0) {
            allTrucks.splice(0, allTrucks.length);
            trucks.splice(0, trucks.length);
            result.forEach(truck => {
                allTrucks.push(truck);
                trucks.push(truck);
            });
        }
    } catch (error) {
        console.error('Error loading trucks:', error);
    }
}
//#endregion

onMounted(async () => {
    // Set default date range (last 30 days)
    const endDate = new Date();
    const startDate = new Date();
    startDate.setDate(startDate.getDate() - 30);

    date.value = [startDate, endDate];
    handleDateRange([startDate, endDate]);

    // Load trucks for filter
    await loadTrucks();

    // Load initial data
    await search();
});
</script>

<style scoped>
.card {
    border-radius: 8px;
}

.badge {
    font-size: 0.875rem;
    padding: 0.5rem 0.75rem;
}

.table th {
    border-top: none;
    font-weight: 600;
    background-color: #f8f9fa;
}

.table-warning {
    background-color: rgba(255, 193, 7, 0.1);
}

.card-header {
    background-color: #f8f9fa;
    border-bottom: 1px solid #dee2e6;
}

.card-title {
    color: #495057;
    font-weight: 600;
}

.bg-teal {
    background-color: #20c997 !important;
}

.text-teal {
    color: #20c997 !important;
}

.bg-purple {
    background-color: #6f42c1 !important;
}

.text-purple {
    color: #6f42c1 !important;
}

/* Expand/Collapse styles */
.driver-row {
    cursor: pointer;
    transition: background-color 0.2s ease;
}

.driver-row:hover {
    background-color: rgba(0, 123, 255, 0.05);
}

.driver-row.expanded {
    background-color: rgba(0, 123, 255, 0.08);
}

.truck-detail-row {
    background-color: #f8f9fa;
    font-size: 0.9em;
}

.truck-detail-row:hover {
    background-color: #e9ecef;
}

.btn-link {
    color: #495057;
}

.btn-link:hover {
    color: #007bff;
}
</style>
