<template>
    <div>
        <Modal :title="modalTitle" ref="modal" @close="closeExplnumForm" class="explnum-collections-modal"
            :modal-style="modalStyle">
            <form @submit.prevent="submitExplnumForm($event)"
                :action="'./catalog.php?categ=docnum_collections&sub=add&action=save&id=' + currentExplnumEditedId"
                v-html="explnumForm"></form>
        </Modal>
        <Modal :title="messages.get('docnums', 'modale_association_title')" ref="modalAssociation"
            :modal-style="modalStyle">
            <form>
                <div class='row explnum-collection-row'>
                    <div class='colonne25'>
                        <label for='index_docnums'>{{ messages.get("docnums", "index_docnums") }}</label>
                    </div>
                    <div class='colonne75'>
                        <input type="checkbox" id="index_docnums" name="index_docnums"
                            v-model="associationSettings.indexDocnums" />
                    </div>
                </div>
                <div class='row explnum-collection-row' v-if="lenders.length">
                    <div class='colonne25'>
                        <label for='lender'>{{ messages.get("docnums", "lenders") }}</label>
                    </div>
                    <div class='colonne75'>
                        <select id="lenders" name="lenders" v-model="associationSettings.lenders" multiple>
                            <option v-for="lender in lenders" :key="lender.idlender" :value="lender.idlender">
                                {{ lender.lender_libelle }}</option>
                        </select>
                    </div>
                </div>
                <div class='row explnum-collection-row' v-if="locations.length">
                    <div class='colonne25'>
                        <label for='docsLocation'>{{ messages.get("docnums", "docs_location") }}</label>
                    </div>
                    <div class='colonne75'>
                        <select id="docsLocation" name="docsLocation" v-model="associationSettings.docsLocation"
                            multiple>
                            <option v-for="location in locations" :key="location.idlocation"
                                :value="location.idlocation">
                                {{ location.location_libelle }}</option>
                        </select>
                    </div>
                </div>
                <div v-if="licences.length">
                    <div v-for="(selectedLicence, index) in selectedLicences" :key="index">
                        <div class='row explnum-collection-row'>
                            <div class='colonne25' v-if="index == 0">
                                <label for='explnumLicences'>{{ messages.get("docnums", "explnum_licences") }}</label>
                            </div>
                            <div class='colonne75'>
                                <select id="explnumLicences" name="explnumLicences" v-model="selectedLicence.idLicence"
                                    @change="getProfiles(index)">
                                    <option value="" disabled>{{ messages.get("docnums", "select_licence") }}</option>
                                    <option v-for="licence in licences" :key="licence.id_explnum_licence"
                                        :value="licence.id_explnum_licence">
                                        {{ licence.explnum_licence_label }}</option>
                                </select>
                            </div>
                        </div>
                        <div class='row explnum-collection-row explnum-licence-profiles'
                            v-if="selectedLicence.profiles.length">
                            <div v-for="profile in selectedLicence.profiles" :key="profile.idProfile + '_' + index">
                                <input type="radio" :id="'licenceProfile' + profile.idProfile + '_' + index"
                                    :name="'licenceProfile' + profile.idProfile + '_' + index"
                                    v-model="associationSettings.licenceProfiles[index]" :value="profile.idProfile" />
                                <label :for="'licenceProfile' + profile.idProfile + '_' + index"><img
                                        :src="profile.logoUrl" :alt="profile.label" :title="profile.label"></label>
                            </div>
                        </div>
                    </div>
                    <div>
                        <button type="button" class="bouton" @click.prevent="addSelectedLicence"
                            :disabled="!canAddLicence">+</button>
                    </div>
                </div>
                <div class="row explnum-collection-row">
                    <div class='left'>
                        <input type="button" class="bouton" :value="messages.get('docnums', 'associate')"
                            @click.prevent="associate">
                    </div>
                    <div class='right'>
                        <input type="button" class="bouton" :value="messages.get('common', 'cancel')"
                            @click.prevent='$refs.modalAssociation.close()'>
                    </div>
                </div>
            </form>
        </Modal>
        <div class="explnum-add-buttons">
            <button type="button" @click.prevent="openExplnumForm(0)"
                class="bouton">{{ messages.get('docnums', 'add_explnum') }}</button>
        </div>
        <div class="explnum-grid">
            <div v-for="explnum in explnums" :key="explnum.explnum_id" class="explnum-item">
                <div class="explnum-actions">
                    <button type="button" class="bouton" @click.prevent="openExplnumForm(explnum.explnum_id)">
                        <i class="fa fa-pencil" aria-hidden="true"></i>
                    </button>
                    <button type="button" class="bouton" @click.prevent="showExplnum(explnum.explnum_id)">
                        <i class="fa fa-eye" aria-hidden="true"></i>
                    </button>
                    <button type="button" class="bouton" @click.prevent="deleteExplnum(explnum.explnum_id)">
                        <i class="fa fa-times" aria-hidden="true"></i>
                    </button>
                </div>
                <img class="explnum-vign" :ref="'vign-' + explnum.explnum_id"
                    :src="$root.vign_url + '?explnum_id=' + explnum.explnum_id">
                <div class="explnum-name"><span>{{ explnum.explnum_nom }}</span></div>
                <div>
                    <input type="checkbox" v-model="selectedExplnums" :value="explnum.explnum_id" />
                </div>
            </div>
        </div>

        <div class="explnum-paginator">
            <paginator :total="paginator.total" :current-page="paginator.currentPage" :nbPerPage="paginator.nbPerPage"
                @switchPage="switchPage($event)" />
        </div>
        <div v-show="explnums.length">
            <hr>
            <div class='row explnum-collection-row'>
                <div class='colonne25'>
                    <label for='notice_link_label'>{{ messages.get("docnums", "notice_link") }}</label>
                </div>
                <div class='colonne75'>
                    <input type="text" class="saisie-30emr" id="notice_link_label" name="notice_link_label"
                        completion="notice" autfield="notice_link_id" autexclude="0" autocomplete="off"
                        callback="fillLinkedNotice" @keydown.enter="autocompleteIgnoreEnter($event)">
                    <input type="button" class="bouton" value="..."
                        onclick="openPopUp('./select.php?what=notice&amp;caller=collection_form&amp;param1=notice_link_id&amp;param2=notice_link_label&amp;callback=fillLinkedNotice&amp;no_display=0', 'selector_notice')">
                    <input type="hidden" id="notice_link_id" name="notice_link_id">
                    <input class='bouton' type='button' @click.prevent="clearNoticeSelector" value='X'>
                </div>
            </div>
            <div class='row explnum-collection-row'>
                <div class='colonne25'>
                    <label for='bulletin_link_label'>{{ messages.get("docnums", "bulletin_link") }}</label>
                </div>
                <div class='colonne75'>
                    <input type="text" class="saisie-30emr" id="bulletin_link_label" name="bulletin_link_label"
                        completion="bull" autfield="bulletin_link_id" autexclude="0" autocomplete="off"
                        callback="fillLinkedBulletin" @keydown.enter="autocompleteIgnoreEnter($event)">
                    <input type="button" class="bouton" value="..."
                        onclick="openPopUp('./select.php?what=bulletins&amp;caller=collection_form&amp;param1=bulletin_link_id&amp;param2=bulletin_link_label&amp;callback=fillLinkedBulletin&amp;no_display=0', 'selector_notice')">
                    <input type="hidden" id="bulletin_link_id" name="bulletin_link_id">
                    <input class='bouton' type='button' @click.prevent="clearBulletinSelector" value='X'>
                </div>
            </div>
            <div class="explnum-associate-buttons">
                <button type="button" class="bouton" @click.prevent="showAssociationModal"
                    :disabled="!canAssociate">{{ messages.get('docnums', 'associate') }}</button>
            </div>
        </div>
        <div class="explnum-associate-buttons">
            <button type="button" v-if="lastAssociatedBulletin || lastAssociatedNotice" class="bouton"
                @click.prevent="goToLastAssociated">{{ messages.get('docnums', 'last_associated_link') }}</button>
        </div>
        <div class='row explnum-collection-row'>
            <div>
                <label for='import_files'>{{ messages.get("docnums", "import_files") }}</label>
            </div>
            <div>
                <div class="drop-zone" @dragover.prevent="isDragging = true" @drop.prevent="handleDrop"
                    @dragleave.prevent="isDragging = false" :class="{ 'dragover': isDragging }">
                    <p v-if="files.length == 0">{{ messages.get("docnums", "drop_files") }}</p>
                    <ul>
                        <li v-for="(file, index) in files" :key="index">
                            {{ file.name }}
                        </li>
                    </ul>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
