<template>
    <div>
        <div class="breadcrumb-header justify-content-between">
            <div class="my-auto">
                <h4 class="page-title">Báo cáo ghi nhận doanh số</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">Ghi nhận doanh số</li>
                </ol>
            </div>
        </div>

        <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 nhận tiền</label>
                                <VueDatePicker ref="dateRangePicker" v-model="date" :enable-time-picker="false" range
                                    multi-calendars auto-apply :format="format" @update:model-value="handleDateRange">
                                    <template #left-sidebar>
                                        <DateRangeSidebar @change-date="onChangeDate"></DateRangeSidebar>
                                    </template>
                                </VueDatePicker>
                            </div>
                            <div class="col-lg-4 col-md-6 mb-3">
                                <label>&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>
                                </div>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>

        <div class="row row-sm" v-if="data.TotalItem">
            <div class="col-sm-12 col-md-12 col-lg-12 col-xl-12 grid-margin">
                <div class="card shadow-none mb-3">
                    <div class="card-header">
                        <h5 class="card-title mb-0">
                            <i class="fas fa-chart-pie me-2"></i>
                            Tổng quan
                        </h5>
                    </div>
                    <div class="card-body">
                        <div class="row">
                            <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(data.TotalItem.RecognizedRevenue) }}</h4>
                                        <p class="mb-1 small card-Count">{{ formatNumber(data.TotalItem.PaidOrders) }}
                                        </p>
                                        <p class="mb-0 small tx-13">Doanh thu đã ghi nhận</p>
                                        <div class="mt-2">
                                            <strong>Doanh số tính thu nhập</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(data.TotalItem.PaidRevenue) }}</h4>
                                        <p class="mb-1 small card-Count">{{ formatNumber(data.TotalItem.PaidOrders) }}
                                        </p>
                                        <p class="mb-0 small tx-13">Đã thanh toán</p>
                                        <div class="mt-2"><strong>Tổng (sau thuế VAT)</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(data.TotalItem.WaitingConfirmationRevenue) }}
                                        </h4>
                                        <p class="mb-1 small card-Count">{{
                                            formatNumber(data.TotalItem.WaitingConfirmationOrders) }}</p>
                                        <p class="mb-0 small tx-13">Đang xử lý</p>
                                        <div class="mt-2"><strong>Chờ kế toán xác nhận</strong></div>
                                    </div>
                                </div>
                            </div>
                            <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(data.TotalItem.UnpaidRevenue) }}</h4>
                                        <p class="mb-1 small card-Count">{{ formatNumber(data.TotalItem.UnpaidOrders) }}
                                        </p>
                                        <p class="mb-0 small tx-13">Chưa thanh toán</p>
                                        <div class="mt-2"><strong>Còn nợ</strong></div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class="row row-sm" v-if="data.Items && data.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>
                            Doanh thu theo ngày nhận tiền
                        </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>
                            Cơ cấu trạng thái thanh toán
                        </h5>
                    </div>
                    <div class="card-body">
                        <v-chart ref="pieChart" :option="pieChartOption" style="height: 300px;"></v-chart>
                    </div>
                </div>
            </div>
        </div>

        <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 nhận tiền
                        </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-10p">Ngày</th>
                                        <th class="wd-12p text-center">Tổng đơn</th>
                                        <th class="wd-12p text-center">Doanh thu</th>
                                        <th class="wd-12p text-center">Chưa thanh toán</th>
                                        <th class="wd-12p text-center">Chờ xác nhận</th>
                                        <th class="wd-12p text-center">Đã thanh toán</th>
                                        <th class="wd-12p text-center">Ghi nhận (VAT 8%)</th>
                                        <th class="wd-10p text-center">Tỷ lệ thanh toán</th>
                                    </tr>
                                </thead>
                                <tbody v-if="loading">
                                    <tr>
                                        <td colspan="8" class="tx-semibold text-center text-default">
                                            <span class="spinner-border spinner-border-sm"></span>
                                        </td>
                                    </tr>
                                </tbody>
                                <tbody v-if="!loading && (!data.Items || data.Items.length <= 0)">
                                    <tr>
                                        <td colspan="8" class="tx-semibold text-center text-danger">
                                            Không tìm thấy dữ liệu!
                                        </td>
                                    </tr>
                                </tbody>
                                <tbody v-if="!loading && data.Items && data.Items.length > 0">
                                    <tr v-for="item in data.Items" :key="item.CollectionDateStr">
                                        <td><strong>{{ item.CollectionDateStr }}</strong></td>
                                        <td class="text-center">{{ formatNumber(item.TotalOrders) }}</td>
                                        <td class="text-center text-primary">{{ formatCurrency(item.TotalRevenue) }}
                                        </td>
                                        <td class="text-center text-danger">
                                            <div class="fw-bold">{{ formatCurrency(item.UnpaidRevenue) }}</div>
                                            <div class="small text-muted">{{ formatNumber(item.UnpaidOrders) }} đơn
                                            </div>
                                        </td>
                                        <td class="text-center text-warning">
                                            <div class="fw-bold">{{ formatCurrency(item.WaitingConfirmationRevenue) }}
                                            </div>
                                            <div class="small text-muted">{{
                                                formatNumber(item.WaitingConfirmationOrders) }} đơn
                                            </div>
                                        </td>
                                        <td class="text-center text-success">
                                            <div class="fw-bold">{{ formatCurrency(item.PaidRevenue) }}</div>
                                            <div class="small text-muted">{{ formatNumber(item.PaidOrders) }} đơn</div>
                                        </td>
                                        <td class="text-center">{{ formatCurrency(item.RecognizedRevenue) }}</td>
                                        <td class="text-center">
                                            <div class="progress" style="height: 20px;">
                                                <div class="progress-bar bg-success" role="progressbar"
                                                    :style="`width: ${item.PaymentRate}%`"
                                                    :aria-valuenow="item.PaymentRate" aria-valuemin="0"
                                                    aria-valuemax="100">
                                                    {{ formatPercent(item.PaymentRate) }}%
                                                </div>
                                            </div>
                                        </td>
                                    </tr>
                                    <tr v-if="data.TotalItem" class="table-warning">
                                        <td><strong>{{ data.TotalItem.CollectionDateStr }}</strong></td>
                                        <td class="text-center">{{ formatNumber(data.TotalItem.TotalOrders) }}</td>
                                        <td class="text-center text-primary">{{
                                            formatCurrency(data.TotalItem.TotalRevenue) }}
                                        </td>
                                        <td class="text-center text-danger">
                                            <div class="fw-bold">{{ formatCurrency(data.TotalItem.UnpaidRevenue) }}
                                            </div>
                                            <div class="small text-muted">{{ formatNumber(data.TotalItem.UnpaidOrders)
                                                }} đơn
                                            </div>
                                        </td>
                                        <td class="text-center text-warning">
                                            <div class="fw-bold">{{
                                                formatCurrency(data.TotalItem.WaitingConfirmationRevenue) }}
                                            </div>
                                            <div class="small text-muted">{{
                                                formatNumber(data.TotalItem.WaitingConfirmationOrders) }} đơn</div>
                                        </td>
                                        <td class="text-center text-success">
                                            <div class="fw-bold">{{ formatCurrency(data.TotalItem.PaidRevenue) }}</div>
                                            <div class="small text-muted">{{ formatNumber(data.TotalItem.PaidOrders) }}
                                                đơn
                                            </div>
                                        </td>
                                        <td class="text-center">{{ formatCurrency(data.TotalItem.RecognizedRevenue) }}
                                        </td>
                                        <td class="text-center">
                                            <div class="progress" style="height: 20px;">
                                                <div class="progress-bar bg-success" role="progressbar"
                                                    :style="`width: ${data.TotalItem.PaymentRate}%`"
                                                    :aria-valuenow="data.TotalItem.PaymentRate" aria-valuemin="0"
                                                    aria-valuemax="100">
                                                    <strong>{{ formatPercent(data.TotalItem.PaymentRate) }}%</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 { useToast } from "vue-toastification";

