<template>
    <div>
        <loader v-if="loading" class="mt-5 mb-5"></loader>
        <div v-if="!loading" class="commands d-flex mg-b-20 mg-t-0">
            <div class="flex-grow-1">
                <div class="btn-group mt-2 mg-l-10">
                    <button @click="reload" type="button" class="btn btn-sm btn-primary nobg">
                        <i class="fas fa-sync-alt"></i></button>
                </div>


                <div class="btn-group mt-2 mg-l-10" v-if="selectedOrders.length > 0">
                    <Assign :orderIds="selectedOrderIds" :addressType="addressType"></Assign>
                    <button @click="unassign" alt="Bỏ gán" title="Bỏ gán" class="btn btn-sm button-icon nobg"
                        type="button">
                        <i class="fas fa-user-slash"></i>
                    </button>
                </div>
            </div>
            <div class="filter d-flex align-items-center gap-2">
                <div class="filter-item" style="min-width: 200px;">
                    <v-select :options="pickupOptions" v-model="pickupFilters" multiple :reduce="o => o.Id"
                        label="Name" placeholder="Lấy hàng" @update:model-value="onFilterChange">
                    </v-select>
                </div>
                <div class="filter-item" style="min-width: 200px;">
                    <v-select :options="deliveryOptions" v-model="deliveryFilters" multiple :reduce="o => o.Id"
                        label="Name" placeholder="Giao hàng" @update:model-value="onFilterChange">
                    </v-select>
                </div>
            </div>


        </div>
        <div v-if="!loading" class="table-responsive">
            <table class="table">
                <thead>
                    <tr>
                        <th scope="col" class="wd-lg-5p fixed-column"></th>
                        <th scope="col" class="wd-lg-20p minwidth150">Đơn hàng</th>
                        <th scope="col" class="wd-lg-20p minwidth150">Địa chỉ</th>
                        <th scope="col" class="wd-lg-15p minwidth150">Hàng hóa</th>
                        <th scope="col" class="wd-lg-20p minwidth150">Tài chính</th>
                        <th scope="col" class="wd-lg-20p minwidth150">Hình ảnh</th>
                    </tr>
                </thead>
                <tbody v-if="isLoading">
                    <tr>
                        <td colspan="6" class="tx-semibold text-center text-default pd-y-30">
                            <span class="spinner-border spinner-border-sm mg-r-10"></span>
                            Đang tải dữ liệu...
                        </td>
                    </tr>
                </tbody>
                <tbody v-else-if="!orders || orders.length === 0">
                    <tr>
                        <td colspan="6" class="tx-semibold text-center text-danger pd-y-30">
                            Không tìm thấy dữ liệu!
                        </td>
                    </tr>
                </tbody>
                <tbody v-else>
                    <tr v-for="(order, index) in orders" :key="order.Id"
                        draggable="true" 
                        @dragstart="onDragStart(index, $event)"
                        @dragenter="onDragEnter(index, $event)"
                        @dragover.prevent="onDragOver($event)"
                        @drop="onDrop(index, $event)"
                        :class="{'drag-over-top': dropTargetIndex === index && dragPosition === 'top', 'drag-over-bottom': dropTargetIndex === index && dragPosition === 'bottom'}"
                        class="draggable-row">
                        <td class="fixed-column">
                            <i class="fas fa-grip-vertical text-muted drag-handle me-2" style="cursor: grab;"></i>
                            <div class="checkbox"
                                v-if="order.OrderOps.Status == 1 && order.OrderOps.PhysicalStatus == 12">
                                <div class="form-checkbox custom-control">
                                    <input type="checkbox" class="custom-control-input"
                                        :id="'orderCheckbox_' + order.Id" v-model="selectedOrders" :value="order">
                                    <label :for="'orderCheckbox_' + order.Id" class="custom-control-label mt-1"></label>
                                </div>
                            </div>

                        </td>
                        <td>
                            <div class="tx-13 tx-bold mb-2">
                                <i class="fas fa-barcode mg-r-5"></i>
                                <router-link :to="{ name: 'orderTrack', params: { code: order.Code } }" target="_blank">
                                    {{ order.Code }}
                                </router-link>
                            </div>


                            <span class="tag mg-r-5 mg-b-5" title="Trạng thái">
                                {{ order.OrderOps ? order.OrderOps.StatusStr : 'Không có' }}
                            </span>
                            <span class="tag mg-r-5 mg-b-5" title="Trạng thái vật lý">
                                {{ order.OrderOps ? order.OrderOps.PhysicalStatusStr : 'Không có' }}
                            </span>

                            <div class="tx-12 mb-1 text-muted" v-if="order.PartnerCode">
                                <i class="fas fa-handshake mg-r-5"></i>
                                {{ order.PartnerCode }}
                            </div>

                            <div class="tx-12 mb-2">
                                <i class="fas fa-user-tie mg-r-5"></i>
                                {{ order.SaleUserName }}
                            </div>
                            <div class="tx-12 mb-2">
                                <i class="fas fa-road mg-r-5"></i>
                                {{ order.RouteName }}
                            </div>

                            <div class="tx-12 mb-2" v-if="order.Note != null && order.Note.length > 0">
                                <i class="fas fa-sticky-note mg-r-5"></i>
                                {{ order.Note }}
                            </div>

                        </td>
                        <td>
                            <template v-if="order.Addresses && order.Addresses.length > 0">
                                <div v-for="(addr, idx) in order.Addresses.filter(a => a.AddressType === (order.OrderOps && order.OrderOps.Status === 1 ? 1 : 2))" :key="idx" class="mb-2">
                                    <span class="badge bg-light text-dark mg-b-5">
                                        {{ addr.AddressType === 1 ? 'Lấy hàng' : 'Giao hàng' }}
                                    </span>
                                    <div v-if="addr.Name || addr.PhoneNumber1">
                                        <strong v-if="addr.Name">{{ addr.Name }}</strong>
                                        <span v-if="addr.Name && addr.PhoneNumber1"> | </span>
                                        <strong v-if="addr.PhoneNumber1">{{ addr.PhoneNumber1 }}</strong>
                                        <span v-if="addr.PhoneNumber2"> hoặc <strong>{{ addr.PhoneNumber2 }}</strong></span>
                                    </div>
                                    <p class="mt-1 mb-1">{{ addr.FullAddress }}</p>
                                    <div class="tx-12" v-if="addr.ScheduledTimeStr">
                                        <i class="fas fa-calendar-day mg-r-5"></i> {{ addr.ScheduledTimeStr }}
                                    </div>
                                    <div class="tx-12 text-muted" v-if="addr.Note">
                                        <i>Ghi chú: {{ addr.Note }}</i>
                                    </div>
                                </div>
                            </template>
                            <span v-else>Không có</span>
                        </td>

                        <td>
                            <span v-if="order.Packages == null || order.Packages.length <= 0" class="tx-12 text-muted">Không có thông tin hàng hóa</span>
                            <div v-for="(pkg, idx) in order.Packages" :key="pkg.Id || idx" class="mb-2">
                                <div class="tx-13 tx-bold mb-1 text-primary" v-if="pkg.Name">
                                    <i class="fas fa-box-open mg-r-5"></i>
                                    {{ pkg.Name }}
                                </div>
                                <div class="tx-12">
                                    <i class="fas fa-weight-hanging mg-r-5"></i>
                                    {{ pkg.Weight / 1000 }} kg
                                </div>
                                <div class="tx-12 text-muted">
                                    <i class="fas fa-ruler-combined mg-r-5"></i>
                                    {{ pkg.Length / 10 }} x {{ pkg.Width / 10 }} x {{ pkg.Height / 10 }} cm
                                </div>
                                <hr class="bd mg-t-5 mg-b-5" v-if="idx < order.Packages.length - 1" />
                            </div>
                        </td>

                        <td>
                            <div v-if="order.OrderFin">
                                <div class="tx-12 mb-1">
                                    <span class="text-muted">Tổng cước:</span>
                                    <strong>{{ formatCurrency(order.OrderFin.TotalFee) }}</strong>
                                </div>
                                <template v-if="order.OrderOps && order.OrderOps.Status === 1">
                                    <div class="tx-12 mb-1">
                                        <span class="text-muted">Cước lấy:</span>
                                        <strong>{{ formatCurrency(order.OrderFin.SourceFee) }}</strong>
                                    </div>
                                </template>
                                <template v-else>
                                    <div class="tx-12 mb-1">
                                        <span class="text-muted">Cước giao:</span>
                                        <strong>{{ formatCurrency(order.OrderFin.DestFee) }}</strong>
                                    </div>
                                </template>
                                <div class="tx-12 mb-1" v-if="order.OrderFin.PayFeeTypeStr">
                                    <span class="text-muted">Hình thức:</span>
                                    <strong>{{ order.OrderFin.PayFeeTypeStr }}</strong>
                                </div>
                                <div class="tx-12 mb-1">
                                    <span class="text-muted">Thu hộ:</span>
                                    <strong class="tx-success">{{ formatCurrency(order.OrderFin.CollectAmount) }}</strong>
                                </div>
                            </div>
                            <span v-else>Không có</span>
                        </td>

                        <td>
                            <div v-if="order.MediaItems && order.MediaItems.length > 0">
                                <viewer :images="order.MediaItems.map(m => m.Url)">
                                    <div class="d-flex flex-wrap gap-1">
                                        <img v-for="media in order.MediaItems" :key="media.Id"
                                            :src="media.Url" :alt="media.AltText"
                                            class="media-thumb" style="cursor: pointer;">
                                    </div>
                                </viewer>
                            </div>
                            <span v-else class="text-muted tx-12">Không có</span>
                        </td>

                    </tr>
                </tbody>
            </table>

        </div>
        <pager ref="ctrlPager" v-show="!isLoading && orders.length > 0" @PageSizeChanged="PageSizeChanged"
            @PageIndexChanged="PageIndexChanged" :Total="searchModel.Pagination.Total" :TotalCurrent="orders.length">
        </pager>
    </div>

