<template>
    <div class="card shadow-none rounded-0" style="min-height: 100vh;">
        <div class="card-body">
            <Form ref="formRef" v-if="!loading" @submit="onSubmit" :onValidated="handleValidate"
                :validation-schema="schema" v-slot="{ errors, isSubmitting }" class="row">
                <div class="col-lg-12">
                    <div class="row">
                        <div class="col-6">
                            <div class="form-group mb-3">
                                <label>Tiêu đề topic:</label>
                                <Field v-model="topicModel.Title" name="Title" type="text" class="form-control"
                                    placeholder="tiêu đề topic" :class="{ 'is-invalid': errors.Title }" />
                                <div class="invalid-feedback">{{ errors.Title }}</div>
                            </div>
                        </div>
                        <div class="col-6">
                            <div class="form-group mb-3">
                                <label>Tên hệ thống:</label>
                                <Field v-model="topicModel.SystemName" name="SystemName" type="text"
                                    class="form-control" placeholder="tên hệ thống"
                                    :class="{ 'is-invalid': errors.SystemName }" />
                            </div>
                        </div>
                        <div class="col-3 mt-3">
                            <div class="form-check">
                                <input type="checkbox" class="form-check-input" id="includeInFooterBottom"
                                    v-model="topicModel.IncludeInFooterBottom">
                                <label class="form-check-label" for="includeInFooterBottom">
                                    Hiển thị trong footer bottom
                                </label>
                            </div>
                        </div>
                        <div class="col-3 mt-3">
                            <div class="form-check">
                                <input type="checkbox" class="form-check-input" id="includeInFooterColumn1"
                                    v-model="topicModel.IncludeInFooterColumn1">
                                <label class="form-check-label" for="includeInFooterColumn1">
                                    Hiển thị trong footer column 1
                                </label>
                            </div>
                        </div>
                        <div class="col-3 mt-3">
                            <div class="form-check">
                                <input type="checkbox" class="form-check-input" id="includeInFooterColumn2"
                                    v-model="topicModel.IncludeInFooterColumn2">
                                <label class="form-check-label" for="includeInFooterColumn2">
                                    Hiển thị trong footer column 2
                                </label>
                            </div>
                        </div>
                        <div class="col-3 mt-3">
                            <div class="form-check">
                                <input type="checkbox" class="form-check-input" id="includeInFooterColumn3"
                                    v-model="topicModel.IncludeInFooterColumn3">
                                <label class="form-check-label" for="includeInFooterColumn3">
                                    Hiển thị trong footer column 3
                                </label>
                            </div>
                        </div>
                        <div class="col-12 mt-4">
                            <div class="form-group">
                                <label>Nội dung topic:</label><br>

                                <button @click="addPicture" type="button"
                                    class="btn btn-sm btn-outline-secondary button-icon mb-2">
                                    <i class="fe fe-camera me-2"></i>Thêm ảnh
                                </button>
                                <br /><small><i>Tự động tạo đề mục với các thẻ <b>H3, H4</b></i></small>
                                <editor v-model="topicModel.Description" :init="editorStore.init"
                                    :toolbar="editorStore.toolbar" :plugins="editorStore.plugins"
                                    style="min-height:535px;">
                                </editor>
                            </div>
                        </div>


                    </div>
                </div>

            </Form>
        </div>
    </div>
</template>
<script setup>
import { ref, onMounted, reactive, watch } from 'vue';
import { Form, Field, ErrorMessage } from 'vee-validate';
import * as Yup from 'yup';
import { useEditorStore } from '@/stores';

import _ from 'lodash';

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

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

//#region Validations
const schema = Yup.object().shape({
    Title: Yup.string().required('Tiêu đề topic không để trống'),
});
//#endregion

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

const formRef = ref();

const editorStore = useEditorStore();

let topicModel = reactive({
    Id: 0,
    SystemName: '',
    Title: '',
    Description: '',
    TOC: '',
    IncludeInFooterBottom: false,
    IncludeInFooterColumn1: false,
    IncludeInFooterColumn2: false,
    IncludeInFooterColumn3: false,
    IsValid: false
});

let tempDescription = ref('');
//#endregion


//#region Methods
const onSubmit = async () => {
    // var result =
    var validateResult = await formRef.value.validate();
    topicModel.IsValid = validateResult.valid;
    topicModel.Description = tempDescription.value;
    topicModel.IncludeInFooterBottom = topicModel.IncludeInFooterBottom ? 1 : 0;
    topicModel.IncludeInFooterColumn1 = topicModel.IncludeInFooterColumn1 ? 1 : 0;
    topicModel.IncludeInFooterColumn2 = topicModel.IncludeInFooterColumn2 ? 1 : 0;
    topicModel.IncludeInFooterColumn3 = topicModel.IncludeInFooterColumn3 ? 1 : 0;
    return topicModel;
};
const handleValidate = () => {
    console.log("Gọi validate");
}

const addPicture = async () => {
    var selectedFile = null;
    var input = document.createElement('input');
    input.type = 'file';
    input.click();
    input.onchange = e => {
        selectedFile = e.target.files[0];
        uploadContentPicture(selectedFile);
    }
};

const uploadContentPicture = async (selectedFile) => {

    const formData = new FormData();
    formData.append(selectedFile.name, selectedFile);
    var uploadResult = await pictureService.uploadTopicContentPicture(formData);
    if (uploadResult != null && uploadResult.Result === 1) {
        topicModel.Description += '<img src="' + uploadResult.Url + '">';
    } else {
        toast.error('Thất bại: ' + uploadResult.Message);
    }

};

