<template>
    <div>
        <!-- Breadcrumb -->
        <div class="breadcrumb-header justify-content-between">
            <div class="my-auto">
                <h4 class="page-title">Báo cáo sản lượng đơn hàng</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">Sản lượng đơn hàng</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"
                                    :min-date="new Date('2025-08-10')">
                                    <template #left-sidebar>
                                        <DateRangeSidebar @change-date="onChangeDate"></DateRangeSidebar>
                                    </template>
                                </VueDatePicker>
                            </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.OrderProductionTotalItem">
            <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-2 col-md-4 col-sm-6 mb-3">
                                <div class="card bg-primary text-white">
                                    <div class="card-body text-center">
                                        <h3 class="mb-1">{{
                                            formatNumber(reportData.OrderProductionTotalItem.TotalOrders) }}
                                        </h3>
                                        <p class="mb-0">Tổng đơn hàng</p>
                                    </div>
                                </div>
                            </div>
                            <div class="col-lg-2 col-md-4 col-sm-6 mb-3">
                                <div class="card bg-warning text-white">
                                    <div class="card-body text-center">
                                        <h3 class="mb-1">{{
                                            formatNumber(reportData.OrderProductionTotalItem.TotalInProgress) }}
                                        </h3>
                                        <p class="mb-0">Đang xử lý</p>
                                    </div>
                                </div>
                            </div>
                            <div class="col-lg-2 col-md-4 col-sm-6 mb-3">
                                <div class="card bg-success text-white">
                                    <div class="card-body text-center">
                                        <h3 class="mb-1">{{
                                            formatNumber(reportData.OrderProductionTotalItem.TotalCompleted) }}
                                        </h3>
                                        <p class="mb-0">Hoàn thành</p>
                                    </div>
                                </div>
                            </div>
                            <div class="col-lg-2 col-md-4 col-sm-6 mb-3">
                                <div class="card bg-danger text-white">
                                    <div class="card-body text-center">
                                        <h3 class="mb-1">{{ formatNumber(reportData.OrderProductionTotalItem.Cancelled)
                                            }}</h3>
                                        <p class="mb-0">Đã hủy</p>
                                    </div>
                                </div>
                            </div>
                            <div class="col-lg-2 col-md-4 col-sm-6 mb-3">
                                <div class="card bg-info text-white">
                                    <div class="card-body text-center">
                                        <h3 class="mb-1">{{
                                            formatPercent(reportData.OrderProductionTotalItem.SuccessRate) }}%
                                        </h3>
                                        <p class="mb-0">Tỷ lệ thành công</p>
                                    </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-line me-2"></i>
                            Biểu đồ xu hướng theo ngày
                        </h5>
                    </div>
                    <div class="card-body">
                        <v-chart ref="lineChart" :option="lineChartOption" style="height: 300px;"></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-doughnut me-2"></i>
                            Phân bố trạng thái
                        </h5>
                    </div>
                    <div class="card-body">
                        <v-chart ref="doughnutChart" :option="doughnutChartOption" style="height: 300px;"></v-chart>
                    </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 ngày
                        </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-15p">Ngày</th>
                                        <th class="wd-10p text-center">Tổng đơn</th>
                                        <th class="wd-10p text-center">Chờ lấy</th>
                                        <th class="wd-10p text-center">Đang lấy</th>
                                        <th class="wd-10p text-center">Vận chuyển</th>
                                        <th class="wd-10p text-center">Đang giao</th>
                                        <th class="wd-10p text-center">Đã giao</th>
                                        <th class="wd-10p text-center">Đã hủy</th>
                                        <th class="wd-15p text-center">Tỷ lệ thành công</th>
                                    </tr>
                                </thead>
                                <tbody v-if="loading">
                                    <tr>
                                        <td colspan="9" 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="9" 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="item in reportData.Items" :key="item.OrderDateStr">
                                        <td>
                                            <strong>{{ item.OrderDateStr }}</strong>
                                        </td>
                                        <td class="text-center">
                                            <span class="badge bg-primary">{{ formatNumber(item.TotalOrders) }}</span>
                                        </td>
                                        <td class="text-center">
                                            <span class="badge bg-secondary">{{ formatNumber(item.WaitPickup) }}</span>
                                        </td>
                                        <td class="text-center">
                                            <span class="badge bg-info">{{ formatNumber(item.Picking) }}</span>
                                        </td>
                                        <td class="text-center">
                                            <span class="badge bg-warning">{{ formatNumber(item.InTransit) }}</span>
                                        </td>
                                        <td class="text-center">
                                            <span class="badge bg-dark">{{ formatNumber(item.Delivering) }}</span>
                                        </td>
                                        <td class="text-center">
                                            <span class="badge bg-success">{{ formatNumber(item.Delivered) }}</span>
                                        </td>
                                        <td class="text-center">
                                            <span class="badge bg-danger">{{ formatNumber(item.Cancelled) }}</span>
                                        </td>
                                        <td class="text-center">
                                            <div class="progress" style="height: 20px;">
                                                <div class="progress-bar bg-success" role="progressbar"
                                                    :style="`width: ${item.SuccessRate}%`"
                                                    :aria-valuenow="item.SuccessRate" aria-valuemin="0"
                                                    aria-valuemax="100">
                                                    {{ formatPercent(item.SuccessRate) }}%
                                                </div>
                                            </div>
                                        </td>
                                    </tr>
                                    <!-- Dòng tổng cộng -->
                                    <tr v-if="reportData.OrderProductionTotalItem" class="table-warning">
                                        <td><strong>{{ reportData.OrderProductionTotalItem.OrderDateStr }}</strong></td>
                                        <td class="text-center">
                                            <strong class="text-primary">{{
                                                formatNumber(reportData.OrderProductionTotalItem.TotalOrders)
                                                }}</strong>
                                        </td>
                                        <td class="text-center">
                                            <strong class="text-secondary">{{
                                                formatNumber(reportData.OrderProductionTotalItem.WaitPickup) }}</strong>
                                        </td>
                                        <td class="text-center">
                                            <strong class="text-info">{{
                                                formatNumber(reportData.OrderProductionTotalItem.Picking) }}</strong>
                                        </td>
                                        <td class="text-center">
                                            <strong class="text-warning">{{
                                                formatNumber(reportData.OrderProductionTotalItem.InTransit) }}</strong>
                                        </td>
                                        <td class="text-center">
                                            <strong class="text-dark">{{
                                                formatNumber(reportData.OrderProductionTotalItem.Delivering) }}</strong>
                                        </td>
                                        <td class="text-center">
                                            <strong class="text-success">{{
                                                formatNumber(reportData.OrderProductionTotalItem.Delivered) }}</strong>
                                        </td>
                                        <td class="text-center">
                                            <strong class="text-danger">{{
                                                formatNumber(reportData.OrderProductionTotalItem.Cancelled) }}</strong>
                                        </td>
                                        <td class="text-center">
                                            <div class="progress" style="height: 20px;">
                                                <div class="progress-bar bg-success" role="progressbar"
                                                    :style="`width: ${reportData.OrderProductionTotalItem.SuccessRate}%`"
                                                    :aria-valuenow="reportData.OrderProductionTotalItem.SuccessRate"
                                                    aria-valuemin="0" aria-valuemax="100">
                                                    <strong>{{
                                                        formatPercent(reportData.OrderProductionTotalItem.SuccessRate)
                                                        }}%</strong>
                                                </div>
                                            </div>
                                        </td>
                                    </tr>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick } from 'vue';
