import {
    getImageList
} from '../../api/imageManagement/index';
import useUserStore from '@/store/modules/user';
(function() {
    tinymce.PluginManager.add('example', function (editor, url) {
        let total = 0;
        let userStoreNameId = useUserStore().userInfo.userId;
        let pageNum = 1;
        let imageList = [];
        function getImage() {
            getImageList({
                pageNum: pageNum,
                pageSize: 10,
                createUser: userStoreNameId,
                status: 'Y',
                oneself: 2,
            }).then(res => {
                total = res.total;
                imageList = res.rows;
            });
        }
        getImage();
        // const inductIP = sessionStorage.getItem('minioUrl');
        const inductIP = import.meta.env.VITE_APP_BASE_API;
        let openDialog = function () {
            const imageHtml = imageList.map((image, index) =>
                `<div style="position:relative; width: 150px; height:100px; margin: 10px; ">
                <img id="image-list-${index}" src="${inductIP + image.url}"
                alt="${image.name}" style="width: 100%; height:100%; cursor: pointer;"
                onmouseover="showTooltip(event)"
                onmouseout="hideTooltip(event)"
                onclick="handleImageClick(this)">
                <span class="tooltip"
                style="display:none; position:absolute; right: 0px; top:0px; color:#fff; background-color: rgba(0,0,0,0.6); padding: 5px 10px; font-size: 14px;"
                >${image.name}</span>
                </img>
                </div>`).join('');
            return editor.windowManager.open({
                title: '插入图片',
                body: {
                    type: 'panel',
                    items: [
                        {
                            type: 'htmlpanel',
                            html: `
                                <div style="padding: 10px; border-bottom: 1px solid #989898;">
                                    <input
                                    id="myInput"
                                    type="text"
                                    autocomplete="off"
                                    placeholder="请输入图片名称查询"
                                    style="width: 250px; line-height:30px;
                                    padding: 0 10px; border: 1px solid #767676;
                                    border-radius: 3px"
                                    />
                                    <input
                                    id="myDateInput"
                                    type="date"
                                    placeholder="请选择日期查询"
                                    style="width: 250px; height:32px; line-height:30px;
                                    padding: 0 10px; border: 1px solid #767676;
                                    border-radius: 3px"
                                    />
                                    <div style="float: right">
                                        <button type="button"
                                        style="font-size: 14px; background-color:#e3e3e3; border-radius: 6px; padding: 7px 16px; color: #000; cursor: pointer;"
                                        onclick="onClickReset()">重置</button>
                                        <button type="button"
                                        style="font-size: 14px; background-color:#006ce7; border-radius: 6px; padding: 7px 16px; margin-left:2px; color: #fff; cursor: pointer;"
                                        onclick="onClickInquire()">搜索</button>
                                    </div>
                                </div>
                                <div id="image-box" style="display: flex; flex-wrap: wrap;">${imageHtml}</div>
                                <div style="position: absolute; right: 16px; bottom: 8px">
                                    <button type="button"
                                    style="font-size: 14px; background-color:#006ce7; border-radius: 6px; padding: 8px 16px; margin-left: 8px; color: #fff; cursor: pointer;"
                                    onclick="onClickPrevious()">上一页</button>
                                    <button
                                    type="button"
                                    style="font-size: 14px; background-color:#006ce7; border-radius: 6px; padding: 8px 16px; margin-left: 8px; color: #fff; cursor: pointer;"
                                    onclick="onClickNext()">下一页</button>
                                </div>
                            `
                        },
                    ]
                },
                buttons: [
                    // {
                    //     type: 'cancel',
                    //     text: 'Close',
                    // },
                    {
                        type: 'submit',
                        text: 'Save',
                        primary: true
                    },
                ],
                onSubmit: function (api) {
                    // 将输入框内容插入到内容区光标位置
                    editor.insertContent(`<p style="width: 100%; text-align: center">
                    <img style="display: inline-block; width: 300px;" src="${insertUrl}" alt="Inserted Image" />
                    </p>`);
                    api.close();
                    pageNum = 1;
                    getImage();
                },
                onCancel: function() {
                    pageNum = 1;
                    getImage();
                }
            });
        };
        let insertUrl = '';
        let selectedElement = null;
        window.handleImageClick = function(imageElement) {
            insertUrl = imageElement.src;
            if (selectedElement === imageElement) {
                // 如果当前元素与已选中元素相同，则取消选中
                imageElement.style.border = '';
                selectedElement = null;
            } else {
                // 否则，清除之前选中的样式，并更新已选中元素
                if (selectedElement !== null) {
                    selectedElement.style.border = '';
                }
                imageElement.style.border = 'solid 3px #006ce7'; // 绿色背景表示选中
                selectedElement = imageElement;
            }
        };
        window.onClickPrevious = function() {
            const inquireName = document.getElementById('myInput').value;
            const inquireDate = document.getElementById('myDateInput').value;
            if (pageNum === 1) {
                return alert('已经第一页了！！！');
            } else {
                pageNum = pageNum - 1;
                getImageList({
                    pageNum: pageNum,
                    pageSize: 10,
                    createUser: userStoreNameId,
                    status: 'Y',
                    oneself: 2,
                    name: inquireName,
                    createTimeStr: inquireDate, // 创建时间
                }).then(res => {
                    total = res.total;
                    imageList = res.rows;
                    editor.windowManager.close();
                    openDialog();
                    const inputElement = document.getElementById('myInput');
                    inputElement.value = inquireName;
                    const inputDateElement = document.getElementById('myDateInput');
                    inputDateElement.value = inquireDate;
                });
            }
        };
        window.onClickNext = function() {
            const inquireName = document.getElementById('myInput').value;
            const inquireDate = document.getElementById('myDateInput').value;
            const totalFloor = Math.floor(total/10);
            if (pageNum > totalFloor) {
                return alert('已经到底了！！！');
            } else {
                pageNum = pageNum + 1;
                getImageList({
                    pageNum: pageNum,
                    pageSize: 10,
                    createUser: userStoreNameId,
                    status: 'Y',
                    oneself: 2,
                    name: inquireName,
                    createTimeStr: inquireDate, // 创建时间
                }).then(res => {
                    total = res.total;
                    imageList = res.rows;
                    editor.windowManager.close();
                    openDialog();
                    const inputElement = document.getElementById('myInput');
                    inputElement.value = inquireName;
                    const inputDateElement = document.getElementById('myDateInput');
                    inputDateElement.value = inquireDate;
                });
            }
        };
        window.onClickInquire = function() {
            const inquireName = document.getElementById('myInput').value;
            const inquireDate = document.getElementById('myDateInput').value;
            getImageList({
                pageNum: pageNum,
                pageSize: 10,
                createUser: userStoreNameId,
                status: 'Y',
                oneself: 2,
                name: inquireName,
                createTimeStr: inquireDate, // 创建时间
            }).then(res => {
                total = res.total;
                imageList = res.rows;
                editor.windowManager.close();
                openDialog();
                const inputElement = document.getElementById('myInput');
                inputElement.value = inquireName;
                const inputDateElement = document.getElementById('myDateInput');
                inputDateElement.value = inquireDate;
            });
        };
        window.onClickReset = function() {
            document.getElementById('myInput').value = '';
            document.getElementById('myDateInput').value = '';
            getImageList({
                pageNum: pageNum,
                pageSize: 10,
                createUser: userStoreNameId,
                status: 'Y',
                oneself: 2,
            }).then(res => {
                total = res.total;
                imageList = res.rows;
                editor.windowManager.close();
                openDialog();
            });
        };
        // 节流函数
        // function throttle(func, delay) {
        //     let timeoutId;
        //     return function (...args) {
        //         if (timeoutId) {
        //             clearTimeout(timeoutId);
        //         }
        //         timeoutId = setTimeout(() => {
        //             func.apply(this, args);
        //             timeoutId = null;
        //         }, delay);
        //     };
        // }
        // function onChangeInquireOriginal(e) {
        //     const acquireValue = e.target.value;
        //     getImageList({
        //         pageNum: pageNum,
        //         pageSize: 10,
        //         createUser: userStoreNameId,
        //         status: 'Y',
        //         oneself: 2,
        //         name: acquireValue,
        //         createTime: '', // 创建时间
        //     }).then(res => {
        //         total = res.total;
        //         imageList = res.rows;
        //         editor.windowManager.close();
        //         openDialog();
        //         const inputElement = document.getElementById('myInput');
        //         inputElement.value = e.target.value;
        //     });
        // };
        // window.onInputInquire = throttle(onChangeInquireOriginal, 2000);
        window.showTooltip = function(event) {
            const tooltip = event.target.nextElementSibling;
            if (tooltip && tooltip.classList.contains('tooltip')) {
                tooltip.style.display = 'block';
            }
        };
        window.hideTooltip = function(event) {
            const tooltips = document.getElementsByClassName('tooltip');
            for (let i = 0; i < tooltips.length; i++) {
                tooltips[i].style.display = 'none';
            }
        };
        // 注册一个工具栏按钮名称
        editor.ui.registry.addButton('example', {
            // text: '工具栏按钮名',
            icon: 'image',
            onAction: function () {
                openDialog();
            }
        });

        // 注册一个菜单项名称 menu/menubar
        editor.ui.registry.addMenuItem('example', {
            text: 'Example菜单名',
            onAction: function () {
                openDialog();
            }
        });

        // return {
        //     getMetadata: function () {
        //         return {
        //             //插件名和链接会显示在“帮助”→“插件”→“已安装的插件”中
        //             name: "Example plugin",//插件名称
        //             url: "http://exampleplugindocsurl.com", //作者网址
        //         };
        //     }
        // };
    });

})();
