<template>
    <div>
        <!-- Breadcrumb -->
        <div class="breadcrumb-header justify-content-between">
            <div class="my-auto">
                <h4 class="page-title">Báo cáo năng suất lái xe theo ngày</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">Năng suất 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-4 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-4 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-4 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.DriverProductivityTotalItem">
            <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 số đơn lấy hàng -->
                            <div class="col-lg-4 col-md-6 mb-3">
                                <div class="card bg-primary text-white">
                                    <div class="card-body">
                                        <h4 class="mb-1">{{
                                            formatNumber(reportData.DriverProductivityTotalItem.PickupCount) }}
                                        </h4>
                                        <div class="mt-2">
                                            <strong>Tổng số đơn lấy hàng</strong>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <!-- Tổng số đơn giao hàng -->
                            <div class="col-lg-4 col-md-6 mb-3">
                                <div class="card bg-success text-white">
                                    <div class="card-body">
                                        <h4 class="mb-1">{{
                                            formatNumber(reportData.DriverProductivityTotalItem.DeliveryCount)
                                        }}</h4>
                                        <div class="mt-2">
                                            <strong>Tổng số đơn giao hàng</strong>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <!-- Tổng cộng -->
                            <div class="col-lg-4 col-md-6 mb-3">
                                <div class="card bg-info text-white">
                                    <div class="card-body">
                                        <h4 class="mb-1">{{
                                            formatNumber(reportData.DriverProductivityTotalItem.TotalCount) }}
                                        </h4>
                                        <div class="mt-2">
                                            <strong>Tổng số đơn hàng</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 năng suấ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-5p"></th>
                                        <th class="wd-5p">STT</th>
                                        <th class="wd-15p">Mã lái xe</th>
                                        <th class="wd-20p">Tên lái xe</th>
                                        <th class="wd-12p text-center">Số đơn lấy hàng</th>
                                        <th class="wd-12p text-center">Số đơn giao hàng</th>
                                        <th class="wd-12p text-center">Tổng số đơn</th>
                                    </tr>
                                </thead>
                                <tbody v-if="loading">
                                    <tr>
                                        <td colspan="7" 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="7" class="tx-semibold text-center text-danger">
                                            Không tìm thấy dữ liệu!
                                        </td>
                                    </tr>
                                </tbody>
                                <template v-if="!loading && reportData.Items && reportData.Items.length > 0">
                                    <tbody v-for="(item, index) in reportData.Items" :key="item.DriverId">
                                        <!-- Dòng tổng hợp theo lái xe -->
                                        <tr class="driver-group-row"
                                            :class="{ 'expanded': expandedDrivers[item.DriverId] }">
                                            <td class="text-center">
                                                <button v-if="item.DailyDetails && item.DailyDetails.length > 0"
                                                    @click="toggleDriver(item.DriverId)" class="btn btn-sm btn-link p-0"
                                                    type="button">
                                                    <i v-if="!expandedDrivers[item.DriverId]"
                                                        class="fe fe-chevron-right"></i>
                                                    <i v-else class="fe fe-chevron-down"></i>
                                                </button>
                                            </td>
                                            <td><strong>{{ index + 1 + ((searchModel.Pagination.PageIndex - 1) *
                                                searchModel.Pagination.PageSize) }}</strong></td>
                                            <td>
                                                <strong>{{ item.DriverUserName }}</strong>
                                            </td>
                                            <td>
                                                <strong>{{ item.DriverFullName }}</strong>
                                            </td>
                                            <td class="text-center">
                                                <div class="fw-bold text-primary">{{ formatNumber(item.PickupCount) }}
                                                </div>
                                            </td>
                                            <td class="text-center">
                                                <div class="fw-bold text-success">{{ formatNumber(item.DeliveryCount) }}
                                                </div>
                                            </td>
                                            <td class="text-center">
                                                <div class="fw-bold text-info">{{ formatNumber(item.TotalCount) }}</div>
                                            </td>
                                        </tr>

                                        <!-- Chi tiết theo từng ngày -->
                                        <template
                                            v-if="expandedDrivers[item.DriverId] && item.DailyDetails && item.DailyDetails.length > 0">
                                            <tr v-for="detail in item.DailyDetails"
                                                :key="`${item.DriverId}-${detail.ActivityDate}`"
                                                class="daily-detail-row">
                                                <td></td>
                                                <td colspan="3" class="ps-5">
                                                    <i class="fe fe-calendar me-2 text-muted"></i>
                                                    <span class="text-muted">{{ formatDate(detail.ActivityDate)
                                                        }}</span>
                                                    <span class="badge bg-secondary ms-2">{{ detail.DayOfWeek }}</span>
                                                </td>
                                                <td class="text-center">
                                                    <span class="text-primary">{{ formatNumber(detail.PickupCount)
                                                        }}</span>
                                                </td>
                                                <td class="text-center">
                                                    <span class="text-success">{{ formatNumber(detail.DeliveryCount)
                                                        }}</span>
                                                </td>
                                                <td class="text-center">
                                                    <span class="text-info">{{ formatNumber(detail.TotalCount) }}</span>
                                                </td>
                                            </tr>
                                        </template>
                                    </tbody>

                                    <!-- Dòng tổng cộng -->
                                    <tbody v-if="reportData.DriverProductivityTotalItem">
                                        <tr class="table-warning">
                                            <td></td>
                                            <td colspan="3"><strong>{{
                                                reportData.DriverProductivityTotalItem.DriverFullName
                                                    }}</strong></td>
                                            <td class="text-center">
                                                <div class="fw-bold text-primary">{{
                                                    formatNumber(reportData.DriverProductivityTotalItem.PickupCount) }}
                                                </div>
                                            </td>
                                            <td class="text-center">
                                                <div class="fw-bold text-success">{{
                                                    formatNumber(reportData.DriverProductivityTotalItem.DeliveryCount)
                                                    }}</div>
                                            </td>
                                            <td class="text-center">
                                                <div class="fw-bold text-info">{{
                                                    formatNumber(reportData.DriverProductivityTotalItem.TotalCount) }}
                                                </div>
                                            </td>
                                        </tr>
                                    </tbody>
                                </template>
                            </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"; // Changed from userService
