<template>
    <div>
        <!-- Breadcrumb -->
        <div class="breadcrumb-header justify-content-between">
            <div class="my-auto">
                <h4 class="page-title">Báo cáo đơn hàng theo tuyến</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 hàng theo tuyến</li>
                </ol>
            </div>
        </div>

        <!-- Search Form -->
        <div class="row row-sm">
            <div class="col-lg-12">
                <div class="card shadow-none">
                    <div class="card-header">
                        <h5 class="card-title mb-0">
                            <i class="fas fa-search me-2"></i>
                            Tìm kiếm
                        </h5>
                    </div>
                    <div class="card-body">
                        <div class="row">
                            <!-- Date Range -->
                            <div class="col-lg-4 col-md-6 mb-3">
                                <label class="form-label">Thời gian</label>
                                <VueDatePicker ref="dateRangePicker" v-model="date" :enable-time-picker="false" range
                                    multi-calendars auto-apply :format="format" @update:model-value="handleDate">
                                    <template #left-sidebar>
                                        <DateRangeSidebar @change-date="onChangeDate"></DateRangeSidebar>
                                    </template>
                                </VueDatePicker>
                            </div>

                            <!-- Sale (chỉ Founder) -->
                            <div class="col-lg-4 col-md-6 mb-3" v-if="isFounder">
                                <label class="form-label">Sale</label>
                                <v-select label="FullName" :options="sales" v-model="selectedSale"
                                    :reduce="(option) => option.Id" @search="searchSale" placeholder="Chọn Sale...">
                                    <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">Nhập để tìm kiếm Sale</span>
                                    </template>
                                </v-select>
                            </div>

                            <!-- Source Cities (Multiple) -->
                            <div class="col-lg-4 col-md-6 mb-3">
                                <label class="form-label">Tỉnh/TP gửi hàng</label>
                                <v-select label="Name" :options="cities" v-model="selectedSourceCities"
                                    :reduce="(option) => option.Id" placeholder="Tất cả" multiple :filterable="false"
                                    @search="searchCities">
                                    <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...</span>
                                    </template>
                                </v-select>
                                <small class="text-muted">Có thể chọn nhiều tỉnh/thành phố</small>
                            </div>

                            <!-- Dest Cities (Multiple) -->
                            <div class="col-lg-4 col-md-6 mb-3">
                                <label class="form-label">Tỉnh/TP nhận hàng</label>
                                <v-select label="Name" :options="cities" v-model="selectedDestCities"
                                    :reduce="(option) => option.Id" placeholder="Tất cả" multiple :filterable="false"
                                    @search="searchCities">
                                    <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...</span>
                                    </template>
                                </v-select>
                                <small class="text-muted">Có thể chọn nhiều tỉnh/thành phố</small>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-12">
                                <button type="button" class="btn btn-primary me-2" @click="search" :disabled="loading">
                                    <span v-show="loading" class="spinner-border spinner-border-sm me-2"></span>
                                    <i v-show="!loading" class="fas fa-search me-2"></i>Tìm kiếm
                                </button>
                                <button type="button" class="btn btn-secondary" @click="resetSearch">
                                    <i class="fas fa-redo me-2"></i>Làm mới
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Số liệu tổng quan -->
        <div class="row row-sm" v-if="reportData.Items && reportData.Items.length > 0">
            <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">
                            <div class="col-lg-3 col-md-6 mb-3">
                                <div class="card bg-primary text-white">
                                    <div class="card-body">
                                        <h4 class="mb-1">{{ formatNumber(totalOrders) }}</h4>
                                        <p class="mb-1 small">Tổng số đơn hàng</p>
                                        <div class="mt-2">
                                            <strong>Doanh thu: {{ formatCurrency(totalRevenue) }}</strong>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="col-lg-3 col-md-6 mb-3">
                                <div class="card bg-info text-white">
                                    <div class="card-body">
                                        <h4 class="mb-1">{{ formatNumber(uniqueRoutes) }}</h4>
                                        <p class="mb-1 small">Số tuyến</p>
                                        <div class="mt-2">
                                            <strong>Trung bình: {{ formatCurrency(avgRevenuePerRoute) }}/tuyến</strong>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="col-lg-3 col-md-6 mb-3">
                                <div class="card bg-success text-white">
                                    <div class="card-body">
                                        <h4 class="mb-1">{{ formatCurrency(maxRevenue) }}</h4>
                                        <p class="mb-1 small">Doanh thu cao nhất</p>
                                        <div class="mt-2">
                                            <strong>{{ topRoute }}</strong>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="col-lg-3 col-md-6 mb-3">
                                <div class="card bg-warning text-white">
                                    <div class="card-body">
                                        <h4 class="mb-1">{{ formatCurrency(minRevenue) }}</h4>
                                        <p class="mb-1 small">Doanh thu thấp nhất</p>
                                        <div class="mt-2">
                                            <strong>Trung bình: {{ formatCurrency(avgRevenue) }}</strong>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Biểu đồ -->
        <div class="row row-sm" v-if="reportData.Items && reportData.Items.length > 0">
            <div class="col-lg-6 col-md-12 mb-3">
                <div class="card shadow-none">
                    <div class="card-header">
                        <h5 class="card-title mb-0">
                            <i class="fas fa-chart-bar me-2"></i>
                            Top 10 tuyến theo doanh thu
                        </h5>
                    </div>
                    <div class="card-body">
                        <v-chart ref="barChart" :option="barChartOption" style="height: 350px;"></v-chart>
                    </div>
                </div>
            </div>
            <div class="col-lg-6 col-md-12 mb-3">
                <div class="card shadow-none">
                    <div class="card-header">
                        <h5 class="card-title mb-0">
                            <i class="fas fa-chart-pie me-2"></i>
                            Phân bố trạng thái đơn hàng
                        </h5>
                    </div>
                    <div class="card-body">
                        <v-chart ref="pieChart" :option="pieChartOption" style="height: 350px;"></v-chart>
                    </div>
                </div>
            </div>
        </div>

        <!-- Bảng dữ liệu -->
        <div class="row row-sm">
            <div class="col-lg-12">
                <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 hàng theo tuyến
                        </h5>
                    </div>
                    <div class="card-body">
                        <div class="table-responsive">
                            <table class="table table-bordered table-striped">
                                <thead class="table-primary">
                                    <tr>
                                        <th class="align-middle text-center" style="min-width: 200px;">Tuyến</th>
                                        <th v-for="status in uniqueStatuses" :key="status.order" class="text-center">
                                            <span :class="getStatusBadgeClass(status.order)">{{ status.name }}</span>
                                        </th>
                                        <th class="align-middle text-center bg-light">Tổng cộng</th>
                                    </tr>
                                </thead>
                                <tbody v-if="loading">
                                    <tr>
                                        <td :colspan="2 + uniqueStatuses.length"
                                            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="2 + uniqueStatuses.length"
                                            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">
                                    <tr v-for="(route, index) in pivotedData" :key="index">
                                        <td class="align-middle">
                                            <div class="fw-bold text-primary">{{ route.routeName }}</div>
                                            <div class="small text-muted">
                                                <i class="fas fa-map-marker-alt me-1"></i>
                                                {{ route.sourceCityName }} → {{ route.destCityName }}
                                            </div>
                                        </td>
                                        <td v-for="status in uniqueStatuses" :key="`${index}-${status.order}`"
                                            class="text-center">
                                            <div class="fw-bold" :class="getStatusTextClass(status.order)">
                                                {{ formatCurrency(route.statusData[status.order]?.revenue || 0) }}
                                            </div>
                                            <div class="small text-muted">
                                                {{ formatNumber(route.statusData[status.order]?.orderCount || 0) }} đơn
                                            </div>
                                        </td>
                                        <td class="text-center align-middle bg-light">
                                            <div class="fw-bold text-primary">
                                                {{ formatCurrency(route.totalRevenue) }}
                                            </div>
                                            <div class="small text-muted">
                                                <strong>{{ formatNumber(route.totalOrders) }}</strong> đơn
                                            </div>
                                        </td>
                                    </tr>
                                </tbody>
                                <tfoot v-if="!loading && reportData.Items && reportData.Items.length > 0"
                                    class="table-warning">
                                    <tr class="fw-bold">
                                        <td class="text-center align-middle">
                                            <i class="fas fa-calculator me-2"></i>
                                            <strong>TỔNG CỘNG</strong>
                                        </td>
                                        <td v-for="status in uniqueStatuses" :key="`total-${status.order}`"
                                            class="text-center">
                                            <div class="fw-bold" :class="getStatusTextClass(status.order)">
                                                {{ formatCurrency(totalByStatus[status.order]?.revenue || 0) }}
                                            </div>
                                            <div class="small text-muted">
                                                {{ formatNumber(totalByStatus[status.order]?.orderCount || 0) }} đơn
                                            </div>
                                        </td>
                                        <td class="text-center align-middle bg-warning">
                                            <div class="fw-bold text-primary">
                                                {{ formatCurrency(grandTotalRevenue) }}
                                            </div>
                                            <div class="small text-dark">
                                                <strong>{{ formatNumber(grandTotalOrders) }}</strong> đơn
                                            </div>
                                        </td>
                                    </tr>
                                </tfoot>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed, nextTick } from 'vue';
