<template>
    <div>
        <!-- Breadcrumb -->
        <div class="breadcrumb-header justify-content-between">
            <div class="my-auto">
                <h4 class="page-title">Lịch sử Đổ Dầu</h4>
                <ol class="breadcrumb">
                    <li class="breadcrumb-item"><a href="/">Trang chủ</a></li>
                    <li class="breadcrumb-item"><a href="javascript:void(0);">Quản lý Dầu</a></li>
                    <li class="breadcrumb-item active" aria-current="page">Lịch sử Đổ Dầu</li>
                </ol>
            </div>
            
        </div>

        <!-- Search Form -->
        <div class="row row-sm">
            <div class="col-lg-12">
                <div class="card shadow-none">
                    <div class="card-header">
                        <h5 class="card-title mb-0">
                            <i class="fas fa-search me-2"></i>
                            Tìm kiếm
                        </h5>
                    </div>
                    <div class="card-body">
                        <div class="row">
                            <div class="col-lg-4 col-md-6 mb-3">
                                <label class="form-label">Từ khóa</label>
                                <input type="text" class="form-control" v-model="searchKeyword"
                                    placeholder="Nhập biển số xe, tên lái xe..." @keyup.enter="search">
                            </div>
                            <div class="col-lg-4 col-md-6 mb-3">
                                <label class="form-label">Thời gian</label>
                                <VueDatePicker ref="refillDatePicker" v-model="dateRange" :enable-time-picker="false" range
                                    multi-calendars auto-apply :format="formatDate" @update:model-value="handleDate">
                                    <template #left-sidebar>
                                        <DateRangeSidebar @change-date="onChangeDate"></DateRangeSidebar>
                                    </template>
                                </VueDatePicker>
                            </div>
                            <div class="col-lg-4 col-md-6 mb-3">
                                <label class="form-label">Phương thức thanh toán</label>
                                <select class="form-select" v-model="selectedPaymentMethod">
                                    <option :value="null">Tất cả</option>
                                    <option :value="1">Thẻ tín dụng</option>
                                    <option :value="2">Tiền mặt</option>
                                </select>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-12">
                                <button type="button" class="btn btn-primary me-2" @click="search">
                                    <i class="fas fa-search me-2"></i>Tìm kiếm
                                </button>
                                <button type="button" class="btn btn-secondary" @click="resetSearch">
                                    <i class="fas fa-redo me-2"></i>Làm mới
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Data Table -->
        <div class="row row-sm">
            <div class="col-lg-12">
                <div class="card card-table shadow-none">
                    <div class="card-body card-table-body">
                        <div class="d-flex flex-row justify-content-between mg-b-10">
                            <button type="button" class="btn btn-success mx-2 button-icon mb-1" @click="exportToExcel" :disabled="exporting">
                                <span v-if="exporting" class="spinner-border spinner-border-sm me-2"></span>
                                <i v-else class="fe fe-download me-2"></i>
                                {{ exporting ? 'Đang xuất...' : 'Xuất Excel' }}
                            </button>
                            <button type="button" class="btn btn-outline-primary mx-2 button-icon mb-1" @click="goToRefill">
                                <i class="fe fe-plus me-2"></i>Đổ dầu mới
                            </button>
                        </div>
                        <div class="table-responsive border-top mg-b-10">
                            <table class="table table-vcenter mb-0" style="min-height:300px">
                                <thead>
                                    <tr>
                                        <th class="wd-lg-5p min-width-1"><span>STT</span></th>
                                        <th class="wd-lg-20p min-width-3"><span>Thông tin chung</span></th>
                                        <th class="wd-lg-15p min-width-2"><span>ODO & Km</span></th>
                                        <th class="wd-lg-20p min-width-2"><span>Chi tiết đổ dầu</span></th>
                                        <th class="wd-lg-20p min-width-2"><span>Khoán & Chênh lệch</span></th>

                                        <th class="wd-lg-20p"><span>Hành động</span></th>
                                    </tr>
                                </thead>
                                <tbody v-if="loading">
                                    <tr>
                                        <td colspan="5" class="tx-semibold text-center text-default">
                                            <span class="spinner-border spinner-border-sm"></span>
                                        </td>
                                    </tr>
                                </tbody>
                                <tbody v-if="!loading && (!refills.Items || refills.Items.length <= 0)">
                                    <tr>
                                        <td colspan="5" class="tx-semibold text-center text-danger">
                                            Không tìm thấy bản ghi nào!
                                        </td>
                                    </tr>
                                </tbody>
                                <tbody v-if="!loading && refills.Items && refills.Items.length > 0">
                                    <tr v-for="(item, index) in refills.Items" :key="item.Id">
                                        <td class="text-wrap align-top">{{ getRowNumber(index) }}</td>
                                        <td class="text-wrap align-top">
                                            <div class="mb-1">
                                                <h5><span class="badge bg-info">{{ item.TruckLicensePlate }}</span></h5>
                                            </div>
                                            <div class="small text-muted mb-1">{{ item.DriverName }}</div>
                                            <div class="mb-1">
                                                <span :class="getPaymentMethodBadge(item.PaymentMethod)">{{ item.PaymentMethodStr }}</span>
                                            </div>
                                            <div class="text-muted" style="font-size: 0.75rem;">{{ formatDateTime(item.RefillTime) }}</div>
                                        </td>
                                        <td class="text-wrap align-top">
                                            <div class="small text-muted">Trước: {{ formatNumber(item.PreviousOdo) }}</div>
                                            <div class="small fw-bold">Sau: {{ formatNumber(item.CurrentOdo) }}</div>
                                            <div class="small text-primary fw-bold">Km: {{ formatNumber(item.DistanceKm) }}</div>
                                        </td>
                                        <td class="text-wrap align-top">
                                            <div class="small fw-bold mb-1">Số tiền: {{ formatCurrency(item.Amount) }}</div>
                                            <div class="small text-muted mb-1">Đơn giá: {{ formatNumber(item.UnitPrice) }} ₫/L</div>
                                            <div class="small">
                                                <span class="fw-bold">Thực tế:</span> {{ formatLiters(item.ActualLiters) }}
                                            </div>
                                        </td>
                                        <td class="text-wrap align-top">
                                            <div class="small mb-1">
                                                <span class="text-muted">Khoán:</span> {{ formatLiters(item.QuotaLiters) }}
                                            </div>
                                            <div :class="getDifferenceClass(item.DifferenceLiters)" class="mb-1">
                                                {{ getDifferenceIcon(item.DifferenceLiters) }}
                                                {{ formatLiters(Math.abs(item.DifferenceLiters)) }}
                                            </div>
                                            <div :class="getDifferenceClass(item.DifferenceLiters)" style="font-size: 0.75rem;">
                                                {{ formatCurrency(item.DifferenceLiters * item.UnitPrice) }}
                                            </div>
                                        </td>

                                        <td class="align-top pt-2">
                                            <button type="button" data-bs-toggle="dropdown"
                                                class="mb-1 mt-1 mr-1 btn btn-light dropdown-toggle btn-sm"
                                                aria-expanded="false"><i class="fas fa-cog"></i> Quản lý
                                            </button>
                                            <div class="dropdown-menu dropdown-menu-arrow">
                                                <a @click="viewDetail(item.Id)" class="dropdown-item"
                                                    href="javascript:void(0);"><i class="fe fe-eye"></i>
                                                    <span class="mg-l-6">Xem chi tiết</span>
                                                </a>
                                                <a @click="editRefill(item.Id)" class="dropdown-item"
                                                    href="javascript:void(0);"><i class="fe fe-edit-2"></i>
                                                    <span class="mg-l-6">Cập nhật</span>
                                                </a>
                                                <a @click="confirmDelete(item.Id)" class="dropdown-item"
                                                    href="javascript:void(0);">
                                                    <i class="fe fe-trash"></i>
                                                    <span class="mg-l-6">Xóa</span></a>
                                            </div>
                                        </td>
                                    </tr>
                                </tbody>
                            </table>
                        </div>
                        <pager ref="ctrlPager" v-show="!loading && refills.Items && refills.Items.length > 0"
                            @PageSizeChanged="PageSizeChanged" @PageIndexChanged="PageIndexChanged"
                            :Total="searchModel.Pagination.Total" :TotalCurrent="refills.Items.length">
                        </pager>
                    </div>
                </div>
            </div>
        </div>

        <!-- Detail Dialog -->
        <LadaDialog :visible="modalControl.Detail" variant="modal-full">
            <template #header>
                <div class="modal-header">
                    <h5 class="modal-title">
                        <i class="fas fa-info-circle me-2"></i>Chi Tiết Đổ Dầu
                    </h5>
                    <button @click="closeDetailModal" type="button" class="close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
            </template>
            <template #body>
                <FuelRefillDetail v-if="selectedRefillId > 0" :id="selectedRefillId" @close="closeDetailModal" />
            </template>
        </LadaDialog>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import fuelCardService from '@/services/fuelCardService';