import VueDatePicker from '@vuepic/vue-datepicker';
import { DateRangeSidebar, Pager } from '@/components/index';
import { useToast } from "vue-toastification";
import _ from 'lodash'; // Added lodash

const toast = useToast();

//#region DATA
const loading = ref(false);
const date = ref();
const dateRangePicker = ref(VueDatePicker);
const ctrlPager = ref(Pager);

const drivers = reactive([]);

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

// Track expanded drivers
const expandedDrivers = reactive({});

// Search model
const searchModel = reactive({
    Pagination: {
        Total: 0,
        PageIndex: 1,
        PageSize: 10,
        From: 0
    },
    Sort: {
        Predicate: 'TotalCount',
        Reverse: true
    },
    Search: {
        PredicateObject: {
            FromDate: null,
            ToDate: null,
            DriverIds: []
        }
    },
    IsExport: false
});
//#endregion

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

function formatDate(dateString) {
    if (!dateString) return '';
    const date = new Date(dateString);
    const day = date.getDate().toString().padStart(2, '0');
    const month = (date.getMonth() + 1).toString().padStart(2, '0');
    const year = date.getFullYear();
    return `${day}/${month}/${year}`;
}

function toggleDriver(driverId) {
    expandedDrivers[driverId] = !expandedDrivers[driverId];
}

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;
    searchModel.Pagination.From = 0;
    if (ctrlPager.value && ctrlPager.value.Refresh) {
        ctrlPager.value.Refresh();
    }
    await loadData();
}

async function loadData() {
    loading.value = true;
    try {
        // Tính From từ PageIndex và PageSize
        searchModel.Pagination.From = (searchModel.Pagination.PageIndex - 1) * searchModel.Pagination.PageSize;

        const result = await reportService.getDriverProductivityByDate(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.DriverProductivityTotalItem = result.DriverProductivityTotalItem;
            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];

        // Chuyển sang DateTimeOffset format cho API
        searchModel.Search.PredicateObject.FromDate = startDate;
        searchModel.Search.PredicateObject.ToDate = endDate;
    } else {
        searchModel.Search.PredicateObject.FromDate = null;
        searchModel.Search.PredicateObject.ToDate = null;
    }
}

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

function exportExcel() {
    toast.info('Chức năng xuất Excel đang được phát triển');
}

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);
//#endregion

onMounted(async () => {
    // Set default date range (current month)
    const endDate = new Date();
    const startDate = new Date();
    startDate.setDate(1); // First day of current month

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

    // 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;
}

.driver-group-row {
    background-color: #f8f9fa;
    font-weight: 600;
}

.driver-group-row:hover {
    background-color: #e9ecef;
}

.driver-group-row.expanded {
    background-color: #e7f3ff;
}

.daily-detail-row {
    background-color: #ffffff;
}

.daily-detail-row:hover {
    background-color: #f8f9fa;
}

.btn-link {
    text-decoration: none;
    color: #495057;
}

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