<template>
    <div>

        <div class="card-body p-0 ht-250" style="overflow: auto;">
            <!-- <div class="input-group" style="position: absolute;z-index: 9;">
                <input class="form-control rounded-0" placeholder="từ khóa..." type="text">
                <button class="btn btn-primary rounded-0" type="button"><i class="fa fa-plus"></i></button>
            </div> -->
            <p class="text-center text-default mt-3" v-if="loading">
                <span class="spinner-border spinner-border-sm"></span>
            </p>
            <div>
                <div class="d-flex p-2 border-top" v-for="item in items" v-if="!loading">
                    <label :key="item.id" class="ckbox">
                        <input class="mb-2" type="checkbox" :value="item.Id" v-model="selected">
                        <span>{{ item.Name }}</span>
                    </label>
                </div>
            </div>

        </div>
        <div class="card-footer p-2">
            <b>Đã chọn:</b>
            <div class="tags">
                <span class="tag tag-default" v-for="category in selectedCategories">{{ category.RawName }}</span>
            </div>
        </div>
    </div>
</template>
<script setup>


//#region Imports
import { ref, reactive, onMounted, watch, computed } from 'vue';
import categoryService from "@/services/categoryService";
//#endregion

//#region props
const props = defineProps({
    modelValue: Array
})
//#endregion

//#region data
const items = reactive([]);
const selected = ref([]);
const loading = ref(false);

//#endregion

//#region emit
// const emit = defineEmits(['update:modelValue']);
// watch(selected, (nval) => {
//     console.log(nval);
// })

const selectedCategories = computed(() => {
    var selectedIds = selected.value;
    return items.filter(c => selectedIds.includes(c.Id));
});

//#endregion


//#region methods
async function getCategories() {
    items.splice(0, items.length);
    var catResult = await categoryService.getTree("", 2);
    if (catResult != null && catResult.length > 0) {
        catResult.forEach(cat => {
            items.push(cat);
        });
    }
}
const onSubmit = async () => {

    var selectedCat = selectedCategories.value;
    var submitCats = [];
    if (selectedCat != null && selectedCat.length > 0) {
        selectedCat.forEach(cat => {
            submitCats.push({
                Id: cat.Id,
                Name: cat.RawName
            });
        });

    }
    return submitCats;
};

const init = async (initModel) => {
    if (initModel.ProductCategoryModels != null && initModel.ProductCategoryModels.length > 0) {
        initModel.ProductCategoryModels.forEach(cat => {
            selected.value.push(cat.Id);
        });
    }
};

//#endregion

//#region Events
onMounted(async () => {
    loading.value = true;
    await getCategories();
    loading.value = false;

});
//#endregion

defineExpose({
    onSubmit,
    init
})


</script>