import { useToast } from 'vue-toastification';
import VueDatePicker from '@vuepic/vue-datepicker';
import DatepickerInstance from "@vuepic/vue-datepicker";
import moment from 'moment';
import { LadaDialog, DateRangeSidebar } from '@/components/index';
import FuelRefillDetail from './detail.vue';

const router = useRouter();
const toast = useToast();

//#region DATA
const loading = ref(false);
const exporting = ref(false);
const searchKeyword = ref('');
const dateRange = ref(null);
const refillDatePicker = ref(DatepickerInstance);
const selectedPaymentMethod = ref(null);

const refills = reactive({
    Items: [],
    TotalRecord: 0,
    NumberOfPages: 0
});

const searchModel = reactive({
    Pagination: {
        Total: 0,
        PageIndex: 1,
        PageSize: 15
    },
    Sort: {
        Predicate: 'RefillTime',
        Reverse: true
    },
    Search: {
        PredicateObject: {
            Keyword: '',
            RefillStart: null,
            RefillEnd: null,
            PaymentMethod: null
        }
    }
});

const ctrlPager = ref();

// Modal control
const modalControl = reactive({
    Detail: false
});
const selectedRefillId = ref(0);

function closeDetailModal() {
    modalControl.Detail = false;
    selectedRefillId.value = 0;
}
//#endregion