import reportService from "@/services/reportService";
import locationService from "@/services/locationService";
import userService from "@/services/userService";
import { useUserStore } from "@/stores";
import VChart from 'vue-echarts';
import { use } from 'echarts/core';
import { CanvasRenderer } from 'echarts/renderers';
import { BarChart, PieChart } from 'echarts/charts';
import {
    TitleComponent,
    TooltipComponent,
    LegendComponent,
    GridComponent
} from 'echarts/components';
import VueDatePicker from '@vuepic/vue-datepicker';
import { DateRangeSidebar } from '@/components/index';
import { useToast } from "vue-toastification";
import moment from "moment";
import _ from 'lodash';

// Đăng ký ECharts components
use([
    CanvasRenderer,
    BarChart,
    PieChart,
    TitleComponent,
    TooltipComponent,
    LegendComponent,
    GridComponent
]);

const toast = useToast();
const userStore = useUserStore();

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

// Check if user is Founder
const isFounder = computed(() => {
    return userStore.user?.IsFounder === true;
});

// Cities data
const cities = reactive([]);

// Sales data
const sales = reactive([]);
const selectedSale = ref(null);
const selectedSourceCities = ref([]);
const selectedDestCities = ref([]);

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

// Chart refs và options
const barChart = ref();
const pieChart = ref();
const barChartOption = ref({});
const pieChartOption = ref({});

