<template>
    <div>
        <!-- Breadcrumb -->
        <div class="breadcrumb-header justify-content-between">
            <div class="my-auto">
                <h4 class="page-title">Báo cáo doanh thu đơ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">Doanh thu đơ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-3 col-md-6 mb-3">
                                <label>Thời gian tạo đơn</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, 7, 10)">
                                    <template #left-sidebar>
                                        <DateRangeSidebar @change-date="onChangeDate"></DateRangeSidebar>
                                    </template>
                                </VueDatePicker>
                            </div>
                            <div class="col-lg-3 col-md-6 mb-3">
                                <label>Thời gian lấy hàng</label>
                                <VueDatePicker ref="pickupDateRangePicker" v-model="pickupDate" :enable-time-picker="false" range
                                    multi-calendars auto-apply :format="format" @update:model-value="handlePickupDateRange"
                                    :min-date="new Date(2025, 7, 10)">
                                    <template #left-sidebar>
                                        <DateRangeSidebar @change-date="onChangePickupDate"></DateRangeSidebar>
                                    </template>
                                </VueDatePicker>
                            </div>
                            <div class="col-lg-3 col-md-6 mb-3">
                                <label>Thời gian giao thành công</label>
                                <VueDatePicker ref="deliveryDateRangePicker" v-model="deliveryDate" :enable-time-picker="false" range
                                    multi-calendars auto-apply :format="format" @update:model-value="handleDeliveryDateRange"
                                    :min-date="new Date(2025, 7, 10)">
                                    <template #left-sidebar>
                                        <DateRangeSidebar @change-date="onChangeDeliveryDate"></DateRangeSidebar>
                                    </template>
                                </VueDatePicker>
                            </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.OrderRevenueTotalItem">
            <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 -->
                            <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">{{
                                            formatCurrency(reportData.OrderRevenueTotalItem.TotalRevenue) }}
                                        </h4>
                                        <p class="mb-1 small card-Count">{{
                                            formatNumber(reportData.OrderRevenueTotalItem.TotalOrders) }}
                                        </p>
                                        <p class="mb-0 small tx-13">COD: {{
                                            formatCurrency(reportData.OrderRevenueTotalItem.TotalCollectAmount) }}</p>
                                        <div class="mt-2">
                                            <strong>Tổng <small>(Không bao gồm hủy)</small></strong>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <!-- Chờ lấy -->
                            <div class="col-lg-3 col-md-6 mb-3">
                                <div class="card bg-secondary text-white">
                                    <div class="card-body">
                                        <h4 class="mb-1">{{
                                            formatCurrency(reportData.OrderRevenueTotalItem.WaitPickupRevenue)
                                        }}</h4>
                                        <p class="mb-1 small card-Count">{{
                                            formatNumber(reportData.OrderRevenueTotalItem.WaitPickup) }}
                                        </p>
                                        <p class="mb-0 small tx-13">COD: {{
                                            formatCurrency(reportData.OrderRevenueTotalItem.WaitPickupCollectAmount) }}
                                        </p>
                                        <div class="mt-2">
                                            <strong>Chờ lấy</strong>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <!-- Đang lấy -->
                            <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">{{
                                            formatCurrency(reportData.OrderRevenueTotalItem.PickingRevenue) }}
                                        </h4>
                                        <p class="mb-1 small card-Count">{{
                                            formatNumber(reportData.OrderRevenueTotalItem.Picking)
                                        }}
                                        </p>
                                        <p class="mb-0 small tx-13">COD: {{
                                            formatCurrency(reportData.OrderRevenueTotalItem.PickingCollectAmount) }}</p>
                                        <div class="mt-2">
                                            <strong>Đang lấy</strong>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <!-- Đã lấy -->
                            <div class="col-lg-3 col-md-6 mb-3">
                                <div class="card bg-teal text-white">
                                    <div class="card-body">
                                        <h4 class="mb-1">{{
                                            formatCurrency(reportData.OrderRevenueTotalItem.PickedRevenue)
                                        }}</h4>
                                        <p class="mb-1 small card-Count">{{
                                            formatNumber(reportData.OrderRevenueTotalItem.Picked) }}
                                        </p>
                                        <p class="mb-0 small tx-13">COD: {{
                                            formatCurrency(reportData.OrderRevenueTotalItem.PickedCollectAmount)
                                        }}</p>
                                        <div class="mt-2">
                                            <strong>Đã lấy</strong>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <!-- Nhập kho -->
                            <div class="col-lg-3 col-md-6 mb-3">
                                <div class="card bg-purple text-white">
                                    <div class="card-body">
                                        <h4 class="mb-1">{{
                                            formatCurrency(reportData.OrderRevenueTotalItem.InWarehouseRevenue)
                                        }}</h4>
                                        <p class="mb-1 small card-Count">{{
                                            formatNumber(reportData.OrderRevenueTotalItem.InWarehouse) }}
                                        </p>
                                        <p class="mb-0 small tx-13">COD: {{
                                            formatCurrency(reportData.OrderRevenueTotalItem.InWarehouseCollectAmount)
                                        }}</p>
                                        <div class="mt-2">
                                            <strong>Nhập kho</strong>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <!-- Xuất kho -->
                            <div class="col-lg-3 col-md-6 mb-3">
                                <div class="card bg-indigo text-white">
                                    <div class="card-body">
                                        <h4 class="mb-1">{{
                                            formatCurrency(reportData.OrderRevenueTotalItem.OutWarehouseRevenue)
                                        }}</h4>
                                        <p class="mb-1 small card-Count">{{
                                            formatNumber(reportData.OrderRevenueTotalItem.OutWarehouse) }}
                                        </p>
                                        <p class="mb-0 small tx-13">COD: {{
                                            formatCurrency(reportData.OrderRevenueTotalItem.OutWarehouseCollectAmount)
                                        }}</p>
                                        <div class="mt-2">
                                            <strong>Xuất kho</strong>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <!-- Đang giao -->
                            <div class="col-lg-3 col-md-6 mb-3">
                                <div class="card bg-dark text-white">
                                    <div class="card-body">
                                        <h4 class="mb-1">{{
                                            formatCurrency(reportData.OrderRevenueTotalItem.DeliveringRevenue)
                                        }}</h4>
                                        <p class="mb-1 small card-Count">{{
                                            formatNumber(reportData.OrderRevenueTotalItem.Delivering) }}
                                        </p>
                                        <p class="mb-0 small tx-13">COD: {{
                                            formatCurrency(reportData.OrderRevenueTotalItem.DeliveringCollectAmount) }}
                                        </p>
                                        <div class="mt-2">
                                            <strong>Đang giao</strong>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <!-- Đã giao -->
                            <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(reportData.OrderRevenueTotalItem.DeliveredRevenue) }}
                                        </h4>
                                        <p class="mb-1 small card-Count">{{
                                            formatNumber(reportData.OrderRevenueTotalItem.Delivered) }}
                                        </p>
                                        <p class="mb-0 small tx-13">COD: {{
                                            formatCurrency(reportData.OrderRevenueTotalItem.DeliveredCollectAmount) }}
                                        </p>
                                        <div class="mt-2">
                                            <strong>Đã giao</strong>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <!-- Đã hủy -->
                            <div class="col-lg-3 col-md-6 mb-3">
                                <div class="card bg-danger text-white">
                                    <div class="card-body">
                                        <h4 class="mb-1">{{
                                            formatCurrency(reportData.OrderRevenueTotalItem.CancelledRevenue) }}
                                        </h4>
                                        <p class="mb-1 small card-Count">{{
                                            formatNumber(reportData.OrderRevenueTotalItem.Cancelled) }}
                                        </p>
                                        <p class="mb-0 small tx-13">COD: {{
                                            formatCurrency(reportData.OrderRevenueTotalItem.CancelledCollectAmount) }}
                                        </p>
                                        <div class="mt-2">
                                            <strong>Đã hủy</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-12 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 đồ doanh thu theo ngày
                        </h5>
                    </div>
                    <div class="card-body">
                        <v-chart ref="lineChart" :option="lineChartOption" 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 card-table 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 card-table-body">
                        <div class="table-responsive border-top">
                            <table class="table table-vcenter mb-0" style="min-height:300px">
                                <thead>
                                    <tr>
                                        <th class="wd-8p"><span>Ngày</span></th>
                                        <th class="wd-12p text-center"><span>Tổng</span></th>
                                        <th class="wd-10p text-center"><span>Chờ lấy</span></th>
                                        <th class="wd-10p text-center"><span>Đang lấy</span></th>
                                        <th class="wd-10p text-center"><span>Đã lấy</span></th>
                                        <th class="wd-10p text-center"><span>Nhập kho</span></th>
                                        <th class="wd-10p text-center"><span>Xuất kho</span></th>
                                        <th class="wd-10p text-center"><span>Đang giao</span></th>
                                        <th class="wd-10p text-center"><span>Đã giao</span></th>
                                        <th class="wd-10p text-center"><span>Đã hủy</span></th>
                                        <th class="wd-10p text-center"><span>Tỷ lệ thành công</span></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">
                                    <tr v-for="item in reportData.Items" :key="item.OrderDateStr">
                                        <td class="text-wrap align-top">
                                            <strong>{{ item.OrderDateStr }}</strong>
                                        </td>
                                        <td class="text-wrap align-top text-center">
                                            <div class="fw-bold text-primary">{{ formatCurrency(item.TotalRevenue) }}
                                            </div>
                                            <div class="small text-muted">{{ formatNumber(item.TotalOrders) }} đơn</div>
                                            <div class="small text-info">COD: {{ formatCurrency(item.TotalCollectAmount)
                                            }}
                                            </div>
                                        </td>
                                        <td class="text-wrap align-top text-center">
                                            <div class="fw-bold text-secondary">{{
                                                formatCurrency(item.WaitPickupRevenue) }}
                                            </div>
                                            <div class="small text-muted">{{ formatNumber(item.WaitPickup) }} đơn</div>
                                            <div class="small text-info">COD: {{
                                                formatCurrency(item.WaitPickupCollectAmount) }}
                                            </div>
                                        </td>
                                        <td class="text-wrap align-top text-center">
                                            <div class="fw-bold text-info">{{ formatCurrency(item.PickingRevenue) }}
                                            </div>
                                            <div class="small text-muted">{{ formatNumber(item.Picking) }} đơn</div>
                                            <div class="small text-info">COD: {{
                                                formatCurrency(item.PickingCollectAmount) }}
                                            </div>
                                        </td>
                                        <td class="text-wrap align-top text-center">
                                            <div class="fw-bold text-teal">{{ formatCurrency(item.PickedRevenue) }}
                                            </div>
                                            <div class="small text-muted">{{ formatNumber(item.Picked) }} đơn</div>
                                            <div class="small text-info">COD: {{
                                                formatCurrency(item.PickedCollectAmount) }}
                                            </div>
                                        </td>
                                        <td class="text-wrap align-top text-center">
                                            <div class="fw-bold text-purple">{{ formatCurrency(item.InWarehouseRevenue) }}
                                            </div>
                                            <div class="small text-muted">{{ formatNumber(item.InWarehouse) }} đơn</div>
                                            <div class="small text-info">COD: {{
                                                formatCurrency(item.InWarehouseCollectAmount) }}
                                            </div>
                                        </td>
                                        <td class="text-wrap align-top text-center">
                                            <div class="fw-bold text-indigo">{{ formatCurrency(item.OutWarehouseRevenue) }}
                                            </div>
                                            <div class="small text-muted">{{ formatNumber(item.OutWarehouse) }} đơn</div>
                                            <div class="small text-info">COD: {{
                                                formatCurrency(item.OutWarehouseCollectAmount) }}
                                            </div>
                                        </td>
                                        <td class="text-wrap align-top text-center">
                                            <div class="fw-bold text-dark">{{ formatCurrency(item.DeliveringRevenue) }}
                                            </div>
                                            <div class="small text-muted">{{ formatNumber(item.Delivering) }} đơn</div>
                                            <div class="small text-info">COD: {{
                                                formatCurrency(item.DeliveringCollectAmount) }}
                                            </div>
                                        </td>
                                        <td class="text-wrap align-top text-center">
                                            <div class="fw-bold text-success">{{ formatCurrency(item.DeliveredRevenue)
                                            }}</div>
                                            <div class="small text-muted">{{ formatNumber(item.Delivered) }} đơn</div>
                                            <div class="small text-info">COD: {{
                                                formatCurrency(item.DeliveredCollectAmount) }}
                                            </div>
                                        </td>
                                        <td class="text-wrap align-top text-center">
                                            <div class="fw-bold text-danger">{{ formatCurrency(item.CancelledRevenue) }}
                                            </div>
                                            <div class="small text-muted">{{ formatNumber(item.Cancelled) }} đơn</div>
                                            <div class="small text-info">COD: {{
                                                formatCurrency(item.CancelledCollectAmount) }}
                                            </div>
                                        </td>
                                        <td class="text-wrap align-top 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.OrderRevenueTotalItem" class="table-warning">
                                        <td class="text-wrap align-top"><strong>{{ reportData.OrderRevenueTotalItem.OrderDateStr }}</strong></td>
                                        <td class="text-wrap align-top text-center">
                                            <div class="fw-bold text-primary">{{
                                                formatCurrency(reportData.OrderRevenueTotalItem.TotalRevenue) }}</div>
                                            <div class="small text-muted">{{
                                                formatNumber(reportData.OrderRevenueTotalItem.TotalOrders) }} đơn</div>
                                            <div class="small text-info">COD: {{
                                                formatCurrency(reportData.OrderRevenueTotalItem.TotalCollectAmount) }}
                                            </div>
                                        </td>
                                        <td class="text-wrap align-top text-center">
                                            <div class="fw-bold text-secondary">{{
                                                formatCurrency(reportData.OrderRevenueTotalItem.WaitPickupRevenue) }}
                                            </div>
                                            <div class="small text-muted">{{
                                                formatNumber(reportData.OrderRevenueTotalItem.WaitPickup) }} đơn</div>
                                            <div class="small text-info">COD: {{
                                                formatCurrency(reportData.OrderRevenueTotalItem.WaitPickupCollectAmount)
                                            }}
                                            </div>
                                        </td>
                                        <td class="text-wrap align-top text-center">
                                            <div class="fw-bold text-info">{{
                                                formatCurrency(reportData.OrderRevenueTotalItem.PickingRevenue) }}</div>
                                            <div class="small text-muted">{{
                                                formatNumber(reportData.OrderRevenueTotalItem.Picking) }} đơn</div>
                                            <div class="small text-info">COD: {{
                                                formatCurrency(reportData.OrderRevenueTotalItem.PickingCollectAmount) }}
                                            </div>
                                        </td>
                                        <td class="text-wrap align-top text-center">
                                            <div class="fw-bold text-teal">{{
                                                formatCurrency(reportData.OrderRevenueTotalItem.PickedRevenue) }}</div>
                                            <div class="small text-muted">{{
                                                formatNumber(reportData.OrderRevenueTotalItem.Picked) }} đơn</div>
                                            <div class="small text-info">COD: {{
                                                formatCurrency(reportData.OrderRevenueTotalItem.PickedCollectAmount) }}
                                            </div>
                                        </td>
                                        <td class="text-wrap align-top text-center">
                                            <div class="fw-bold text-purple">{{
                                                formatCurrency(reportData.OrderRevenueTotalItem.InWarehouseRevenue) }}</div>
                                            <div class="small text-muted">{{
                                                formatNumber(reportData.OrderRevenueTotalItem.InWarehouse) }} đơn</div>
                                            <div class="small text-info">COD: {{
                                                formatCurrency(reportData.OrderRevenueTotalItem.InWarehouseCollectAmount) }}
                                            </div>
                                        </td>
                                        <td class="text-wrap align-top text-center">
                                            <div class="fw-bold text-indigo">{{
                                                formatCurrency(reportData.OrderRevenueTotalItem.OutWarehouseRevenue) }}</div>
                                            <div class="small text-muted">{{
                                                formatNumber(reportData.OrderRevenueTotalItem.OutWarehouse) }} đơn</div>
                                            <div class="small text-info">COD: {{
                                                formatCurrency(reportData.OrderRevenueTotalItem.OutWarehouseCollectAmount) }}
                                            </div>
                                        </td>
                                        <td class="text-wrap align-top text-center">
                                            <div class="fw-bold text-dark">{{
                                                formatCurrency(reportData.OrderRevenueTotalItem.DeliveringRevenue) }}
                                            </div>
                                            <div class="small text-muted">{{
                                                formatNumber(reportData.OrderRevenueTotalItem.Delivering) }} đơn</div>
                                            <div class="small text-info">COD: {{
                                                formatCurrency(reportData.OrderRevenueTotalItem.DeliveringCollectAmount)
                                            }}
                                            </div>
                                        </td>
                                        <td class="text-wrap align-top text-center">
                                            <div class="fw-bold text-success">{{
                                                formatCurrency(reportData.OrderRevenueTotalItem.DeliveredRevenue) }}
                                            </div>
                                            <div class="small text-muted">{{
                                                formatNumber(reportData.OrderRevenueTotalItem.Delivered) }} đơn</div>
                                            <div class="small text-info">COD: {{
                                                formatCurrency(reportData.OrderRevenueTotalItem.DeliveredCollectAmount)
                                            }}</div>
                                        </td>
                                        <td class="text-wrap align-top text-center">
                                            <div class="fw-bold text-danger">{{
                                                formatCurrency(reportData.OrderRevenueTotalItem.CancelledRevenue) }}
                                            </div>
                                            <div class="small text-muted">{{
                                                formatNumber(reportData.OrderRevenueTotalItem.Cancelled) }} đơn</div>
                                            <div class="small text-info">COD: {{
                                                formatCurrency(reportData.OrderRevenueTotalItem.CancelledCollectAmount)
                                            }}</div>
                                        </td>
                                        <td class="text-wrap align-top text-center">
                                            <div class="progress" style="height: 20px;">
                                                <div class="progress-bar bg-success" role="progressbar"
                                                    :style="`width: ${reportData.OrderRevenueTotalItem.SuccessRate}%`"
                                                    :aria-valuenow="reportData.OrderRevenueTotalItem.SuccessRate"
                                                    aria-valuemin="0" aria-valuemax="100">
                                                    <strong>{{
                                                        formatPercent(reportData.OrderRevenueTotalItem.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 } 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,
    TitleComponent,
    TooltipComponent,
    LegendComponent,
    GridComponent
]);

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

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

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

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

