<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-8">
                            <div class="form-group mb-3">
                                <label>Tên dịch vụ:</label>
                                <Field v-model="productModel.Name" name="Name" type="text" class="form-control"
                                    placeholder="tên dịch vụ" :class="{ 'is-invalid': errors.Name }" />
                                <div class="invalid-feedback">{{ errors.Name }}</div>
                            </div>
                        </div>
                        <div class="col-4">
                            <div class="form-group mb-3">
                                <label>Loại dịch vụ</label>
                                <v-select label="Name" :options="productTypes" v-model="productModel.ProductType"
                                    :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-12">
                            <div class="form-group mb-3">
                                <label>Mô tả ngắn:</label>
                                <textarea rows="6" class="form-control" v-model="productModel.ShortDescription"
                                    placeholder="mô tả ngắn"
                                    :class="{ 'is-invalid': errors.ShortDescription }"></textarea>

                                <div class="invalid-feedback">{{ errors.ShortDescription }}</div>
                            </div>
                        </div>
                        <div class="col-12 mt-2">
                            <div class="form-group">
                                <label>Nội dung dịch vụ:</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="productModel.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({
    Name: Yup.string().required('Tiêu đề dịch vụ không để trống'),
});
//#endregion

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

const formRef = ref();

const editorStore = useEditorStore();

const productTypes = reactive([
    { Id: 1, Name: 'Hàng hóa chung' },
    { Id: 2, Name: 'Xe đạp, xe máy' },
    { Id: 3, Name: 'Hàng gia dụng' },
    { Id: 6, Name: 'Xe tải nguyên chuyến' }

]);

let productModel = reactive({
    Id: 0,
    Name: '',
    ShortDescription: '',
    Description: '',
    TableOfContent: '',
    IsValid: false,
    ProductType: 1
});

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


//#region Methods
const onSubmit = async () => {
    // var result =
    var validateResult = await formRef.value.validate();
    productModel.IsValid = validateResult.valid;
    productModel.Description = tempDescription.value;
    productModel.ProductType = productModel.ProductType;
    return productModel;
};
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.uploadProductContentPicture(formData);
    if (uploadResult != null && uploadResult.Result === 1) {
        productModel.Description += '<img src="' + uploadResult.Url + '">';
    } else {
        toast.error('Thất bại: ' + uploadResult.Message);
    }

};

const init = (initModel) => {
    console.log(initModel);
    productModel.Id = initModel.id;
    productModel.Name = initModel.Name;
    productModel.ShortDescription = initModel.ShortDescription;
    productModel.Description = initModel.Description;
    productModel.ProductType = initModel.ProductType;
    tempDescription.value = productModel.Description;
};

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);
            });

            productModel.TableOfContent = 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(() => productModel.Description, (nval) => {
    generateTOC(nval);
})

defineExpose({
    onSubmit,
    init,
    handleValidate
})


</script>