// Search model (SmartTableParam structure)
const searchModel = reactive({
    Pagination: {
        PageIndex: 1,
        PageSize: 100,
        Total: 0
    },
    Sort: {
        Predicate: '',
        Reverse: false
    },
    Search: {
        PredicateObject: {
            StartDate: null,
            EndDate: null,
            SaleId: null,
            SourceCityIds: null,
            DestCityIds: null
        }
    }
});

//#endregion

//#region COMPUTED
// Get unique statuses from data
const uniqueStatuses = computed(() => {
    if (!reportData.Items || reportData.Items.length === 0) return [];

    const statusMap = new Map();
    reportData.Items.forEach(item => {
        if (!statusMap.has(item.StatusOrder)) {
            statusMap.set(item.StatusOrder, {
                order: item.StatusOrder,
                name: item.OrderStatusName
            });
        }
    });

    // Sort by status order
    return Array.from(statusMap.values()).sort((a, b) => a.order - b.order);
});

// Pivot data: convert status rows to status columns
const pivotedData = computed(() => {
    if (!reportData.Items || reportData.Items.length === 0) return [];

    const routeMap = new Map();

    reportData.Items.forEach(item => {
        const key = item.RouteName;

        if (!routeMap.has(key)) {
            routeMap.set(key, {
                routeName: item.RouteName,
                sourceCityName: item.SourceCityName,
                destCityName: item.DestCityName,
                statusData: {},
                totalOrders: 0,
                totalRevenue: 0
            });
        }

        const route = routeMap.get(key);
        route.statusData[item.StatusOrder] = {
            orderCount: item.OrderCount,
            revenue: item.TotalRevenue
        };
        route.totalOrders += item.OrderCount || 0;
        route.totalRevenue += item.TotalRevenue || 0;
    });

    return Array.from(routeMap.values());
});

// Group data by route (legacy - kept for backward compatibility)
const groupedData = computed(() => {
    if (!reportData.Items || reportData.Items.length === 0) return [];

    const grouped = {};
    reportData.Items.forEach(item => {
        const key = item.RouteName;
        if (!grouped[key]) {
            grouped[key] = {
                routeName: item.RouteName,
                sourceCityName: item.SourceCityName,
                destCityName: item.DestCityName,
                items: []
            };
        }
        grouped[key].items.push(item);
    });

    // Sort items by StatusOrder
    Object.values(grouped).forEach(group => {
        group.items.sort((a, b) => a.StatusOrder - b.StatusOrder);
    });

    return Object.values(grouped);
});