</template>
<script setup>
import { ref, computed, reactive, onMounted, watch } from 'vue';
import deployService from "@/services/business/deployService";

import Assign from "@/views/business/deployment/components/assign/index.vue";
import { useToast } from "vue-toastification";
const toast = useToast();

const emit = defineEmits(['reload'])

//#region props
const props = defineProps({
    picId: Number

});
//#endregion

//#region DATA
const selectedOrders = ref([]);
const allSelected = ref(false);
const isLoading = ref(true);

const pickupFilters = ref([]);
const deliveryFilters = ref([]);

const pickupOptions = [
    { Id: 'PickingUp', Name: 'Đang lấy' },
    { Id: 'PickedUp', Name: 'Đã lấy' }
];

const deliveryOptions = [
    { Id: 'Delivering', Name: 'Đang giao' },
    { Id: 'Delivered', Name: 'Đã giao' }
];

const orders = reactive([]);
const searchModel = reactive({
    Pagination: {
        Total: 0,
        PageIndex: 1,
        PageSize: 25
    },
    Sort: {
        Predicate: 'CreatedTime',
        Reverse: true
    },
    Search: {
        PredicateObject: {

        }
    }
});
//#endregion


//#region Methods
const formatCurrency = (value) => {
    if (value == null || value === 0) return '0 ₫';
    return new Intl.NumberFormat('vi-VN', { style: 'currency', currency: 'VND' }).format(value);
};