import reportService from "@/services/reportService";
import VChart from 'vue-echarts';
import { use } from 'echarts/core';
import { CanvasRenderer } from 'echarts/renderers';
import { LineChart, PieChart } from 'echarts/charts';
import {
    TitleComponent,
    TooltipComponent,
    LegendComponent,
    GridComponent
} from 'echarts/components';
import VueDatePicker from '@vuepic/vue-datepicker';

import { DateRangeSidebar } from '@/components/index';
import { useDatePickerStore } from "@/stores";
import { useToast } from "vue-toastification";

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

// Đăng ký components
const components = {
    VChart
};

const toast = useToast();
const datePickerStore = useDatePickerStore();

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

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

// Chart refs và options
const lineChart = ref();
const doughnutChart = ref();
const lineChartOption = ref({});
const doughnutChartOption = ref({});

// Search model
const searchModel = reactive({
    Pagination: {
        Total: 0,
        PageIndex: 1,
        PageSize: 25
    },
    Sort: {
        Predicate: '',
        Reverse: true
    },
    Search: {
        PredicateObject: {
            Keyword: '',
            StartDate: null,
            EndDate: null,
            Status: null,
            MenuType: null,
            AppType: null,
            MenuLevel: null,
            ContentType: null
        }
    }
});
//#endregion