// Summary statistics
const totalOrders = computed(() => {
    return reportData.Items.reduce((sum, item) => sum + (item.OrderCount || 0), 0);
});

const totalRevenue = computed(() => {
    // Group by route and sum total revenue per route
    const routeRevenues = {};
    reportData.Items.forEach(item => {
        if (!routeRevenues[item.RouteName]) {
            routeRevenues[item.RouteName] = 0;
        }
        routeRevenues[item.RouteName] += (item.TotalRevenue || 0);
    });
    return Object.values(routeRevenues).reduce((sum, val) => sum + val, 0);
});

const uniqueRoutes = computed(() => {
    const routes = new Set(reportData.Items.map(item => item.RouteName));
    return routes.size;
});

const avgRevenuePerRoute = computed(() => {
    if (uniqueRoutes.value === 0) return 0;
    return totalRevenue.value / uniqueRoutes.value;
});

const maxRevenue = computed(() => {
    const routeRevenues = {};
    reportData.Items.forEach(item => {
        if (!routeRevenues[item.RouteName]) {
            routeRevenues[item.RouteName] = 0;
        }
        routeRevenues[item.RouteName] += (item.TotalRevenue || 0);
    });
    return Math.max(...Object.values(routeRevenues), 0);
});

const minRevenue = computed(() => {
    const routeRevenues = {};
    reportData.Items.forEach(item => {
        if (!routeRevenues[item.RouteName]) {
            routeRevenues[item.RouteName] = 0;
        }
        routeRevenues[item.RouteName] += (item.TotalRevenue || 0);
    });
    const values = Object.values(routeRevenues);
    return values.length > 0 ? Math.min(...values) : 0;
});

const avgRevenue = computed(() => {
    if (reportData.Items.length === 0) return 0;
    return reportData.Items.reduce((sum, item) => sum + (item.AvgRevenue || 0), 0) / reportData.Items.length;
});

const topRoute = computed(() => {
    const routeRevenues = {};
    reportData.Items.forEach(item => {
        if (!routeRevenues[item.RouteName]) {
            routeRevenues[item.RouteName] = 0;
        }
        routeRevenues[item.RouteName] += (item.TotalRevenue || 0);
    });

    let maxRoute = '';
    let maxValue = 0;
    Object.entries(routeRevenues).forEach(([route, value]) => {
        if (value > maxValue) {
            maxValue = value;
            maxRoute = route;
        }
    });

    return maxRoute || 'N/A';
});

// Calculate total by status for footer
const totalByStatus = computed(() => {
    const statusTotals = {};

    reportData.Items.forEach(item => {
        const statusOrder = item.StatusOrder;
        if (!statusTotals[statusOrder]) {
            statusTotals[statusOrder] = {
                orderCount: 0,
                revenue: 0
            };
        }
        statusTotals[statusOrder].orderCount += item.OrderCount || 0;
        statusTotals[statusOrder].revenue += item.TotalRevenue || 0;
    });

    return statusTotals;
});

// Grand total orders
const grandTotalOrders = computed(() => {
    return Object.values(totalByStatus.value).reduce((sum, status) => sum + status.orderCount, 0);
});

// Grand total revenue
const grandTotalRevenue = computed(() => {
    return Object.values(totalByStatus.value).reduce((sum, status) => sum + status.revenue, 0);
});
//#endregion

//#region LIFECYCLE
onMounted(async () => {
    // Set default date range (current month)
    const start = moment().startOf('month').toDate();
    const end = moment().toDate();
    date.value = [start, end];
    handleDate(date.value);

    // Load cities
    await loadCities();

    // Search
    search();
});
//#endregion

//#region FUNCTIONS
async function loadCities() {
    try {
        // Sử dụng hàm loSug với type=3 (City), parentId=0, keyword="" để load tất cả tỉnh/thành phố
        const result = await locationService.loSug("", 3, 0);
        // API loSug trả về array trực tiếp, không có Result và Items
        if (result && Array.isArray(result) && result.length > 0) {
            cities.splice(0, cities.length);
            result.forEach(city => {
                cities.push(city);
            });
        }
    } catch (error) {
        console.error('Error loading cities:', error);
    }
}