const init = (initModel) => {
    console.log(initModel);
    topicModel.Id = initModel.id;
    topicModel.SystemName = initModel.SystemName;
    topicModel.Title = initModel.Title;
    topicModel.Description = initModel.Description;
    topicModel.TOC = initModel.TOC;
    topicModel.IncludeInFooterBottom = initModel.IncludeInFooterBottom;
    topicModel.IncludeInFooterColumn1 = initModel.IncludeInFooterColumn1;
    topicModel.IncludeInFooterColumn2 = initModel.IncludeInFooterColumn2;
    topicModel.IncludeInFooterColumn3 = initModel.IncludeInFooterColumn3;
};

const generateTOC = _.debounce((htmlContent) => {
    if (htmlContent != null && htmlContent.length > 0) {
        let frag = document.createRange().createContextualFragment(htmlContent);
        const h3Elements = frag.querySelectorAll("h3");
        if (h3Elements != null && h3Elements.length > 0) {
            var h3Tags = [];
            var slugList = [];
            var toc = document.createElement('ul');
            h3Elements.forEach((h3) => {
                h3 = removeAttributes(h3);

                var innerText = h3.innerText;
                var slug = convertToSlug(innerText);

                var tocItem = document.createElement("li");
                var tocItemLink = document.createElement("a");
                tocItemLink.setAttribute("href", "#" + slug);
                tocItemLink.innerText = innerText;
                tocItem.appendChild(tocItemLink);
                toc.appendChild(tocItem);


                h3Tags.push(innerText);
                slugList.push(slug);
                h3.setAttribute("id", slug);
            });

            topicModel.TOC = toc.outerHTML;

        }

        var div = document.createElement('div');
        div.appendChild(frag.cloneNode(true));

        tempDescription.value = div.innerHTML;
    }
}, 500);

const convertToSlug = (path) => {
    var unsignPath = removeVietnameseTones(path);
    return unsignPath
        .toLowerCase()
        .replace(/ /g, '-') // Thay thế khoảng trắng bằng dấu gạch ngang
        .replace(/[^\w-]+/g, '');
}

const removeVietnameseTones = (str) => {
    str = str.replace(/à|á|ạ|ả|ã|â|ầ|ấ|ậ|ẩ|ẫ|ă|ằ|ắ|ặ|ẳ|ẵ/g, "a");
    str = str.replace(/è|é|ẹ|ẻ|ẽ|ê|ề|ế|ệ|ể|ễ/g, "e");
    str = str.replace(/ì|í|ị|ỉ|ĩ/g, "i");
    str = str.replace(/ò|ó|ọ|ỏ|õ|ô|ồ|ố|ộ|ổ|ỗ|ơ|ờ|ớ|ợ|ở|ỡ/g, "o");
    str = str.replace(/ù|ú|ụ|ủ|ũ|ư|ừ|ứ|ự|ử|ữ/g, "u");
    str = str.replace(/ỳ|ý|ỵ|ỷ|ỹ/g, "y");
    str = str.replace(/đ/g, "d");
    str = str.replace(/À|Á|Ạ|Ả|Ã|Â|Ầ|Ấ|Ậ|Ẩ|Ẫ|Ă|Ằ|Ắ|Ặ|Ẳ|Ẵ/g, "A");
    str = str.replace(/È|É|Ẹ|Ẻ|Ẽ|Ê|Ề|Ế|Ệ|Ể|Ễ/g, "E");
    str = str.replace(/Ì|Í|Ị|Ỉ|Ĩ/g, "I");
    str = str.replace(/Ò|Ó|Ọ|Ỏ|Õ|Ô|Ồ|Ố|Ộ|Ổ|Ỗ|Ơ|Ờ|Ớ|Ợ|Ở|Ỡ/g, "O");
    str = str.replace(/Ù|Ú|Ụ|Ủ|Ũ|Ư|Ừ|Ứ|Ự|Ử|Ữ/g, "U");
    str = str.replace(/Ỳ|Ý|Ỵ|Ỷ|Ỹ/g, "Y");
    str = str.replace(/Đ/g, "D");
    // Some system encode vietnamese combining accent as individual utf-8 characters
    // Một vài bộ encode coi các dấu mũ, dấu chữ như một kí tự riêng biệt nên thêm hai dòng này
    str = str.replace(/\u0300|\u0301|\u0303|\u0309|\u0323/g, ""); // ̀ ́ ̃ ̉ ̣  huyền, sắc, ngã, hỏi, nặng
    str = str.replace(/\u02C6|\u0306|\u031B/g, ""); // ˆ ̆ ̛  Â, Ê, Ă, Ơ, Ư
    // Remove extra spaces
    // Bỏ các khoảng trắng liền nhau
    str = str.replace(/ + /g, " ");
    str = str.trim();
    // Remove punctuations
    // Bỏ dấu câu, kí tự đặc biệt
    str = str.replace(/!|@|%|\^|\*|\(|\)|\+|\=|\<|\>|\?|\/|,|\.|\:|\;|\'|\"|\&|\#|\[|\]|~|\$|_|`|-|{|}|\||\\/g, " ");
    return str;
};

const removeAttributes = (element) => {
    while (element.attributes.length > 0) {
        element.removeAttribute(element.attributes[0].name);
    }
    return element;
};

//#endregion

watch(() => topicModel.Description, (nval) => {
    generateTOC(nval);
})

defineExpose({
    onSubmit,
    init,
    handleValidate
})


</script>