<template>
    <div>
        <div v-if="loading" class="row">
            <div class="col-12 tx-semibold text-center text-default">
                <span class="spinner-border spinner-border-sm"></span>
            </div>
        </div>
        <Form v-if="!loading" @submit="onSubmit" :validation-schema="schema" v-slot="{ errors, isSubmitting }"
            class="row">

            <div class="col-6">
                <div class="form-group mb-3">
                    <label>Tên danh mục</label>
                    <Field v-model="categoryModel.Name" name="Name" type="text" class="form-control"
                        placeholder="tên menu" :class="{ 'is-invalid': errors.Name }" />
                    <div class="invalid-feedback">{{ errors.Name }}</div>
                </div>
            </div>
            <div class="col-6">
                <div class="form-group mb-3">
                    <label>Danh mục cha</label>
                    <v-select label="Name" :options="parents" v-model="categoryModel.ParentId"
                        :reduce="(option) => option.Id">
                        <template v-slot:no-options="{ search, searching }">
                            <template v-if="searching">
                                Không có kết quả cho <em>{{ search }}</em>.
                            </template>
                            <span v-else style="opacity: 0.8">Không có bản ghi nào</span>
                        </template>
                    </v-select>
                </div>
            </div>
            <div class="col-4">
                <div class="form-group mb-3">
                    <label>Loại danh mục</label>
                    <v-select label="Name" :options="contentTypes" v-model="categoryModel.ContentType"
                        :reduce="(option) => option.Id">
                        <template v-slot:no-options="{ search, searching }">
                            <template v-if="searching">
                                Không có kết quả cho <em>{{ search }}</em>.
                            </template>
                            <span v-else style="opacity: 0.8">Không có bản ghi nào</span>
                        </template>
                    </v-select>
                </div>
            </div>
            <div class="col-4">
                <div class="form-group mb-3">
                    <label>Thứ tự hiển thị:</label>

                    <Field v-model="categoryModel.DisplayOrder" name="DisplayOrder" type="number" class="form-control"
                        placeholder="thứ tự hiển thị" :class="{ 'is-invalid': errors.DisplayOrder }" />
                    <ErrorMessage class="invalid-error" name="DisplayOrder" />

                </div>
            </div>
            <div class="col-4">
                <div class="form-group mt-4 pt-2">

                    <label class="ckbox">
                        <i class="fa fa-satellite-dish"></i>
                        <input v-model="categoryModel.IsFeaturedPost" type="checkbox" class="mb-2">
                        <span class="p-0">Là danh mục nổi bật</span>
                    </label>
                </div>
            </div>
            <div class="col-12">
                <div class="form-group">
                    <editor v-model="categoryModel.Description" :init="editorStore.init" :toolbar="editorStore.toolbar"
                        :plugins="editorStore.plugins" style="min-height:400px;">
                    </editor>
                </div>
            </div>


            <div class="col-12 ">
                <div class="d-flex flex-row-reverse">
                    <button @click="cancel" type="button" class="btn btn-main-default mg-l-15">
                        Bỏ qua
                    </button>
                    <button type="submit" class="btn btn-main-primary" :disabled="isSubmitting">
                        <span v-show="isSubmitting" class="spinner-border spinner-border-sm"></span>
                        Xác nhận
                    </button>
                </div>
            </div>
        </Form>
    </div>
</template>
<script setup>

//#region Imports....
import { ref, onMounted, reactive, watch } from 'vue';
import { Form, Field, ErrorMessage } from 'vee-validate';
import * as Yup from 'yup';
import { useEditorStore } from '@/stores';

//#endregion

//#region Services
import categoryService from "@/services/categoryService";
//#endregion


//#region Toast
import { useToast } from "vue-toastification";
const toast = useToast();
//#endregion


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

//#region data
const editorStore = useEditorStore();

//#endregion


const emit = defineEmits(['cancel']);


//#region Models
const loading = ref(false);

const parents = reactive([]);
const contentTypes = reactive([
    { Id: 1, Name: 'Bài viết' },
    { Id: 2, Name: 'Dịch vụ' },
    { Id: 3, Name: 'Việc làm' }
]);

let categoryModel = reactive({
    Id: 0,
    Name: '',
    Description: '',
    ParentId: null,
    DisplayOrder: 0,
    IsFeaturedPost: false,
    ContentType: 1
});


//#endregion

//#region Validations
const schema = Yup.object().shape({
    Name: Yup.string().required('Tên danh mục không để trống'),
});
//#endregion

//#region Methods


async function getParents() {
    parents.splice(0, parents.length);
    var parentResult = await categoryService.getTree("", categoryModel.ContentType);
    if (parentResult != null && parentResult.length > 0) {
        parentResult.forEach(menu => {
            parents.push(menu);
        });
    }
}


async function getById(id) {

    var categoryResult = await categoryService.getById(id);
    categoryModel.Id = categoryResult.Id;
    categoryModel.Name = categoryResult.Name;
    categoryModel.Description = categoryResult.Description;
    categoryModel.DisplayOrder = categoryResult.DisplayOrder;
    categoryModel.IsFeaturedPost = categoryResult.IsFeaturedPost;
    categoryModel.ContentType = categoryResult.ContentType;

    if (categoryResult.ParentId == 0) {
        categoryModel.ParentId = null;
    } else {
        categoryModel.ParentId = categoryResult.ParentId;
    }


}
async function onSubmit() {
    // var temp = document.createElement("div");
    // temp.innerHTML = categoryModel.Description;
    // var textContent = temp.textContent || temp.innerText || "";
    // if (textContent.length > 0) {
    //     var normalTextContent = textContent.replace(/(\r\n|\n|\r)/gm, "").trim();
    //     console.log(normalTextContent);
    // }



    categoryModel.UpdatedByUserName = "";
    categoryModel.UpdatedBy = 0;
    if (categoryModel.ParentId == null) {
        categoryModel.ParentId = 0;
    }
    var categoryResult = await categoryService.createOrUpdate(categoryModel);
    if (categoryResult != null && categoryResult.Result === 1) {
        toast.success('Thành công!');
        cancel();
    } else {
        toast.error('Thất bại: ' + categoryResult.Message);
    }

}

function cancel() {
    emit('cancel');
}

//#endregion



//#region Events
onMounted(async () => {
    loading.value = true;
    await getParents();
    if (props.id > 0) {
        await getById(props.id);
    }
    loading.value = false;



})


watch(() => categoryModel.ContentType, (nval) => {
    getParents();
})
//#endregion



</script>

<style scoped>
.tox-tinymce-aux {
    z-index: 999999 !important;
}

.tox.tox-tinymce-aux {
    z-index: 999999 !important;
}

.tox.tox-tinymce-aux,
.tox-fullscreen .tox.tox-tinymce-aux {
    z-index: 999999;
}
</style>