async function searchCities(keyword, loading) {
    if (keyword && keyword.length > 0) {
        loading(true);
        await searchCitiesDebounce(loading, keyword);
    } else {
        // Nếu không có keyword, load tất cả tỉnh/thành phố
        await loadCities();
    }
}

let searchCitiesDebounce = _.debounce(async (loading, keyword) => {
    try {
        cities.splice(0, cities.length);
        // Sử dụng hàm loSug với type=3 (City), parentId=0 và keyword từ người dùng
        const result = await locationService.loSug(keyword, 3, 0);
        // API loSug trả về array trực tiếp, không có Result và Items
        if (result && Array.isArray(result) && result.length > 0) {
            result.forEach(city => {
                cities.push(city);
            });
        }
        loading(false);
    } catch (error) {
        console.error('Error searching cities:', error);
        loading(false);
    }
}, 500);

async function searchSale(search, loading) {
    if (search.length < 2) return;

    try {
        loading(true);
        const result = await userService.sugStaff(search);
        if (result && result.length > 0) {
            sales.splice(0, sales.length);
            result.forEach(sale => {
                sales.push(sale);
            });
        }
        loading(false);
    } catch (error) {
        console.error('Error searching sales:', error);
        loading(false);
    }
}

function formatNumber(value) {
    if (value == null || value == undefined) return '0';
    return new Intl.NumberFormat('vi-VN').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 || !Array.isArray(dates) || dates.length !== 2) return '';

    let start = dates[0];
    let 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 onChangeDate(newDates) {
    date.value = newDates;
    dateRangePicker.value.closeMenu();
    handleDate(newDates);
}

function handleDate(modelData) {
    if (modelData != null && Array.isArray(modelData) && modelData.length === 2) {
        searchModel.Search.PredicateObject.StartDate = modelData[0];
        searchModel.Search.PredicateObject.EndDate = modelData[1];
    } else {
        searchModel.Search.PredicateObject.StartDate = null;
        searchModel.Search.PredicateObject.EndDate = null;
    }
}

async function search() {
    loading.value = true;
    try {
        handleDate(date.value);

        // Set filters
        searchModel.Search.PredicateObject.SaleId = selectedSale.value;
        searchModel.Search.PredicateObject.SourceCityIds = selectedSourceCities.value.length > 0 ? selectedSourceCities.value : null;
        searchModel.Search.PredicateObject.DestCityIds = selectedDestCities.value.length > 0 ? selectedDestCities.value : null;

        const result = await reportService.getOrderReportByRoute(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.TotalRecord = result.TotalRecord;
            reportData.Result = result.Result;
            reportData.Message = result.Message;

            // Update pagination
            searchModel.Pagination.Total = result.TotalRecord;

            // Render charts after data is loaded
            await nextTick();
            renderCharts();
        } else {
            toast.error('Lỗi: ' + (result.Message || 'Không thể tải dữ liệu'));
        }
    } catch (error) {
        console.error('Error searching order report by route:', error);
        toast.error('Có lỗi xảy ra khi tải dữ liệu');
    } finally {
        loading.value = false;
    }
}

function resetSearch() {
    // Reset date to current month
    const start = moment().startOf('month').toDate();
    const end = moment().toDate();
    date.value = [start, end];
    handleDate(date.value);

    // Reset filters
    selectedSale.value = null;
    selectedSourceCities.value = [];
    selectedDestCities.value = [];

    // Search again
    search();
}

function getStatusBadgeClass(statusOrder) {
    const classes = {
        1: 'badge bg-warning text-dark',      // Chờ lấy hàng
        2: 'badge bg-info',                    // Đang lấy hàng
        3: 'badge bg-primary',                 // Đã lấy hàng
        4: 'badge bg-secondary',               // Trung chuyển
        5: 'badge bg-purple',                  // Đang giao hàng
        6: 'badge bg-success'                  // Đã giao hàng
    };
    return classes[statusOrder] || 'badge bg-light';
}

