<template>
    <div>

        <div lass="commands pd-l-10 mg-b-20">
            <div class="btn-group mb-2 mt-2" style="margin-inline-start: 13px;">
                <div class="checkbox" v-if="orders != null && orders.length > 0">
                    <div class="form-checkbox custom-control">
                        <input :indeterminate="isIndeterminate" v-model="allSelected" @change="toggleSelectAll"
                            id="cbxAll" type="checkbox" class="custom-control-input">
                        <label for="cbxAll" class="custom-control-label mt-1"></label>
                    </div>
                </div>
            </div>
            <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>

        <div class="table-responsive">
            <table class="table">
                <thead>
                    <tr>
                        <th scope="col" class="wd-lg-5p fixed-column"></th>
                        <th scope="col" class="wd-lg-25p minwidth150">Đơn hàng</th>
                        <th scope="col" class="wd-lg-20p minwidth150">Địa chỉ</th>
                        <th scope="col" class="wd-lg-20p minwidth150">Sản Phẩm</th>
                        <th scope="col" class="wd-lg-20p minwidth150">Ảnh</th>
                        <th scope="col" class="wd-lg-10p minwidth150">Lệnh</th>
                    </tr>
                </thead>
                <tbody v-if="orders != null && orders.length > 0 && !isLoading">
                    <tr v-for="order in orders" :key="order.Id">
                        <td class=" fixed-column">
                            <div class="checkbox">
                                <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>

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


                            <span class="tag mg-r-5 mg-b-5" title="Trạng thái">
                                {{ order.StatusStr }}
                            </span>

                            <span class="tag mg-r-5 mg-b-5" title="Trạng thái">
                                {{ order.PhysicalStatusStr }}
                            </span>

                        </td>

                        <td>
                            <template v-for="(addressItem, index) in order.OrderAddresses">
                                <template v-if="addressItem.AddressType == 1">
                                    <div class="d-flex flex-row justify-content-between">
                                        <div class="address-info">
                                            <div class="tx-14 mg-b-10 mg-t-10">
                                                <b>{{ addressItem.AddressTypeStr }}</b>
                                            </div>
                                            <h6 class="tx-13">
                                                <i class="far fa-user mg-r-10"></i>
                                                {{ addressItem.Name }} | {{ addressItem.PhoneNumber1 }}

                                            </h6>
                                            <div class="tx-13 mg-b-5">
                                                <i class="fas fa-map-marker-alt mg-r-10"></i>
                                                {{ addressItem.Address1 }}, {{ addressItem.WardName }}, {{
                                                    addressItem.DistrictName }}, {{ addressItem.CityName }}
                                            </div>

                                        </div>
                                    </div>
                                </template>

                            </template>
                        </td>

                        <td>
                            <span v-if="order.OrderPackages == null || order.OrderPackages.length <= 0">Không có</span>
                            <div v-for="pkg in order.OrderPackages">
                                <div>{{ pkg.Name }} | <b class="tx-12">Slg:{{ pkg.Quantity }}</b> </div>
                            </div>

                            <hr />

                        </td>
                        <td>
                            <div v-if="order.MediaFiles != null && order.MediaFiles.length > 0" class="mediaContainer">
                                <viewer v-if="order.MediaFiles != null && order.MediaFiles.length > 0">
                                    <img v-for="img in order.MediaFiles"
                                        class="avatar-md mg-sm-r-10 mg-b-10 mg-sm-b-0 align-self-center" :key="img.Id"
                                        :src="img.Path" style="cursor: pointer;">

                                </viewer>
                            </div>
                        </td>
                        <td>
                            <button type="button" @click="singleInbound(order.Id)" class="btn btn-warning btn-wave">Nhận
                                hàng</button>
                        </td>
                    </tr>

                </tbody>
            </table>

        </div>
        <loader v-if="isLoading" lass="mt-5 mb-5" style="margin-bottom: 20px;"></loader>
        <empty v-if="!isLoading && orders.length <= 0" :border="false"></empty>
        <pager class="mb-3" ref="ctrlPager" v-if="!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 warehouseService from "@/services/business/warehouseService";
import { forEach } from 'lodash';

import { useToast } from "vue-toastification";
const toast = useToast();



const emit = defineEmits(['reload'])

//#region props
const props = defineProps({
    driverId: Number
});
//#endregion

//#region DATA
const ctrlPager = ref();
const searchModel = reactive({
    Pagination: {
        Total: 0,
        PageIndex: 1,
        PageSize: 25
    },
    Sort: {
        Predicate: '',
        Reverse: true
    },
    Search: {
        PredicateObject: {


        }
    }
});


const selectedOrders = ref([]);
const allSelected = ref(false);
const isLoading = ref(false);
const orders = reactive([]);

//#endregion

//#region Methods

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

const getOrders = async () => {
    console.log(props.driverId);
    selectedOrders.value = [];
    orders.splice(0, orders.length);
    if (props.driverId == null || props.driverId <= 0) {
        console.log(props.driverId);
        console.log('driverId is null');
        return;
    } else {
        isLoading.value = true;
        selectedOrders.value = [];
        var searchResult = await warehouseService.GetInboundOrders(props.driverId,
            searchModel.Pagination.PageIndex
            , searchModel.Pagination.PageSize
        );
        orders.splice(0, orders.length);
        if (searchResult != null && searchResult.length > 0) {
            searchResult.forEach(o => {
                var routeName = '';
                if (o.OrderAddresses != null && o.OrderAddresses.length > 0) {
                    forEach(o.OrderAddresses, function (oa, index) {
                        routeName += oa.CityName;
                        if (index < o.OrderAddresses.length - 1) {
                            routeName += ' -> ';
                        }
                    });
                }
                o.RouteName = routeName;
                orders.push(o);
            });
        }
        isLoading.value = false;
        console.log(ctrlPager.value);
    }

};

const singleInbound = async (id) => {
    var cf = confirm('Bạn có chắc chắn muốn nhận hàng không?');
    if (!cf) return;
    await inbound([id]);
};
const multiInbound = async () => {
    var cf = confirm('Bạn có chắc chắn muốn nhận hàng không?');
    if (!cf) return;
    console.log(selectedOrderIds.value);
};

const inbound = async (ids) => {
    isLoading.value = true;
    var model = {
        OrderIds: ids
    }
    var inboundResult = await warehouseService.Inbound(model);

    if (inboundResult != null && inboundResult.Result === 1) {
        toast.success('Thành công!');
    } else {
        toast.error('Thất bại vì ' + inboundResult.Message);
    }
    isLoading.value = false;
    await getOrders();
};


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



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 orders = computed(() => {
//     return props.ordersData;
// });


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

watch(() => props.driverId, (newVal, oldVal) => {
    console.log('driverId changed');
    if (newVal !== oldVal) {
        getOrders();
    }
});


onMounted(async () => {
    //await getParents();
    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;
    /* Đảm bảo cột cố định không bị che phủ bởi các cột khác */
}
</style>
