<template>
    <div>
        <div class="breadcrumb-header justify-content-between">
            <div class="my-auto">
                <h4 class="page-title">Quản lý xe tải</h4>
                <ol class="breadcrumb">
                    <li class="breadcrumb-item"><a href="javascript:void(0);">Trang chủ</a></li>
                    <li class="breadcrumb-item active" aria-current="page">Quản lý xe tải</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">
                    <form class="card-body" @submit.prevent="search">
                        <div class="row">
                            <div class="col-lg-3 col-md-4 mb-3">
                                <label>Biển số</label>
                                <input type="text" v-model="searchModel.Search.PredicateObject.Keyword"
                                    class="form-control" placeholder="Từ khóa...">
                            </div>
                            <div class="col-lg-3 col-md-4 mb-3">
                                <label>Ngày tạo</label>
                                <VueDatePicker @update:model-value="handleCreateTime" v-model="createdTime"
                                    :enable-time-picker="false" range multi-calendars auto-apply :format="format"
                                    placeholder="Ngày tạo">
                                    <template #left-sidebar>
                                        <DateRangeSidebar @change-date="onChangeCreatedTime"></DateRangeSidebar>
                                    </template>
                                </VueDatePicker>
                            </div>
                            <div class="col-lg-3 col-md-3 mb-3">
                                <label>Ngày sửa chữa</label>
                                <VueDatePicker @update:model-value="handleLastRepairTime" v-model="lastRepairTime"
                                    :enable-time-picker="false" range multi-calendars auto-apply :format="format"
                                    placeholder="Ngày sửa chữa cuối">
                                    <template #left-sidebar>
                                        <DateRangeSidebar @change-date="onChangeLastRepairTime"></DateRangeSidebar>
                                    </template>
                                </VueDatePicker>
                            </div>
                            <div class="col-lg-3 col-md-4 mb-3">
                                <label>Trạng thái</label>
                                <v-select label="Name" :options="statusOptions"
                                    v-model="searchModel.Search.PredicateObject.Status"
                                    :reduce="(option) => option.Id"></v-select>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-lg mb-3">
                                <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>

                    </form>
                </div>
                <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 @click="fnCreateOrUpdate(0)" type="button"
                                class="btn btn-outline-primary mx-2 button-icon mb-1"><i
                                    class="fe fe-plus me-2"></i>Thêm
                                mới</button>
                            <!-- <button type="button" class="btn btn-outline-success mx-2 button-icon mb-1">
                                <i class="fe fe-download me-2"></i>Xuất excel</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-15p min-width-2"><span>Thông tin xe</span></th>
                                        <th class="wd-lg-8p min-width-2"><span>Trạng thái</span></th>
                                        <th class="wd-lg-10p min-width-2"><span>Chi nhánh</span></th>
                                        <th class="wd-lg-10p min-width-1"><span>Người lái</span></th>
                                        <th class="wd-lg-12p min-width-2"><span>Thông số kỹ thuật</span></th>
                                        <th class="wd-lg-8p min-width-1"><span>Định mức</span></th>
                                        <th class="wd-lg-8p min-width-1"><span>ODO đổ dầu</span></th>
                                        <th class="wd-lg-8p"></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 && items.length <= 0">
                                    <tr>
                                        <td colspan="9" 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 && items.length > 0">

                                    <tr v-for="item in items" :key="item.Id">
                                        <td class="text-wrap align-top">
                                            <div class="d-flex flex-column">
                                                <strong class="tx-15">{{ item.LicensePlate }}</strong>
                                                <span class="tx-12 text-muted">
                                                    <span v-if="item.Brand || item.Model">
                                                        {{ item.Brand || '' }} {{ item.Model || '' }}
                                                        <span v-if="item.ManufacturingYear"> - {{ item.ManufacturingYear }}</span>
                                                    </span>
                                                    <span v-else-if="item.ManufacturingYear">Năm {{ item.ManufacturingYear }}</span>
                                                </span>
                                            </div>
                                        </td>
                                        <td class="text-wrap align-top">
                                            <span :class="[
                                                'badge',
                                                item.OperatingStatus == 1 ? 'bg-secondary' : (item.OperatingStatus == 2 ? 'bg-success' : 'bg-secondary')
                                            ]">
                                                {{ item.OperatingStatusStr }}
                                            </span>
                                        </td>
                                        <td class="text-wrap align-top">
                                            {{ item.AgencyName }}
                                        </td>
                                        <td class="text-wrap align-top">
                                            <span>{{ item.PicUserName }}</span><span v-if="item.PicFullName">
                                                ({{ item.PicFullName }})</span>
                                        </td>
                                        <td class="text-wrap align-top">
                                            <div class="d-flex flex-column">
                                                <span class="tx-13">
                                                    <i class="fas fa-weight-hanging tx-11 text-muted me-1"></i>
                                                    {{ item.MaxPayload != null ? item.MaxPayload.toFixed(2) + ' tấn' : '-' }}
                                                </span>
                                                <span class="tx-12 text-muted" v-if="item.CargoLength || item.CargoWidth || item.CargoHeight">
                                                    <i class="fas fa-ruler-combined tx-11 me-1"></i>
                                                    {{ item.CargoLength || 0 }}x{{ item.CargoWidth || 0 }}x{{ item.CargoHeight || 0 }} cm
                                                </span>
                                            </div>
                                        </td>
                                        <td class="text-wrap align-top text-end">
                                            {{ item.FuelQuotaPer100Km != null ? item.FuelQuotaPer100Km.toFixed(2) + ' lít/100km' : '-' }}
                                        </td>
                                        <td class="text-wrap align-top text-end">
                                            <span v-if="item.LastRefillOdo != null" class="badge bg-info-transparent">
                                                <i class="fe fe-activity me-1"></i>
                                                {{ item.LastRefillOdo.toLocaleString('vi-VN') }} km
                                            </span>
                                            <span v-else class="text-muted">-</span>
                                        </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="fnCreateOrUpdate(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="fnDelete(item.Id)" class="dropdown-item"
                                                    href="javascript:void(0);">
                                                    <i class="fe fe-trash"></i>
                                                    <span class="mg-l-6">Xóa</span></a>

                                                <a @click="truckCheckOpen(item, 1)" class="dropdown-item"
                                                    href="javascript:void(0);">
                                                    <i class="fe fe-minimize-2"></i>
                                                    <span class="mg-l-6">Check-In</span></a>
                                                <a @click="truckCheckOpen(item, 0)" class="dropdown-item"
                                                    href="javascript:void(0);">
                                                    <i class="fe fe-maximize-2"></i>
                                                    <span class="mg-l-6">Check-Out</span></a>
                                                <a @click="openActivityHistory(item)" class="dropdown-item"
                                                    href="javascript:void(0);">
                                                    <i class="fe fe-clock"></i>
                                                    <span class="mg-l-6">Lịch sử giao nhận</span></a>
                                                <a @click="openUpdateOdoModal(item)" class="dropdown-item"
                                                    href="javascript:void(0);">
                                                    <i class="fe fe-activity"></i>
                                                    <span class="mg-l-6">Cập nhật ODO đổ dầu</span></a>
                                            </div>
                                        </td>
                                    </tr>
                                </tbody>
                            </table>
                        </div>
                        <pager ref="ctrlPager" v-show="!loading && items.length > 0" @PageSizeChanged="pageSizeChanged"
                            @PageIndexChanged="pageIndexChanged" :Total="searchModel.Pagination.Total"
                            :TotalCurrent="items.length">
                        </pager>
                    </div>
                </div>
            </div><!-- COL END -->
        </div>
        <LadaDialog :visible="modalControl.CreateOrUpdate">
            <template #header>
                <div class="modal-header">
                    <h5 class="modal-title" v-if="truckId <= 0">Thêm xe tải</h5>
                    <h5 class="modal-title" v-if="truckId > 0">Cập nhật xe tải</h5>
                    <button @click="closeModal" type="button" class="close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
            </template>
            <template #body>
                <CreateOrUpdate @cancel="closeModal" :id="truckId"></CreateOrUpdate>
            </template>

        </LadaDialog>
        <LadaDialog :visible="modalControl.TruckCheckModal">
            <template #header>
                <div class="modal-header">
                    <h5 class="modal-title" v-if="modalControl.TruckCheckParam == 0">Check Out</h5>
                    <h5 class="modal-title" v-if="modalControl.TruckCheckParam == 1">Check In</h5>
                    <button @click="truckCheckClose" type="button" class="close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
            </template>
            <template #body>
                <div class="row">
                    <div class="col-lg-12 justify-content">
                        <div class="d-flex justify-content-center">
                            <canvas id="QRCode"></canvas>
                        </div>
                        <div class="d-flex justify-content-center">
                            <h5 class="modal-title" v-if="modalControl.TruckCheckParam == 0">Check Out QR Code</h5>
                            <h5 class="modal-title" v-if="modalControl.TruckCheckParam == 1">Check In QR Code</h5>
                        </div>
                    </div>
                    <div class="col-lg-12 ">
                        <div class="d-flex flex-row-reverse">
                            <button @click="truckCheckClose" type="button" class="btn btn-main-default mg-l-15">
                                Bỏ qua
                            </button>
                            <!-- <button v-if="modalControl.TruckCheckParam == 1" @click="fnCheckIn" type="button"
                                class="btn btn-main-primary" :disabled="isSubmitting">
                                <span v-show="isSubmitting" class="spinner-border spinner-border-sm"></span>
                                Xác nhận
                            </button>
                            <button v-if="modalControl.TruckCheckParam == 0" @click="fnCheckOut" type="button"
                                class="btn btn-main-primary" :disabled="isSubmitting">
                                <span v-show="isSubmitting" class="spinner-border spinner-border-sm"></span>
                                Xác nhận
                            </button> -->
                        </div>
                    </div>
                </div>
            </template>

        </LadaDialog>
        <LadaDialog :visible="modalControl.ActivityHistoryModal" size="lg">
            <template #header>
                <div class="modal-header">
                    <h5 class="modal-title">Lịch sử giao nhận xe tải</h5>
                    <button @click="closeActivityHistoryModal" type="button" class="close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
            </template>
            <template #body>
                <ActivityHistory :truckId="selectedTruckId"></ActivityHistory>
            </template>
        </LadaDialog>
        <LadaDialog :visible="modalControl.UpdateOdoModal">
            <template #header>
                <div class="modal-header">
                    <h5 class="modal-title">Cập nhật ODO đổ dầu gần nhất</h5>
                    <button @click="closeUpdateOdoModal" type="button" class="close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
            </template>
            <template #body>
                <div class="row">
                    <div class="col-lg-12 mb-3">
                        <div class="alert alert-info">
                            <i class="fe fe-info me-2"></i>
                            <strong>Xe tải:</strong> {{ selectedTruck?.LicensePlate }}
                        </div>
                    </div>
                    <div class="col-lg-12 mb-3">
                        <label class="form-label">Giá trị ODO (km) <span class="text-danger">*</span></label>
                        <input type="number" class="form-control" v-model.number="odoValue"
                            placeholder="Nhập giá trị ODO hiện tại" min="0" step="1" required>
                        <small class="text-muted">Giá trị ODO phải lớn hơn hoặc bằng ODO đổ dầu trước đó</small>
                    </div>
                    <div class="col-lg-12">
                        <div class="d-flex flex-row-reverse">
                            <button @click="closeUpdateOdoModal" type="button" class="btn btn-secondary mg-l-15">
                                Hủy
                            </button>
                            <button @click="updateOdo" type="button" class="btn btn-primary" :disabled="isSubmitting">
                                <span v-show="isSubmitting" class="spinner-border spinner-border-sm me-2"></span>
                                <i v-show="!isSubmitting" class="fe fe-check me-2"></i>
                                Cập nhật
                            </button>
                        </div>
                    </div>
                </div>
            </template>
        </LadaDialog>
    </div>