function getStatusTextClass(statusOrder) {
    const classes = {
        1: 'text-warning',      // Chờ lấy hàng
        2: 'text-info',         // Đang lấy hàng
        3: 'text-primary',      // Đã lấy hàng
        4: 'text-secondary',    // Trung chuyển
        5: 'text-purple',       // Đang giao hàng
        6: 'text-success'       // Đã giao hàng
    };
    return classes[statusOrder] || 'text-dark';
}

function renderCharts() {
    renderBarChart();
    renderPieChart();
}

function renderBarChart() {
    if (!reportData.Items || reportData.Items.length === 0) return;

    // Calculate total revenue per route
    const routeRevenues = {};
    reportData.Items.forEach(item => {
        if (!routeRevenues[item.RouteName]) {
            routeRevenues[item.RouteName] = 0;
        }
        routeRevenues[item.RouteName] += (item.TotalRevenue || 0);
    });

    // Sort and take top 10
    const sortedRoutes = Object.entries(routeRevenues)
        .sort((a, b) => b[1] - a[1])
        .slice(0, 10);

    const labels = sortedRoutes.map(([route]) => route);
    const revenueData = sortedRoutes.map(([, revenue]) => revenue);

    barChartOption.value = {
        title: {
            text: 'Top 10 tuyến theo doanh thu',
            left: 'center'
        },
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'shadow'
            },
            formatter: function (params) {
                const param = params[0];
                return param.name + '<br/>' +
                    param.marker + 'Doanh thu: ' +
                    new Intl.NumberFormat('vi-VN', {
                        style: 'currency',
                        currency: 'VND'
                    }).format(param.value);
            }
        },
        grid: {
            left: '3%',
            right: '4%',
            bottom: '20%',
            top: '15%',
            containLabel: true
        },
        xAxis: {
            type: 'category',
            data: labels,
            axisLabel: {
                rotate: 45,
                interval: 0,
                fontSize: 10
            }
        },
        yAxis: {
            type: 'value',
            min: 0,
            axisLabel: {
                formatter: function (value) {
                    return new Intl.NumberFormat('vi-VN').format(value);
                }
            }
        },
        series: [{
            name: 'Doanh thu',
            type: 'bar',
            data: revenueData,
            itemStyle: {
                color: '#007bff'
            }
        }]
    };
}

function renderPieChart() {
    if (!reportData.Items || reportData.Items.length === 0) return;

    // Calculate total orders by status
    const statusOrders = {};
    reportData.Items.forEach(item => {
        const statusName = item.OrderStatusName;
        if (!statusOrders[statusName]) {
            statusOrders[statusName] = 0;
        }
        statusOrders[statusName] += (item.OrderCount || 0);
    });

    const pieData = Object.entries(statusOrders).map(([name, value]) => ({
        name,
        value
    }));

    pieChartOption.value = {
        title: {
            text: 'Phân bố trạng thái đơn hàng',
            left: 'center'
        },
        tooltip: {
            trigger: 'item',
            formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        legend: {
            orient: 'vertical',
            left: 'left',
            top: 'middle'
        },
        series: [
            {
                name: 'Trạng thái',
                type: 'pie',
                radius: ['40%', '70%'],
                center: ['60%', '50%'],
                avoidLabelOverlap: false,
                label: {
                    show: false,
                    position: 'center'
                },
                emphasis: {
                    label: {
                        show: true,
                        fontSize: '18',
                        fontWeight: 'bold'
                    }
                },
                labelLine: {
                    show: false
                },
                data: pieData
            }
        ]
    };
}
//#endregion
</script>

<style scoped>
.badge {
    padding: 0.35rem 0.65rem;
    font-size: 0.875rem;
}

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

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

.table th {
    font-weight: 600;
    font-size: 0.875rem;
    white-space: nowrap;
}

.table td {
    vertical-align: middle;
}

.fw-bold {
    font-weight: 600;
}

.table-responsive {
    overflow-x: auto;
}

.table thead th.small {
    font-size: 0.75rem;
    padding: 0.5rem;
}

.table tbody td {
    padding: 0.75rem 0.5rem;
}

.bg-light {
    background-color: #f8f9fa !important;
    font-weight: 600;
}

.table-warning {
    background-color: #fff3cd !important;
}

.table tfoot td {
    font-weight: 700;
    font-size: 0.9rem;
    border-top: 3px double #dee2e6 !important;
}

.table tfoot .bg-warning {
    background-color: #ffc107 !important;
}
</style>
