<template>
    <div>
        <BreadCrumb></BreadCrumb>
        <UpdateOrder :isShowdialog="isShowdialog" @updated="updated"></UpdateOrder>
        <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-5">
                    <form class="card-body" @submit.prevent="search">
                        <div class="row">
                            <div class="col-lg-3 col-md-4 mb-3">
                                <label>Từ khóa</label>
                                <input type="text" v-model="searchModel.Search.PredicateObject.Keyword"
                                    class="form-control" placeholder="Mã đơn hàng, mã đối tác...">
                            </div>

                            <div class="col-lg-3 col-md-4 mb-3">
                                <label>Trạng thái đơn hàng</label>
                                <v-select label="Name" :options="orderStatuses"
                                    v-model="searchModel.Search.PredicateObject.OrderStatuses"
                                    :reduce="(option) => option.Id" multiple placeholder="Chọn trạng thái...">
                                    <template v-slot:no-options="{ search, searching }">
                                        <template v-if="searching">
                                            Không có kết quả cho <em>{{ search }}</em>.
                                        </template>
                                        <span v-else style="opacity: 0.8">Không có bản ghi nào</span>
                                    </template>
                                </v-select>
                            </div>
                            <div class="col-lg-3 col-md-4 mb-3">
                                <label>Trạng thái vật lý</label>
                                <v-select label="Name" :options="orderPhysicalStatuses"
                                    v-model="searchModel.Search.PredicateObject.OrderPhysicalStatuses"
                                    :reduce="(option) => option.Id" multiple placeholder="Chọn trạng thái vật lý...">
                                    <template v-slot:no-options="{ search, searching }">
                                        <template v-if="searching">
                                            Không có kết quả cho <em>{{ search }}</em>.
                                        </template>
                                        <span v-else style="opacity: 0.8">Không có bản ghi nào</span>
                                    </template>
                                </v-select>
                            </div>
                            <div class="col-lg-3 col-md-4 mb-3">
                                <label>Phương thức thanh toán</label>
                                <v-select label="Name" :options="paymentMethods"
                                    v-model="searchModel.Search.PredicateObject.PayFeeTypes"
                                    :reduce="(option) => option.Id" multiple
                                    placeholder="Chọn phương thức thanh toán...">
                                    <template v-slot:no-options="{ search, searching }">
                                        <template v-if="searching">
                                            Không có kết quả cho <em>{{ search }}</em>.
                                        </template>
                                        <span v-else style="opacity: 0.8">Không có bản ghi nào</span>
                                    </template>
                                </v-select>
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-lg-3 col-md-4 mb-3">
                                <label>Khách hàng</label>
                                <v-select v-model="searchModel.Search.PredicateObject.CustomerId"
                                    :reduce="(option) => option.Id" label="FullName" :filterable="false"
                                    :options="customers" @search="searchCustomers"
                                    placeholder="Chọn / tìm khách hàng theo tên / sđt">
                                    <template #no-options>
                                        Gõ từ khóa để tìm khách hàng...
                                    </template>
                                    <template #option="{ FullName, PhoneNumber, UserName }">
                                        <div class="mt-0 pb-1">
                                            <h5 class="mb-1 tx-14">{{ FullName }}</h5>
                                            <p class="mb-0 tx-13">
                                                <span><i class="fas fa-phone tx-11"></i> {{ PhoneNumber }}</span>
                                                <span class="mg-l-10"><i class="fas fa-user tx-11"></i> {{ UserName
                                                    }}</span>
                                            </p>
                                        </div>
                                    </template>
                                    <template #selected-option="{ FullName, PhoneNumber }">
                                        <div style="display: flex; align-items: baseline">
                                            <strong>{{ FullName }}</strong>
                                            <span class="mg-r-5 mg-l-10">|</span>
                                            <small style="margin-left: 0.5rem">{{ PhoneNumber }}</small>
                                        </div>
                                    </template>
                                </v-select>
                            </div>
                            <div class="col-lg-3 col-md-4 mb-3">
                                <label>Ngày tạo</label>
                                <LadaDateRangePicker ref="createDatePicker" v-model="date"
                                    :format="datePickerStore.format" @update:model-value="handleDate" />
                            </div>

                            <div class="col-lg-3 col-md-4 mb-3">
                                <label>Thời gian lấy hàng</label>
                                <LadaDateRangePicker ref="pickupTimeDatePicker" v-model="pickupTimeDate"
                                    :format="datePickerStore.format" @update:model-value="onChangePickupTimeDate" />
                            </div>
                            <div class="col-lg-3 col-md-4 mb-3">
                                <label>Thời gian giao hàng</label>
                                <LadaDateRangePicker ref="deliveryTimeDatePicker" v-model="deliveryTimeDate"
                                    :format="datePickerStore.format" @update:model-value="onChangeDeliveryTimeDate" />
                            </div>
                            <div class="col-lg-3 col-md-4 mb-3">
                                <label>Thời gian nhận tiền</label>
                                <LadaDateRangePicker ref="headFeeTimeDatePicker" v-model="headFeeTimeDate"
                                    :format="datePickerStore.format" @update:model-value="onChangeHeadFeeTimeDate" />
                            </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>

                    <!-- Action Buttons -->
                    <div class="d-flex flex-row justify-content-between mg-b-10">
                        <button @click="exportToExcel" type="button"
                            class="btn btn-outline-success mx-2 button-icon mb-1" :disabled="exporting">
                            <i v-show="!exporting" class="fe fe-download me-2"></i>
                            <span v-show="exporting" class="spinner-border spinner-border-sm me-2"></span>
                            <span>Xuất Excel</span>
                        </button>
                    </div>

                    <div class="table-responsive">
                        <table class="table table-hover mg-b-0 text-md-nowrap">
                            <thead>
                                <tr>
                                    <th class="wd-20p">
                                        Thông tin chung
                                    </th>

                                    <th class="wd-20p">
                                        Địa chỉ
                                    </th>
                                    <th class="wd-20p">
                                        Triển khai
                                    </th>
                                    <th class="wd-20p">
                                        Tài chính
                                    </th>
                                    <th class="wd-5p">
                                        Quản lý
                                    </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 && 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>
                                <tr v-for="item in items">
                                    <td>
                                        <GeneralItem :general-model="item"></GeneralItem>

                                    </td>

                                    <td>
                                        <template v-for="(addressItem, index) in item.Addresses">
                                            <AddressItem :addressModel="addressItem"></AddressItem>
                                        </template>
                                    </td>
                                    <td>
                                        <OpsItem :ops-model="item.OrderOps"></OpsItem>
                                    </td>
                                    <td>

                                        <FinItem :fin-model="item.OrderFin"></FinItem>
                                    </td>
                                    <td>
                                        <button type="button"
                                            class="btn btn-block btn-outline-primary dropdown-toggle btn-sm"
                                            data-bs-toggle="dropdown" aria-expanded="false">
                                            <i class="fe fe-settings"></i>
                                            <!-- <span class="pd-l-5">Quản lý</span> -->
                                        </button>
                                        <ul class="dropdown-menu">
                                            <h6
                                                class="dropdown-header tx-uppercase tx-11 tx-bold tx-inverse tx-spacing-1">
                                                CẬP NHẬT
                                            </h6>
                                            <li @click="updateAddress(item, 1)">
                                                <a class="dropdown-item" href="javascript:void(0);">
                                                    <i class="fas fa-map-marker-alt"></i> Địa chỉ lấy hàng
                                                </a>
                                            </li>
                                            <li @click="updateAddress(item, 2)">
                                                <a class="dropdown-item" href="javascript:void(0);">
                                                    <i class="fas fa-map-marker"></i> Địa chỉ giao hàng
                                                </a>
                                            </li>
                                            <li @click="updateFin(item)">
                                                <a class="dropdown-item" href="javascript:void(0);">
                                                    <i class="fas fa-file-invoice-dollar"></i> Cước & COD
                                                </a>
                                            </li>
                                            <li @click="updatePackage(item.Id)">
                                                <a class="dropdown-item" href="javascript:void(0);">
                                                    <i class="fas fa-cubes"></i> Hàng hóa
                                                </a>
                                            </li>
                                            <!-- <li @click="review(item.Id)">
                                                <a class="dropdown-item" href="javascript:void(0);">
                                                    <i class="fa fa-star"></i> Cập nhật trạng thái
                                                </a>
                                            </li> -->
                                        </ul>
                                    </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>
    </div>
