<template>
    <div>
        <loader v-if="isLoading" class="mt-5 mb-5"></loader>
        <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 class="btn-group mt-2 mg-l-10" v-if="selectedOrders.length > 0">
                <Assign @reload="reload" :orderIds="selectedOrderIds" :addressType="addressType"></Assign>

            </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-25p 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>

                    </tr>
                </thead>
                <tbody>
                    <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="far fa-clock mg-r-5"></i>
                                {{ order.CreatedTimeDisplay }}
                            </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">
                                <i class="fas fa-dollar-sign mg-r-5"></i>
                                {{ order.OrderFin ?
                                    vueNumberFormat(order.OrderFin.TotalFee, {
                                        precision: 0, prefix: '', suffix: 'đ', decimal:
                                            ',', thousand: '.'
                                    }) : 'Không có' }}

                            </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">
                                {{ order.OrderOps ? order.OrderOps.PhysicalStatusStr : 'Không có' }}
                            </span>

                        </td>
                        <td v-html="getAddress(order, addressType)"></td>
                        <td>
                            <span v-if="order.Packages == null || order.Packages.length <= 0">Không có</span>
                            <div v-for="pkg in order.Packages">
                                <div>{{ pkg.Name }} | <b class="tx-12">Slg:{{ pkg.Quantity }}</b> </div>
                            </div>
                            <hr />

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

                                </viewer>
                            </div>
                        </td>

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

        </div>
    </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";


const emit = defineEmits(['reload'])

//#region props
const props = defineProps({
    addressType: Number,
    locationId: Number

});
//#endregion

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


//#region Methods
const getAddress = (order, type) => {
    var addressInfo = "";
    var contactName = "";
    var contactPhone1 = "";
    var contactPhone2 = "";
    var contactAddress = "";
    var outputHtml = "";
    var addressTypetmp = type === 5 ? 2 : type;
    var addresses = order.Addresses;
    if (order.OrderOps.PhysicalStatus == 13 || order.OrderOps.PhysicalStatus == 11
        || order.OrderOps.PhysicalStatus == 12 || order.OrderOps.PhysicalStatus == 1
    ) {
        addressTypetmp = 1;
    } else {
        addressTypetmp = 2;
    }
    if (addresses && addresses.length > 0) {

        const address = addresses.find(addr => addr.AddressType === addressTypetmp);
        if (address) {
            contactName = `<b>${address.Name}</b> | `;
            outputHtml += contactName;
            contactPhone1 = `<b>${address.PhoneNumber1}</b>`;
            outputHtml += contactPhone1;
            if (address.PhoneNumber2 != null && address.PhoneNumber2.length > 0) {
                contactPhone2 = `hoặc <b>${address.PhoneNumber2}</b>`;
                outputHtml += contactPhone2;
            }
            contactAddress = `<p class='mt-1 mb-1'>${address.FullAddress}</p>`;
            outputHtml += contactAddress;


            if (address.ScheduledTimeStr != null && address.ScheduledTimeStr.length > 0) {
                // contactPhone2 = `hoặc <b>${address.PhoneNumber2}</b>`;
                outputHtml += `<i class='fas fa-calendar-day mg-r-5'></i> ${address.ScheduledTimeStr}`;
            }
            if (address.Note != null && address.Note.length > 0) {
                // contactPhone2 = `hoặc <b>${address.PhoneNumber2}</b>`;
                outputHtml += `<br/><i class='tx-13'>Ghi chú: ${address.Note}</i>`;
            }

        }
    }
    return outputHtml;
};


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



const getOrders = async () => {
    isLoading.value = true;
    selectedOrders.value = [];
    var searchResult = await deployService.getDeployOrder(props.addressType, props.locationId);
    orders.splice(0, orders.length);
    if (searchResult.Items != null && searchResult.Items.length > 0) {
        searchResult.Items.forEach(o => {
            orders.push(o);
        });
    }
    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 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;
});

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

watch(() => props.locationId, 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;
    /* Đảm bảo cột cố định không bị che phủ bởi các cột khác */
}
</style>