//#region LIFECYCLE
onMounted(() => {
    // Set default date range (current month)
    const startOfMonth = moment().startOf('month').toDate();
    const endOfMonth = moment().endOf('month').toDate();
    dateRange.value = [startOfMonth, endOfMonth];
    search();
});
//#endregion

//#region FUNCTIONS
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 formatLiters(value) {
    if (value == null || value == undefined) return '0.00 L';
    return `${parseFloat(value).toFixed(2)} L`;
}

function formatDateTime(value) {
    if (!value) return '';
    return moment(value).format('DD/MM/YYYY HH:mm');
}

function formatDate(dates) {
    if (!dates || !Array.isArray(dates) || dates.length !== 2) return '';
    const start = moment(dates[0]).format('DD/MM/YYYY');
    const end = moment(dates[1]).format('DD/MM/YYYY');
    return `${start} - ${end}`;
}

function handleDate(modelData) {
    if (modelData != null && Array.isArray(modelData) && modelData.length === 2) {
        // Date range is already set in dateRange.value by v-model
        // Just trigger search if needed
    } else {
        dateRange.value = null;
    }
}

async function onChangeDate(newDates) {
    dateRange.value = newDates;
    refillDatePicker.value.closeMenu();
    handleDate(newDates);
}

function getDifferenceClass(difference) {
    if (difference > 0) {
        return 'small fw-bold text-success';
    } else if (difference < 0) {
        return 'small fw-bold text-danger';
    }
    return 'small text-muted';
}

function getDifferenceIcon(difference) {
    if (difference > 0) {
        return '↑';
    } else if (difference < 0) {
        return '↓';
    }
    return '';
}

function getPaymentMethodBadge(method) {
    return method === 1 ? 'badge bg-primary' : 'badge bg-success';
}

function getRowNumber(index) {
    return (searchModel.Pagination.PageIndex - 1) * searchModel.Pagination.PageSize + index + 1;
}

async function search() {
    loading.value = true;
    try {
        // Update search model
        searchModel.Search.PredicateObject.Keyword = searchKeyword.value;
        searchModel.Search.PredicateObject.PaymentMethod = selectedPaymentMethod.value;

        // Set date range
        if (dateRange.value && Array.isArray(dateRange.value) && dateRange.value.length === 2) {
            searchModel.Search.PredicateObject.RefillStart = dateRange.value[0];
            searchModel.Search.PredicateObject.RefillEnd = dateRange.value[1];
        } else {
            searchModel.Search.PredicateObject.RefillStart = null;
            searchModel.Search.PredicateObject.RefillEnd = null;
        }

        const result = await fuelCardService.searchRefills(searchModel);
        if (result && result.Items) {
            refills.Items.splice(0, refills.Items.length);
            result.Items.forEach(item => {
                refills.Items.push(item);
            });
            refills.TotalRecord = result.TotalRecord || 0;
            refills.NumberOfPages = result.NumberOfPages || 0;
            searchModel.Pagination.Total = result.TotalRecord || 0;
        } else {
            toast.error('Không thể tải dữ liệu');
        }
    } catch (error) {
        console.error('Error searching refills:', error);
        toast.error('Có lỗi xảy ra khi tải dữ liệu');
    } finally {
        loading.value = false;
    }
}