const onFilterChange = () => {
    searchModel.Pagination.PageIndex = 1;
    getOrders();
};

const draggedRowIndex = ref(null);
const dropTargetIndex = ref(null);
const dragPosition = ref(''); // 'top' or 'bottom'

const onDragStart = (index, event) => {
    draggedRowIndex.value = index;
    if (event.dataTransfer) {
        event.dataTransfer.effectAllowed = 'move';
        // Needs some data to work in Firefox
        event.dataTransfer.setData('text/plain', index.toString());
    }
};

const onDragEnter = (index, event) => {
    if (draggedRowIndex.value === null || draggedRowIndex.value === index) return;
    dropTargetIndex.value = index;
    // Determine if drag is over the top or bottom half of the row
    const rect = event.currentTarget.getBoundingClientRect();
    const midY = rect.top + rect.height / 2;
    dragPosition.value = event.clientY < midY ? 'top' : 'bottom';
};

const onDragOver = (event) => {
    // Determine position continuously during dragover
    if (dropTargetIndex.value !== null) {
        const rect = event.currentTarget.getBoundingClientRect();
        const midY = rect.top + rect.height / 2;
        dragPosition.value = event.clientY < midY ? 'top' : 'bottom';
    }
};

const onDrop = async (index, event) => {
    event.preventDefault(); // Required for some browsers
    
    if (draggedRowIndex.value === null || dropTargetIndex.value === null) {
        resetDragState();
        return;
    }

    const fromIndex = draggedRowIndex.value;
    let toIndex = dropTargetIndex.value;

    // Adjust toIndex based on dragPosition
    if (fromIndex < toIndex && dragPosition.value === 'top') {
        toIndex--;
    } else if (fromIndex > toIndex && dragPosition.value === 'bottom') {
        toIndex++;
    }

    if (fromIndex !== toIndex) {
        // Optimistic UI Update
        const itemToMove = orders[fromIndex];
        orders.splice(fromIndex, 1);
        orders.splice(toIndex, 0, itemToMove);

        await saveNewOrder();
    }

    resetDragState();
};

const resetDragState = () => {
    draggedRowIndex.value = null;
    dropTargetIndex.value = null;
    dragPosition.value = '';
};

const saveNewOrder = async () => {
    isLoading.value = true;
    const itemsToUpdate = [];
    const pageOffset = (searchModel.Pagination.PageIndex - 1) * searchModel.Pagination.PageSize;

    orders.forEach((order, index) => {
        itemsToUpdate.push({
            OrderId: order.Id,
            DisplayOrder: pageOffset + index + 1
        });
    });

    const result = await deployService.reorderOrders(itemsToUpdate);
    
    if (result && result.Result === 1) {
        toast.success('Cập nhật thứ tự thành công!');
    } else {
        toast.error('Cập nhật thứ tự thất bại: ' + (result?.Message || 'Vui lòng thử lại.'));
        await getOrders(); // Revert to original order
    }
    isLoading.value = false;
};