// Search model
const searchModel = reactive({
    Pagination: {
        Total: 0,
        PageIndex: 1,
        PageSize: 25
    },
    Sort: {
        Predicate: '',
        Reverse: true
    },
    Search: {
        PredicateObject: {
            Keyword: '',
            StartDate: null,
            EndDate: null,
            PickupStartDate: null,
            PickupEndDate: null,
            DeliveryStartDate: null,
            DeliveryEndDate: 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 formatCurrency(value) {
    if (value == null || value == undefined) return '0 ₫';
    return new Intl.NumberFormat('vi-VN', {
        style: 'currency',
        currency: 'VND'
    }).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.getOrderProductionWithRevenue(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.OrderRevenueTotalItem = result.OrderRevenueTotalItem;
            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 = 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);
}

function handlePickupDateRange(modelData) {
    if (modelData != null) {
        const endDate = modelData[1];
        const startDate = modelData[0];
        const minDate = new Date(2025, 7, 10);

        if (startDate < minDate) {
            startDate.setTime(minDate.getTime());
        }

        if (endDate < minDate) {
            endDate.setTime(minDate.getTime());
        }

        searchModel.Search.PredicateObject.PickupStartDate = startDate;
        searchModel.Search.PredicateObject.PickupEndDate = endDate;
    } else {
        searchModel.Search.PredicateObject.PickupStartDate = null;
        searchModel.Search.PredicateObject.PickupEndDate = null;
    }
}

async function onChangePickupDate(newDates) {
    pickupDate.value = newDates;
    pickupDateRangePicker.value.closeMenu();
    handlePickupDateRange(newDates);
}

function handleDeliveryDateRange(modelData) {
    if (modelData != null) {
        const endDate = modelData[1];
        const startDate = modelData[0];
        const minDate = new Date(2025, 7, 10);

        if (startDate < minDate) {
            startDate.setTime(minDate.getTime());
        }

        if (endDate < minDate) {
            endDate.setTime(minDate.getTime());
        }

        searchModel.Search.PredicateObject.DeliveryStartDate = startDate;
        searchModel.Search.PredicateObject.DeliveryEndDate = endDate;
    } else {
        searchModel.Search.PredicateObject.DeliveryStartDate = null;
        searchModel.Search.PredicateObject.DeliveryEndDate = null;
    }
}

async function onChangeDeliveryDate(newDates) {
    deliveryDate.value = newDates;
    deliveryDateRangePicker.value.closeMenu();
    handleDeliveryDateRange(newDates);
}

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

function renderCharts() {
    renderLineChart();
}

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

    const labels = reportData.Items.map(item => item.OrderDateStr).reverse();
    const revenueData = reportData.Items.map(item => item.TotalRevenue).reverse();
    const collectData = reportData.Items.map(item => item.TotalCollectAmount).reverse();

    lineChartOption.value = {
        title: {
            text: 'Xu hướng doanh thu theo ngày',
            left: 'center'
        },
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'cross'
            },
            formatter: function (params) {
                let result = params[0].name + '<br/>';
                params.forEach(param => {
                    result += param.marker + param.seriesName + ': ' +
                        new Intl.NumberFormat('vi-VN', {
                            style: 'currency',
                            currency: 'VND'
                        }).format(param.value) + '<br/>';
                });
                return result;
            }
        },
        legend: {
            data: ['Doanh thu', 'Thu hộ'],
            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,
            axisLabel: {
                formatter: function (value) {
                    return new Intl.NumberFormat('vi-VN').format(value);
                }
            }
        },
        series: [
            {
                name: 'Doanh thu',
                type: 'line',
                data: revenueData,
                smooth: true,
                lineStyle: {
                    color: '#28a745'
                },
                itemStyle: {
                    color: '#28a745'
                },
                areaStyle: {
                    color: 'rgba(40, 167, 69, 0.1)'
                }
            },
            {
                name: 'Thu hộ',
                type: 'line',
                data: collectData,
                smooth: true,
                lineStyle: {
                    color: '#17a2b8'
                },
                itemStyle: {
                    color: '#17a2b8'
                },
                areaStyle: {
                    color: 'rgba(23, 162, 184, 0.1)'
                }
            }
        ]
    };
}


//#endregion

onMounted(async () => {
    // Set default date range (last 7 days)


    const endDate = new Date();
    const startDate = new Date();
    startDate.setDate(startDate.getDate() - 30);

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

.card-Count {
    position: absolute;
    bottom: -19px;
    right: 10px;
    font-size: 60px;
    opacity: .55;
}

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

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

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

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

.bg-indigo {
    background-color: #6610f2 !important;
}

.text-indigo {
    color: #6610f2 !important;
}
</style>