</template>
<script setup>
import { ref, reactive, onMounted, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { updateOrderStore } from './listStore';
const updateStore = updateOrderStore();

import orderService from "@/services/orderService";
import customerService from "@/services/customerService";

//#region Components
import BreadCrumb from './components/breadcrumb.vue';
import GeneralItem from './components/general.vue';
import AddressItem from './components/address.vue';
import FinItem from './components/fin.vue';
import OpsItem from './components/ops.vue';

//#region Cập nhật
import UpdateOrder from './components/actions/updateOrder.vue';
//#endregion


import DatepickerInstance from "@vuepic/vue-datepicker";
import { LadaDialog } from '@/components/index';
import { useToast } from "vue-toastification";
const toast = useToast();
//#endregion


import { useDatePickerStore } from "@/stores";
const datePickerStore = useDatePickerStore();
const route = useRoute();
const router = useRouter();

//#region DATA
const items = reactive([]);
const loading = ref(false);
const exporting = ref(false);
const date = ref();
const isShowdialog = ref(false);
const createDatePicker = ref(DatepickerInstance);
const pickupTimeDatePicker = ref(DatepickerInstance);
const deliveryTimeDatePicker = ref(DatepickerInstance);
const headFeeTimeDatePicker = ref(DatepickerInstance);
const filtersReady = ref(false);

// Filter data
const paymentMethods = reactive([]);
const orderStatuses = reactive([]);
const orderPhysicalStatuses = reactive([]);
const customers = reactive([]);

// Time filter state
const pickupTimeDate = ref();
const deliveryTimeDate = ref();
const headFeeTimeDate = ref();

//#endregion


//#region Functions
async function updateAddress(item, type) {
    console.log(item);
    var address = null;
    item.Addresses.forEach(add => {
        if (add.AddressType === type) {
            address = add;
        }
    });
    if (address != null && address.Id > 0) {
        if (type === 1) {
            updateStore.updateActionType(updateStore.actionTypes.SourceAddress);
        } else {
            updateStore.updateActionType(updateStore.actionTypes.DestAddress);
        }

        updateStore.updateAddressId(address.Id);
        isShowdialog.value = true;
    } else {
        alert("Yêu cầu không hợp lệ");
    }
}
async function updateFin(item) {
    console.log(item);

    if (item?.OrderFin != null && item.OrderFin.Id > 0) {
        updateStore.updateActionType(updateStore.actionTypes.Finance);

        // Truyền thêm CustomerId vào OrderFin
        const orderFinWithCustomer = {
            ...item.OrderFin,
            CustomerId: item.CustomerId
        };

        console.log('Debug updateFin - item.CustomerId:', item.CustomerId, 'orderFinWithCustomer:', orderFinWithCustomer);
        updateStore.updateFinance(orderFinWithCustomer);
        isShowdialog.value = true;
    } else {
        alert("Yêu cầu không hợp lệ");
    }
}
async function updatePackage(orderId) {
    if (orderId != null && orderId > 0) {
        updateStore.updateActionType(updateStore.actionTypes.Packages);
        updateStore.updateOrderId(orderId);
        isShowdialog.value = true;
    } else {
        alert("Yêu cầu không hợp lệ");
    }
}
async function updated() {
    isShowdialog.value = false;
    loadData();

}
// updated
//#endregion

//#region EXPORT EXCEL
async function exportToExcel() {
    try {
        exporting.value = true;

        // Tạo export model từ search model hiện tại
        const exportModel = {
            SearchParam: {
                Pagination: {
                    PageIndex: 1,
                    PageSize: 1000
                },
                Search: {
                    PredicateObject: { ...searchModel.Search.PredicateObject }
                },
                Sort: {
                    Predicate: searchModel.Sort.Predicate || 'CreatedTime',
                    Reverse: searchModel.Sort.Reverse
                }
            },
            FileName: `Danh_sach_don_hang_${new Date().toISOString().slice(0, 10)}`,
            IncludeHeader: true,
            FormatDates: true,
            IncludeTimeTrack: true,
            IncludePackages: true,
            IncludeAddresses: true
        };

        // Gọi API xuất Excel
        const result = await orderService.exportExcel(exportModel);

        if (result && result.Result === 1) {
            toast.success(`Xuất Excel thành công! Tổng ${result.TotalRecords} bản ghi.`);

            // Tự động download file
            if (result.DownloadUrl) {
                const link = document.createElement('a');
                link.href = result.DownloadUrl;
                link.download = result.FileName;
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);
            }
        } else {
            toast.error('Xuất Excel thất bại: ' + (result?.Message || 'Có lỗi xảy ra'));
        }
    } catch (error) {
        console.error('Export Excel error:', error);
        toast.error('Xuất Excel thất bại: ' + error.message);
    } finally {
        exporting.value = false;
    }
}
//#endregion