</template>
<script setup>
//#region Imports
import moment from 'moment';
import qrcode from 'qrcode';
import { ref, reactive, onMounted, watch } from 'vue'
import apiPath from "@/infrastructure/apiPath";
import truckService from "@/services/truckService";
//#endregion


//#region Components
import DatepickerInstance from "@vuepic/vue-datepicker";
import { LadaDialog, DateRangeSidebar } from '@/components/index';
import CreateOrUpdate from './components/createOrUpdate.vue';
import ActivityHistory from './components/activityHistory.vue';
import { useToast } from "vue-toastification";
import { watchArray } from '@vueuse/core';
const toast = useToast();

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



//#endregion


//#region Declare argument
const emit = defineEmits('truckId');
const items = reactive([]);
const loading = ref(false);
const truckId = ref(0);
const agencyId = ref(0);
const checkUrl = ref('');
const statusOptions = reactive([
    { Id: null, Name: "Tất cả" },
    { Id: 1, Name: "Đang Dừng / Đỗ" },
    { Id: 2, Name: "Đang Hoạt Động" },
    { Id: 3, Name: "Bảo Trì / Sửa Chữa" }
]);
const createdTime = ref();
const lastRepairTime = ref();
const searchModel = reactive({
    Pagination: {
        Total: 0,
        PageIndex: 1,
        PageSize: 25
    },
    Sort: {
        Predicate: '',
        Reverse: true
    },
    Search: {
        PredicateObject: {
            Keyword: '',
            CreatedStart: null,
            CreatedEnd: null,
            LastRepairStart: null,
            LastRepairEnd: null,
            Status: null
        }
    }
});