const toggleSelectAll = () => {
    if (allSelected.value) {
        selectedOrders.value = orders;
    } else {
        selectedOrders.value = [];
    }
};

const ctrlPager = ref();
function PageSizeChanged(pagesize) {
    searchModel.Pagination.PageSize = pagesize;
    searchModel.Pagination.PageIndex = 1;
    getOrders();
}
function PageIndexChanged(pageIndex) {
    searchModel.Pagination.PageIndex = pageIndex;
    getOrders();
}

const getOrders = async () => {
    isLoading.value = true;

    const requestModel = {
        Pagination: {
            PageIndex: searchModel.Pagination.PageIndex,
            PageSize: searchModel.Pagination.PageSize
        },
        Sort: {
            Predicate: searchModel.Sort.Predicate,
            Reverse: searchModel.Sort.Reverse
        },
        Search: {
            PredicateObject: {
                PicId: props.picId,
                DeployFilter: [...pickupFilters.value, ...deliveryFilters.value]
            }
        }
    };

    var searchResult = await deployService.getDeployDetail(requestModel);
    orders.splice(0, orders.length);
    if (searchResult.Items != null && searchResult.Items.length > 0) {
        searchResult.Items.forEach(o => {
            orders.push(o);
        });
    }
    searchModel.Pagination.Total = searchResult.TotalRecord;
    isLoading.value = false;
};

const reload = async () => {
    emit('reload');
    await getOrders();
};



//#endregion

const selectedOrderIds = computed(() => {
    var rs = [];
    if (selectedOrders.value != null && selectedOrders.value.length > 0) {
        selectedOrders.value.forEach(o => {
            rs.push(o.Id);
        })
    }
    return rs;
});

const isIndeterminate = computed(() => {
    var rs = false;
    if (selectedOrders.value.length > 0 && selectedOrders.value.length < orders.length) rs = true;
    else if (selectedOrders.value.length > 0 && selectedOrders.value.length === orders.length) {
        allSelected.value = true;
    } else if (selectedOrders.value == null || selectedOrders.value.length <= 0) {
        allSelected.value = false;
    }
    return rs;
});




const unassign = async () => {
    var cf = confirm("Bạn chắc chắn muốn bỏ gán?");
    if (cf) {
        isLoading.value = true;
        var model = {
            OrderIds: selectedOrderIds.value,
            UserId: props.picId
        }
        console.log(model);
        var assignResult = await deployService.unassign(model, props.addressType);
        if (assignResult != null && assignResult.Result === 1) {
            toast.success('Thành công!');

        } else {

            toast.error('Thất bại: ' + assignResult.Message);
        }
        isLoading.value = false;
        await getOrders();
    }
};



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

watch(() => props.picId, async (nval) => {
    await getOrders();
})

</script>

<style scoped>
.table thead th {
    border-top-width: 1px;
}

.table thead th.minwidth150 {
    min-width: 150px;
}

.table thead th.minwidth100 {
    min-width: 100px;
}

.table thead th.minwidth200 {
    min-width: 200px;
}

.commands>* {
    width: auto;
}

.btn-group button.btn.nobg {
    background-color: transparent;
    border-color: transparent;
    color: black;
    font-size: .88rem;
    margin-block-start: -5px;
}

.btn-group button.btn.nobg:hover,
.btn-group button.btn.nobg:active,
.btn-group button.btn.nobg:focus {
    background-color: rgba(32, 33, 36, 0.059);
    border-radius: 50%;
    color: black !important;
}

.dropdown-menu {
    box-shadow: 0px 2px 2px 0 rgba(0, 0, 0, .05),
        0 1px 5px 0 rgba(0, 0, 0, .05),
        2px 6px 14px 0px rgba(0, 0, 0, .13)
}

.fixed-column {
    position: sticky;
    left: 0;
    z-index: 1;
    background-color: white;
}

.media-thumb {
    width: 48px;
    height: 48px;
    object-fit: cover;
    border-radius: 4px;
    border: 1px solid #e0e0e0;
}

.gap-1 {
    gap: 0.25rem;
}

.draggable-row {
    transition: background-color 0.2s;
}

.draggable-row:hover {
    background-color: #f8f9fa;
}

.drag-handle {
    opacity: 0.5;
    transition: opacity 0.2s;
}

.draggable-row:hover .drag-handle {
    opacity: 1;
}

.drag-over-top {
    border-top: 2px solid var(--bs-primary) !important;
}

.drag-over-bottom {
    border-bottom: 2px solid var(--bs-primary) !important;
}
</style>