function resetSearch() {
    searchKeyword.value = '';
    selectedPaymentMethod.value = null;
    const startOfMonth = moment().startOf('month').toDate();
    const endOfMonth = moment().endOf('month').toDate();
    dateRange.value = [startOfMonth, endOfMonth];
    searchModel.Pagination.PageIndex = 1;
    if (ctrlPager.value) {
        ctrlPager.value.Refresh();
    }
    search();
}

function PageSizeChanged(pagesize) {
    searchModel.Pagination.PageSize = pagesize;
    searchModel.Pagination.PageIndex = 1;
    search();
}

function PageIndexChanged(pageIndex) {
    searchModel.Pagination.PageIndex = pageIndex;
    search();
}

function goToRefill() {
    router.push({ name: 'FuelRefillCreate' });
}

function viewDetail(id) {
    selectedRefillId.value = id;
    modalControl.Detail = true;
}

function editRefill(id) {
    router.push({ name: 'FuelRefillEdit', params: { id } });
}

async function confirmDelete(id) {
    if (!confirm('Bạn có chắc chắn muốn xóa bản ghi đổ dầu này?\n\nLưu ý: Thao tác này sẽ xóa vĩnh viễn bản ghi và tất cả ảnh liên quan.')) {
        return;
    }
    
    await deleteRefill(id);
}

async function deleteRefill(id) {
    try {
        const result = await fuelCardService.deleteRefill(id);
        if (result && result.Result === 1) {
            toast.success(result.Message || 'Xóa bản ghi đổ dầu thành công');
            // Reload data
            await search();
        } else {
            toast.error(result.Message || 'Không thể xóa bản ghi đổ dầu');
        }
    } catch (error) {
        console.error('Error deleting refill:', error);
        toast.error('Có lỗi xảy ra khi xóa bản ghi đổ dầu');
    }
}

async function exportToExcel() {
    exporting.value = true;
    try {
        // Tạo payload với Pagination, Search và Sort
        const exportParams = {
            Pagination: {
                PageIndex: 1,
                PageSize: 999999 // Xuất toàn bộ dữ liệu
            },
            Search: {
                PredicateObject: {
                    Keyword: searchKeyword.value || null,
                    RefillStart: null,
                    RefillEnd: null,
                    PaymentMethod: selectedPaymentMethod.value || null
                }
            },
            Sort: {
                Predicate: searchModel.Sort.Predicate,
                Reverse: searchModel.Sort.Reverse
            }
        };

        // Set date range
        if (dateRange.value && Array.isArray(dateRange.value) && dateRange.value.length === 2) {
            exportParams.Search.PredicateObject.RefillStart = dateRange.value[0];
            exportParams.Search.PredicateObject.RefillEnd = dateRange.value[1];
        }

        const result = await fuelCardService.exportRefillsExcel(exportParams);
        
        if (result && result.Result === 1) {
            // Tải file về
            if (result.DownloadUrl) {
                // DownloadUrl đã là full URL, không cần ghép baseURL
                window.open(result.DownloadUrl, '_blank');
                
                toast.success(`Xuất Excel thành công! Tổng ${result.TotalRecords} bản ghi`);
            } else {
                toast.error('Không tìm thấy đường dẫn tải file');
            }
        } else {
            toast.error(result.Message || 'Không thể xuất file Excel');
        }
    } catch (error) {
        console.error('Error exporting to Excel:', error);
        toast.error('Có lỗi xảy ra khi xuất file Excel');
    } finally {
        exporting.value = false;
    }
}
//#endregion
</script>

<style scoped>
.table-sm th,
.table-sm td {
    padding: 0.5rem 0.25rem;
    font-size: 0.875rem;
}

.small {
    font-size: 0.875rem;
}
</style>