async function onChangeCreatedTime(newDates) {
    createdTime.value = newDates;
    handleDate(newDates)
}

function handleCreateTime(modelData) {
    if (modelData != null) {
        searchModel.Search.PredicateObject.CreatedStart = modelData[0];
        searchModel.Search.PredicateObject.CreatedEnd = modelData[1];
    } else {
        searchModel.Search.PredicateObject.CreatedStart = null;
        searchModel.Search.PredicateObject.CreatedEnd = null;
    }
}

async function onChangeLastRepairTime(newDates) {
    lastRepairTime.value = newDates;
    handleLastRepairTime(newDates)
}

function handleLastRepairTime(modelData) {
    console.log(moment(modelData[0]));
    if (modelData != null) {
        searchModel.Search.PredicateObject.LastRepairStart = modelData[0];
        searchModel.Search.PredicateObject.LastRepairEnd = modelData[1];
    } else {
        searchModel.Search.PredicateObject.LastRepairStart = null;
        searchModel.Search.PredicateObject.LastRepairEnd = null;
    }
}

//#endregion


//#region Modals

const modalControl = reactive({
    CreateOrUpdate: false,
    TruckCheckModal: false,
    ActivityHistoryModal: false,
    UpdateOdoModal: false,
    // 0 = CheckOut
    // 1 = CheckIn
    TruckCheckParam: 0,
});
const selectedTruckId = ref(0);
const selectedTruck = ref(null);
const odoValue = ref(0);
const isSubmitting = ref(false);