//#region SEARCH
const searchModel = reactive({
    Pagination: {
        PageIndex: 1,
        PageSize: 25,
        Total: 0
    },
    Sort: {
        Predicate: 'CreatedTime',
        Reverse: true
    },
    Search: {
        PredicateObject: {
            Keyword: '',
            OrderStatuses: [],
            OrderPhysicalStatuses: [],
            PayFeeTypes: [],
            CustomerId: null,
            CreatedStart: null,
            CreatedEnd: null,
            PickupTimeStart: null,
            PickupTimeEnd: null,
            DeliveryTimeStart: null,
            DeliveryTimeEnd: null,
            HeadFeeTimeStart: null,
            HeadFeeTimeEnd: null
        }
    },
    IsExport: false
});
const ctrlPager = ref();

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

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






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

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


//#endregion

//#region Filter Functions
async function loadFilters() {
    try {
        // Prefer incoming customer id from URL while loading filters
        const initCustomerId = route.query.cid || route.query.customerId || route.query.CustomerId || 0;
        const result = await orderService.prepareOrderListFilter(initCustomerId);
        if (result) {
            paymentMethods.splice(0, paymentMethods.length);
            if (result.PayFeeTypeOptions && result.PayFeeTypeOptions.length > 0) {
                result.PayFeeTypeOptions.forEach(opt => paymentMethods.push(opt));
            }

            orderStatuses.splice(0, orderStatuses.length);
            if (result.StatusOptions && result.StatusOptions.length > 0) {
                result.StatusOptions.forEach(opt => orderStatuses.push(opt));
            }

            orderPhysicalStatuses.splice(0, orderPhysicalStatuses.length);
            if (result.PhysicalStatusOptions && result.PhysicalStatusOptions.length > 0) {
                result.PhysicalStatusOptions.forEach(opt => orderPhysicalStatuses.push(opt));
            }
            // If API returns CustomerOptions when CustomerId > 0, hydrate customers list for v-select display
            if (result.CustomerOptions && result.CustomerOptions.length > 0) {
                customers.splice(0, customers.length);
                // Normalize to expected shape (Id, FullName, PhoneNumber, UserName)
                result.CustomerOptions.forEach(opt => customers.push(normalizeCustomerOption(opt)));
            }
            return true;
        } else {
            return false;
        }
    } catch (error) {
        console.error('Error loading order filters:', error);
        return false;
    }
}