//#region FUNCTIONS
const format = (dates) => {
    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}`;
}

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

function formatPercent(value) {
    if (value == null || value == undefined) return '0.00';
    return parseFloat(value).toFixed(2);
}

async function search() {
    loading.value = true;
    try {
        const result = await reportService.getOrderProduction(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.OrderProductionTotalItem = result.OrderProductionTotalItem;
            reportData.TotalRecord = result.TotalRecord;
            reportData.Result = result.Result;
            reportData.Message = result.Message;

            // 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 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];
        const minDate = new Date(2025, 7, 10); // Tháng 8 = 7 (tháng bắt đầu từ 0)

        if (startDate < minDate) {
            startDate.setTime(minDate.getTime()); // Set startDate = minDate
        }
        if (endDate < minDate) {
            endDate.setTime(minDate.getTime()); // Set endDate = minDate
        }
        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 onChangeDate(newDates) {
    date.value = newDates;
    dateRangePicker.value.closeMenu();
    handleDateRange(newDates);
}

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

function renderCharts() {
    renderLineChart();
    renderDoughnutChart();
}

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

    const labels = reportData.Items.map(item => item.OrderDateStr).reverse();
    const totalOrdersData = reportData.Items.map(item => item.TotalOrders).reverse();
    const deliveredData = reportData.Items.map(item => item.Delivered).reverse();
    const cancelledData = reportData.Items.map(item => item.Cancelled).reverse();

    lineChartOption.value = {
        title: {
            text: 'Xu hướng đơn hàng theo ngày',
            left: 'center'
        },
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'cross'
            }
        },
        legend: {
            data: ['Tổng đơn hàng', 'Đã giao', 'Đã hủy'],
            top: '10%'
        },
        grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            top: '20%',
            containLabel: true
        },
        xAxis: {
            type: 'category',
            boundaryGap: false,
            data: labels
        },
        yAxis: {
            type: 'value',
            min: 0
        },
        series: [
            {
                name: 'Tổng đơn hàng',
                type: 'line',
                data: totalOrdersData,
                smooth: true,
                lineStyle: {
                    color: '#36a2eb'
                },
                itemStyle: {
                    color: '#36a2eb'
                },
                areaStyle: {
                    color: 'rgba(54, 162, 235, 0.1)'
                }
            },
            {
                name: 'Đã giao',
                type: 'line',
                data: deliveredData,
                smooth: true,
                lineStyle: {
                    color: '#4bc0c0'
                },
                itemStyle: {
                    color: '#4bc0c0'
                },
                areaStyle: {
                    color: 'rgba(75, 192, 192, 0.1)'
                }
            },
            {
                name: 'Đã hủy',
                type: 'line',
                data: cancelledData,
                smooth: true,
                lineStyle: {
                    color: '#ff6384'
                },
                itemStyle: {
                    color: '#ff6384'
                },
                areaStyle: {
                    color: 'rgba(255, 99, 132, 0.1)'
                }
            }
        ]
    };
}

function renderDoughnutChart() {
    if (!reportData.OrderProductionTotalItem) return;

    const totalItem = reportData.OrderProductionTotalItem;
    const pieData = [
        { value: totalItem.WaitPickup, name: 'Chờ lấy hàng' },
        { value: totalItem.Picking, name: 'Đang lấy' },
        { value: totalItem.InTransit, name: 'Vận chuyển' },
        { value: totalItem.Delivering, name: 'Đang giao' },
        { value: totalItem.Delivered, name: 'Đã giao' },
        { value: totalItem.Cancelled, name: 'Đã hủy' }
    ];

    doughnutChartOption.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: 'horizontal',
            bottom: '5%',
            left: 'center'
        },
        color: ['#6c757d', '#17a2b8', '#ffc107', '#343a40', '#28a745', '#dc3545'],
        series: [
            {
                name: 'Trạng thái',
                type: 'pie',
                radius: ['40%', '70%'],
                center: ['50%', '45%'],
                avoidLabelOverlap: false,
                label: {
                    show: false,
                    position: 'center'
                },
                emphasis: {
                    label: {
                        show: true,
                        fontSize: '18',
                        fontWeight: 'bold'
                    }
                },
                labelLine: {
                    show: false
                },
                data: pieData
            }
        ]
    };
}
//#endregion

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

    const endDate = new Date();
    const startDate = new Date();

    // Set min date to 2025-08-10
    const minDate = new Date('2025-08-10');
    if (last30Days < minDate) {
        startDate.setDate(minDate.getDate());
    }

    date.value = [startDate, endDate];
    handleDateRange([startDate, endDate]);
    await search();
});
</script>

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

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

.progress {
    border-radius: 10px;
}

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

.echarts {
    width: 100%;
    height: 300px;
}
</style>