function openModal() {
    modalControl.CreateOrUpdate = true;
}
function closeModal() {
    modalControl.CreateOrUpdate = false;

    truckId.value = 0;
    loadData();
}

const ctrlPager = ref();

async function search() {
    searchModel.Pagination.PageIndex = 1;
    ctrlPager.value.Refresh();
    loadData();
}

async function loadData() {
    loading.value = true;
    items.splice(0, items.length);
    var searchResult = await truckService.truckSearch(searchModel);
    if (searchResult.Items != null && searchResult.Items.length > 0) {
        searchResult.Items.forEach(menu => {
            items.push(menu);
        });
    }
    searchModel.Pagination.Total = searchResult.TotalRecord;
    loading.value = false;
}

function pageSizeChanged(pagesize) {
    searchModel.Pagination.PageSize = pagesize;
    searchModel.Pagination.PageIndex = 1;
    loadData();
}
function pageIndexChanged(pageIndex) {
    searchModel.Pagination.PageIndex = pageIndex;
    loadData();
}
function fnCreateOrUpdate(id) {
    if (id) {
        truckId.value = id;
        emit('truckId', truckId);
    }
    openModal();
}
//#endregion

async function fnDelete(id) {
    if (!id) {
        toast.error('Không xác định được xe tải');
        return;
    }
    
    // Hiển thị hộp thoại xác nhận
    if (!window.confirm('Bạn có chắc chắn muốn xóa xe tải này?')) {
        return;
    }
    
    truckId.value = id;
    emit('truckId', truckId);
    var rs = await truckService.truckDelete(id);
    if (rs.Result == 1) {
        search();
        toast.success('Xóa xe tải thành công');
    } else {
        toast.error(rs.Message || 'Có lỗi xảy ra');
    }
}
async function fnCheckIn() {
    if (truckId.value > 0) {
        if (agencyId.value > 0) {
            var rs = await truckService.truckCheckIn({
                TruckId: truckId.value,
                AgencyId: agencyId.value
            });
            if (rs.Result == 1) {
                search();
                toast.success('Thành công');
            } else {
                toast.error(rs.Message);
            }
        } else {
            toast.success('Không xác định được chi nhánh');
        }
    }
    else {
        toast.success('Không xác định được xe tải');
    }
}
async function fnCheckOut() {
    if (truckId.value > 0) {
        if (agencyId.value > 0) {
            var rs = await truckService.truckCheckOut({
                TruckId: truckId.value,
                AgencyId: agencyId.value
            });
            if (rs.Result == 1) {
                search();
                toast.success('Thành công');
            } else {
                toast.error(rs.Message);
            }
        } else {
            toast.success('Không xác định được chi nhánh');
        }
    }
    else {
        toast.success('Không xác định được xe tải');
    }
}