function toIsoString(value) {
    if (!value) return undefined;
    try {
        const d = (value instanceof Date) ? value : new Date(value);
        return isNaN(d.getTime()) ? undefined : d.toISOString();
    } catch { return undefined; }
}

function parseDate(value) {
    if (!value) return null;
    const d = new Date(value);
    return isNaN(d.getTime()) ? null : d;
}

function updateUrlFromFilters() {
    if (!filtersReady.value) return;
    const q = {};
    const p = searchModel.Search.PredicateObject;
    if (p.Keyword) q.k = p.Keyword;
    if (p.OrderStatuses && p.OrderStatuses.length > 0) q.os = p.OrderStatuses.join(',');
    if (p.OrderPhysicalStatuses && p.OrderPhysicalStatuses.length > 0) q.ops = p.OrderPhysicalStatuses.join(',');
    if (p.PayFeeTypes && p.PayFeeTypes.length > 0) q.pft = p.PayFeeTypes.join(',');
    if (p.CustomerId) q.cid = String(p.CustomerId);
    if (p.CreatedStart) q.cs = toIsoString(p.CreatedStart);
    if (p.CreatedEnd) q.ce = toIsoString(p.CreatedEnd);
    if (p.PickupTimeStart) q.pts = toIsoString(p.PickupTimeStart);
    if (p.PickupTimeEnd) q.pte = toIsoString(p.PickupTimeEnd);
    if (p.DeliveryTimeStart) q.dts = toIsoString(p.DeliveryTimeStart);
    if (p.DeliveryTimeEnd) q.dte = toIsoString(p.DeliveryTimeEnd);
    if (p.HeadFeeTimeStart) q.hfs = toIsoString(p.HeadFeeTimeStart);
    if (p.HeadFeeTimeEnd) q.hfe = toIsoString(p.HeadFeeTimeEnd);

    router.replace({ query: q });
}

