<template>
    <div class="row bg-white padding-40">
        <div class="col">
            <loading-component style="height: 300px; top: 0;" key="1" color="success" v-show="isLoading" ></loading-component>
            <div class="row justify-content-center" v-show="!isLoading">
                <div class="col">
                    <div class="row m-b-20">
                        <div class="col">
                            <h3 class="all-caps text-center">Please select the supplier.</h3>
                        </div>
                    </div>
                    <div class="row m-b-20">
                        <div class="col">
                            <list-component section="supplierListSection" :endpoint="route('api.company.list')" :options="{business_type: 3}">
                                <template #list="{data}">
                                    <div class="row">
                                        <div class="col">
                                            <select-individual-supplier-form-component :data="data" :selectedSupplier="selectedSupplier" @select="updateList($event)"></select-individual-supplier-form-component>
                                        </div>
                                    </div>
                                </template>
                            </list-component>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col">
                            <div class="btn btn-sm btn-success btn-block b-rad-none" @click="submitForm()">Confirm</div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import { useFormHandler } from '@/composables/useFormHandler';
import route from '@/general/functions/router';

const props = defineProps<{
    section: string;
}>();

const emit = defineEmits<{
    (e: 'select', selected: any[]): void;
}>();

const { isLoading, closeModal } = useFormHandler({ section: props.section });
const selectedSupplier = ref<any[]>([]);

const updateList = (supplier: any) => {
    const index = selectedSupplier.value.indexOf(supplier);
    if (index > -1) {
        selectedSupplier.value.splice(index, 1);
    } else {
        selectedSupplier.value.push(supplier);
    }
};

const submitForm = () => {
    emit('select', selectedSupplier.value);
    closeModal();
};
</script>