use([CanvasRenderer, LineChart, PieChart, TitleComponent, TooltipComponent, LegendComponent, GridComponent]);

const toast = useToast();
const date = ref();
const dateRangePicker = ref(VueDatePicker);
const loading = ref(false);

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

const lineChart = ref();
const pieChart = ref();
const lineChartOption = ref({});
const pieChartOption = ref({});

const searchModel = reactive({
    Pagination: {
        Total: 0,
        PageIndex: 1,
        PageSize: 25
    },
    Sort: {
        Predicate: '',
        Reverse: true
    },
    Search: {
        PredicateObject: {
            StartDate: null,
            EndDate: null,
            SaleId: null
        }
    }
});

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() {
    searchModel.Pagination.PageIndex = 1;
    //ctrlPager.value.Refresh();
    loadData();
}

async function loadData() {
    loading.value = true;
    try {
        const result = await reportService.getOrderRevenueByCollectionDate(searchModel);
        if (result && (result.Result === 1 || result.Result === 'Success')) {
            data.Items.splice(0, data.Items.length);
            if (result.Items && result.Items.length > 0) {
                result.Items.forEach(i => data.Items.push(i));
            }
            data.TotalItem = result.TotalItem;
            data.TotalRecord = result.TotalRecord;
            data.Result = result.Result;
            data.Message = result.Message;
            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) {
        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 renderCharts() {
    renderLineChart();
    renderPieChart();
}

function renderLineChart() {
    if (!data.Items || data.Items.length === 0) return;
    const labels = data.Items.map(i => i.CollectionDateStr).reverse();
    const revenueData = data.Items.map(i => i.TotalRevenue).reverse();
    const recognizedData = data.Items.map(i => i.RecognizedRevenue).reverse();

    lineChartOption.value = {
        title: { text: 'Doanh thu & Ghi nhận', left: 'center' },
        tooltip: { trigger: 'axis' },
        legend: { data: ['Doanh thu', 'Ghi nhận'], 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: v => new Intl.NumberFormat('vi-VN').format(v) } },
        series: [
            { name: 'Doanh thu', type: 'line', data: revenueData, smooth: true },
            { name: 'Ghi nhận', type: 'line', data: recognizedData, smooth: true }
        ]
    };
}

function renderPieChart() {
    if (!data.TotalItem) return;
    const t = data.TotalItem;
    const pieData = [
        { value: t.UnpaidOrders, name: 'Chưa thanh toán' },
        { value: t.WaitingConfirmationOrders, name: 'Chờ xác nhận' },
        { value: t.PaidOrders, name: 'Đã thanh toán' }
    ];
    pieChartOption.value = {
        title: { text: 'Trạng thái thanh toán', left: 'center' },
        tooltip: { trigger: 'item', formatter: '{a} <br/>{b}: {c} ({d}%)' },
        legend: { orient: 'horizontal', bottom: '5%', left: 'center' },
        series: [
            { name: 'Trạng thái', type: 'pie', radius: ['40%', '70%'], center: ['50%', '45%'], data: pieData }
        ]
    };
}

onMounted(async () => {
    const endDate = new Date();
    const startDate = new Date();
    startDate.setDate(startDate.getDate() - 30);
    date.value = [startDate, endDate];
    handleDateRange([startDate, endDate]);
    await search();
});

const format = (dates) => {
    if (!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}`;
};
</script>

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

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