import Modal from '@/common/components/Modal.vue';
import paginator from "@/common/navbar/paginator.vue";

export default {
    name: 'explnumsForm',
    props: {
        explnums: {
            type: Array,
            required: true
        },
        numCollection: {
            type: Number,
            required: true
        },
        lenders: {
            type: Array,
            required: true
        },
        locations: {
            type: Array,
            required: true
        },
        licences: {
            type: Array,
            required: true
        }
    },
    components: {
        Modal,
        paginator
    },
    data: function () {
        return {
            selectedExplnums: [],
            linkedNotice: 0,
            linkedNoticeLabel: '',
            linkedBulletin: 0,
            linkedBulletinLabel: '',
            files: [],
            isDragging: false,
            explnumForm: "",
            currentExplnumEditedId: 0,
            modalTitle: "",
            modalStyle: {
                width: "75%"
            },
            paginator: {
                currentPage: 0,
                total: 0,
                nbPerPage: 0,
                result: [],
            },
            associationSettings: {
                indexDocnums: false,
                lenders: [],
                docsLocation: [],
                licenceProfiles: []
            },
            selectedLicences: [],
            profilesList: {},
            lastAssociatedNotice: "",
            lastAssociatedBulletin: ""
        }
    },
    mounted: async function () {
        window["fillLinkedNotice"] = this.fillLinkedNotice;
        window["fillLinkedBulletin"] = this.fillLinkedBulletin;
        window.addEventListener("load", function (event) {
            ajax_parse_elements();
        });
        //On déclare 2x le parse au cas ou on arrive ici après le load (ajout réactif du composant)
        if (typeof ajax_parse_elements == 'function') {
            ajax_parse_elements();
        }

        document.addEventListener('delete-explnum', this.deleteExplnum);

        window.test_form = function () { };
        window.confirm_delete = async function () {
            // dispatch event
            let event = new CustomEvent("delete-explnum");
            document.dispatchEvent(event);
        };

        await this.getExplnums();
        if (this.licences.length) {
            this.addSelectedLicence();
        }
    },
    watch: {
        numCollection: async function () {
            await this.getExplnums();
        }
    },
    computed: {
        canAssociate: function () {
            if (this.selectedExplnums.length == 0) {
                return false;
            }

            if (this.linkedNotice && this.linkedBulletin) {
                return false;
            }

            return this.linkedNotice || this.linkedBulletin;
        },
        canAddLicence: function () {
            if (this.associationSettings.licenceProfiles.length == this.selectedLicences.length) {
                return true;
            }
            return false;
        }
    },
    methods: {
        autocompleteIgnoreEnter(e) {
            e.preventDefault();
        },
        clearNoticeSelector: function () {
            this.linkedNotice = 0;
            this.linkedNoticeLabel = '';
            let input = document.getElementById("notice_link_label");
            input.value = '';
            input = document.getElementById("notice_link_id");
            input.value = '';
        },
        clearBulletinSelector: function () {
            this.linkedBulletin = 0;
            this.linkedBulletinLabel = '';
            let input = document.getElementById("bulletin_link_label");
            input.value = '';
            input = document.getElementById("bulletin_link_id");
            input.value = '';
        },
        fillLinkedNotice: function (e) {
            let input = document.getElementById("notice_link_label");
            this.linkedNoticeLabel = input.value;
            input = document.getElementById("notice_link_id");
            this.linkedNotice = input.value;
        },
        fillLinkedBulletin: function (e) {
            let input = document.getElementById("bulletin_link_label");
            this.linkedBulletinLabel = input.value;
            input = document.getElementById("bulletin_link_id");
            this.linkedBulletin = input.value;
        },
        handleDrop: async function (event) {
            const files = event.dataTransfer.files;
            const maxTransferSize = 20000000;
            let totalSize = 0;
            for (let i = 0; i < files.length; i++) {
                totalSize += files[i].size;
                this.files.push(files[i]);
                if (totalSize > maxTransferSize) {
                    this.sendFiles();
                    this.files = [];
                    totalSize = 0;
                }
            }
            if (this.files.length) {
                this.sendFiles();
                this.files = [];
            }
            this.isDragging = true;
        },
        sendFiles: async function () {
            let newExplnums = await this.ws.post("explnums", "import/" + this.numCollection, this.files, true);
            if (!newExplnums.error) {
                this.$emit("import-explnums", newExplnums);
            }
        },
        openExplnumForm: async function (explnumId) {
            if (explnumId == 0) {
                this.modalTitle = this.messages.get('docnums', 'add_docnum');
            } else {
                this.modalTitle = this.messages.get('docnums', 'edit_docnum');
            }
            this.currentExplnumEditedId = explnumId;
            this.showLoader();
            let request = await fetch(this.$root.url_webservice + "explnums/form/" + this.currentExplnumEditedId + "/" + this.numCollection);
            let form = await request.text();
            this.hiddenLoader();
            if (form) {
                this.explnumForm = form;
            }
            this.$refs.modal.show();

            setTimeout(() => {
                const cancelButton = document.getElementById("cancel_button");
                if (cancelButton) {
                    cancelButton.removeAttribute("onclick");
                    cancelButton.addEventListener("click", () => {
                        this.$refs.modal.close();
                        this.closeExplnumForm();
                    });
                }
            }, 300)
        },

        closeExplnumForm: function () {
            setTimeout(() => this.explnumForm = "", 500);
        },
        submitExplnumForm: async function (e) {
            const form = new FormData(e.target);
            this.showLoader();
            let response = await fetch(e.target.action, {
                method: 'POST',
                body: form
            });
            this.hiddenLoader();
            if (response.status == 200) {
                this.$refs.modal.close();
                if (this.currentExplnumEditedId) {
                    let editedExplnum = await this.ws.get("explnums", "explnum/" + this.currentExplnumEditedId);
                    this.$emit("edit-explnum", editedExplnum);
                    //On force le rechargement de la vignette
                    this.$refs["vign-" + this.currentExplnumEditedId][0].src = this.$refs["vign-" + this.currentExplnumEditedId][0].src + "&t=" + new Date().getTime();
                } else {
                    document.location = "./catalog.php?categ=docnum_collections&id=" + this.numCollection;
                }
            }
        },
        deleteExplnum: async function (id = 0) {
            if (!Number.isInteger(id) || id == 0) {
                id = this.currentExplnumEditedId;
            }

            if (id) {
                if (!confirm(this.messages.get('docnums', 'confirm_del_docnum'))) {
                    return;
                }

                this.showLoader();
                let response = await this.ws.get("explnums", "delete/" + id);
                if (!response.error) {
                    this.$refs.modal.close();
                    this.$emit("delete-explnum", id);
                }
                this.hiddenLoader();
            }
        },
        showExplnum: function (id) {
            window.open(this.$root.docnum_url + '?explnum_id=' + id, '_blank');
        },
        async switchPage(event) {
            await this.getExplnums(event.page);
        },
        async getExplnums(page = 1) {
            this.showLoader();

            let result = await this.ws.get("collections", `explnums/${this.numCollection}/${page}`);
            if (!result) {

            }

            this.paginator.currentPage = result.currentPage;
            this.paginator.total = result.total;
            this.paginator.nbPerPage = result.nbPerPage;

            this.$parent.collection.explnums = result.instances;

            this.hiddenLoader();
        },
        associate: async function () {
            if (this.linkedNotice && this.linkedBulletin) {
                this.notif.error(this.messages.get("docnums", "error_association"));
                return;
            }
            this.lastAssociatedNotice = "";
            this.lastAssociatedBulletin = "";

            if (this.linkedNotice) {
                let result = await this.ws.post("explnums", "associate/notice/" + this.linkedNotice, { "explnums": this.selectedExplnums, "settings": this.associationSettings });
                if (!result.error) {
                    this.lastAssociatedNotice = this.linkedNotice;
                    this.clearNoticeSelector();
                }
            }

            if (this.linkedBulletin) {
                let result = await this.ws.post("explnums", "associate/bulletin/" + this.linkedBulletin, { "explnums": this.selectedExplnums, "settings": this.associationSettings });
                if (!result.error) {
                    this.lastAssociatedBulletin = this.linkedBulletin;
                    this.clearBulletinSelector();
                }
            }

            this.$emit("explnums-associated", this.selectedExplnums);
            this.selectedExplnums = [];
            this.$refs.modalAssociation.close();
            this.notif.info(this.messages.get("docnums", "success_association"));
        },
        showAssociationModal: function () {
            this.$refs.modalAssociation.show();
        },
        getProfiles: async function (i) {
            if (!this.selectedLicences[i]) {
                return;
            }
            if (this.profilesList[this.selectedLicences[i].idLicence]) {
                this.selectedLicences[i].profiles = this.profilesList[this.selectedLicences[i].idLicence];
                return;
            }
            let profiles = await this.ws.get("explnums", "profiles/" + this.selectedLicences[i].idLicence);
            if (!profiles.error) {
                this.selectedLicences[i].profiles = profiles;
                this.profilesList[this.selectedLicences[i].idLicence] = profiles;
            }
        },
        addSelectedLicence: function () {
            this.$set(this.selectedLicences, this.selectedLicences.length, { idLicence: "", profiles: [] });
        },
        goToLastAssociated: function () {
            if (this.lastAssociatedNotice) {
                window.open(this.$root.url_base + 'catalog.php?categ=isbd&id=' + this.lastAssociatedNotice, '_blank');
            }
            if (this.lastAssociatedBulletin) {
                window.open(this.$root.url_base + 'catalog.php?categ=serials&sub=bulletinage&action=view&bul_id=' + this.lastAssociatedBulletin, '_blank');
            }
        }
    }
}
</script>

<style scoped>
.drop-zone {
    width: 100%;
    min-height: 200px;
    border: 2px dashed #ccc;
    border-radius: 10px;
    padding: 20px;
    text-align: center;
    transition: background-color 0.2s ease-in-out;
    align-content: center;
}

.drop-zone.dragover {
    background-color: #f0f0f0;
    border-color: #939393;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);
}

.explnum-name {
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}
</style>