async function applyFiltersFromUrl() {
    const q = route.query;
    const p = searchModel.Search.PredicateObject;
    if (q.k) p.Keyword = String(q.k);
    if (q.os) p.OrderStatuses = String(q.os).split(',').map(x => parseInt(x, 10)).filter(n => !isNaN(n));
    if (q.ops) p.OrderPhysicalStatuses = String(q.ops).split(',').map(x => parseInt(x, 10)).filter(n => !isNaN(n));
    if (q.pft) p.PayFeeTypes = String(q.pft).split(',').map(x => parseInt(x, 10)).filter(n => !isNaN(n));
    const rawCid = q.cid || q.customerId || q.CustomerId;
    if (rawCid) {
        const id = parseInt(String(rawCid), 10);
        if (!isNaN(id) && id > 0) {
            p.CustomerId = id;
            try {
                const customerResult = await customerService.getById(id);
                if (customerResult && customerResult.Id > 0) {
                    customers.splice(0, customers.length);
                    customers.push(normalizeCustomerOption(customerResult));
                }
            } catch (e) {
                console.error('Error loading customer by id:', e);
            }
        }
    }

    const cs = parseDate(q.cs); const ce = parseDate(q.ce);
    if (cs && ce) {
        p.CreatedStart = cs; p.CreatedEnd = ce; date.value = [cs, ce];
    }
    const pts = parseDate(q.pts); const pte = parseDate(q.pte);
    if (pts && pte) {
        p.PickupTimeStart = pts; p.PickupTimeEnd = pte; pickupTimeDate.value = [pts, pte];
    }
    const dts = parseDate(q.dts); const dte = parseDate(q.dte);
    if (dts && dte) {
        p.DeliveryTimeStart = dts; p.DeliveryTimeEnd = dte; deliveryTimeDate.value = [dts, dte];
    }
    const hfs = parseDate(q.hfs); const hfe = parseDate(q.hfe);
    if (hfs && hfe) {
        p.HeadFeeTimeStart = hfs; p.HeadFeeTimeEnd = hfe; headFeeTimeDate.value = [hfs, hfe];
    }
}