function truckCheckOpen(model, type) {
    modalControl.TruckCheckModal = true;
    modalControl.TruckCheckParam = type;
    truckId.value = model.Id;
    agencyId.value = model.AgencyId;
    if (type == 0)
        checkUrl.value = apiPath.truck.truckCheckOut + `?agencyId=${model.AgencyId}&truckId=${model.Id}`;
    if (type == 1)
        checkUrl.value = apiPath.truck.truckCheckIn + `?agencyId=${model.AgencyId}&truckId=${model.Id}`;
    setTimeout(() => {
        if (truckId.value > 0 && agencyId.value > 0) {
            var canvas = document.getElementById('QRCode')
            console.log(canvas);
            qrcode.toCanvas(canvas, checkUrl.value, { width: 250 }, function (error) {
                if (error) {
                    console.error(error);
                }
                console.log(error);
            });
        }
    }, 100)

}
function truckCheckClose() {
    modalControl.TruckCheckModal = false;
    truckId.value = 0;
    agencyId.value = 0;
}

function openActivityHistory(item) {
    selectedTruckId.value = item.Id;
    modalControl.ActivityHistoryModal = true;
}

function closeActivityHistoryModal() {
    modalControl.ActivityHistoryModal = false;
    selectedTruckId.value = 0;
}

function openUpdateOdoModal(item) {
    selectedTruck.value = item;
    selectedTruckId.value = item.Id;
    odoValue.value = 0;
    modalControl.UpdateOdoModal = true;
}

function closeUpdateOdoModal() {
    modalControl.UpdateOdoModal = false;
    selectedTruck.value = null;
    selectedTruckId.value = 0;
    odoValue.value = 0;
}

async function updateOdo() {
    if (!selectedTruckId.value || selectedTruckId.value <= 0) {
        toast.error('Không xác định được xe tải');
        return;
    }

    if (odoValue.value < 0) {
        toast.error('Giá trị ODO phải >= 0');
        return;
    }

    isSubmitting.value = true;
    try {
        const result = await truckService.updateLastRefillOdo(selectedTruckId.value, odoValue.value);
        if (result && result.Result === 1) {
            toast.success(result.Message || 'Cập nhật ODO thành công');
            closeUpdateOdoModal();
            loadData();
        } else {
            toast.error(result.Message || 'Không thể cập nhật ODO');
        }
    } catch (error) {
        console.error('Error updating ODO:', error);
        toast.error('Có lỗi xảy ra khi cập nhật ODO');
    } finally {
        isSubmitting.value = false;
    }
}

onMounted(async () => {
    await search();
})

watch([truckId, agencyId], async ([truck, agency]) => {
    if (truck > 0 && agency > 0) {
        var canvas = document.getElementById('#QRCode')
        qrcode.toCanvas(canvas, checkUrl.value, { width: 550 }, function (error) {
            if (error)
                console.error(error);
        });
    }

})
</script>