// Ensure customer option shape is consistent for v-select display
function normalizeCustomerOption(raw) {
    if (!raw || typeof raw !== 'object') return raw;
    return {
        Id: raw.Id ?? raw.id ?? 0,
        FullName: raw.FullName ?? raw.Name ?? raw.fullName ?? raw.name ?? '',
        PhoneNumber: raw.PhoneNumber ?? raw.Phone ?? raw.Mobile ?? raw.phoneNumber ?? raw.phone ?? '',
        UserName: raw.UserName ?? raw.User ?? raw.Code ?? raw.username ?? raw.code ?? ''
    };
}


function handlePickupTimeDate(modelData) {
    if (modelData != null) {
        searchModel.Search.PredicateObject.PickupTimeStart = modelData[0];
        searchModel.Search.PredicateObject.PickupTimeEnd = modelData[1];
    } else {
        searchModel.Search.PredicateObject.PickupTimeStart = null;
        searchModel.Search.PredicateObject.PickupTimeEnd = null;
    }
}

function handleDeliveryTimeDate(modelData) {
    if (modelData != null) {
        searchModel.Search.PredicateObject.DeliveryTimeStart = modelData[0];
        searchModel.Search.PredicateObject.DeliveryTimeEnd = modelData[1];
    } else {
        searchModel.Search.PredicateObject.DeliveryTimeStart = null;
        searchModel.Search.PredicateObject.DeliveryTimeEnd = null;
    }
}

function handleHeadFeeTimeDate(modelData) {
    if (modelData != null) {
        searchModel.Search.PredicateObject.HeadFeeTimeStart = modelData[0];
        searchModel.Search.PredicateObject.HeadFeeTimeEnd = modelData[1];
    } else {
        searchModel.Search.PredicateObject.HeadFeeTimeStart = null;
        searchModel.Search.PredicateObject.HeadFeeTimeEnd = null;
    }
}

async function onChangePickupTimeDate(newDates) {
    pickupTimeDate.value = newDates;
    pickupTimeDatePicker.value.closeMenu();
    handlePickupTimeDate(newDates);
}

async function onChangeDeliveryTimeDate(newDates) {
    deliveryTimeDate.value = newDates;
    deliveryTimeDatePicker.value.closeMenu();
    handleDeliveryTimeDate(newDates);
}

async function onChangeHeadFeeTimeDate(newDates) {
    headFeeTimeDate.value = newDates;
    headFeeTimeDatePicker.value.closeMenu();
    handleHeadFeeTimeDate(newDates);
}
//#endregion

async function onChangeDate(newDates) {
    console.log(newDates);
    date.value = newDates;
    createDatePicker.value.closeMenu();
    handleDate(newDates)
}

function handleDate(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;
    }
}



onMounted(async () => {
    const ok = await loadFilters();
    if (ok) {
        await applyFiltersFromUrl();
        filtersReady.value = true;
        // Initial sync to normalize URL
        updateUrlFromFilters();
        await search();
    }
});

watch(() => searchModel.Search.PredicateObject, () => {
    updateUrlFromFilters();
}, { deep: true });

async function searchCustomers(keyword, loading) {
    try {
        if (keyword && keyword.length >= 2) {
            loading(true);
            customers.splice(0, customers.length);
            const result = await customerService.suggest(keyword);
            if (result && result.length > 0) {
                result.forEach(c => customers.push(normalizeCustomerOption(c)));
            }
        }
    } catch (e) {
        console.error('Error searching customers:', e);
    } finally {
        loading(false);
    }
}
</script>

<style scoped>
td>hr {
    border: 1px dashed;
    margin-block-start: 8px;
    margin-block-end: 8px;
}
</style>