<?php

/**
 * @id 14
 * @name 友联管理
 * @version 1.0.0
 * @description 提供网站友情链接管理功能，支持添加、编辑、删除以及前台调用，方便网站之间的资源共享
 * @price 0
 * @type 插件
 * @website 
 * @width 680
 * @height 600
 * @thumbnail /img/id14.png
 * @tpl
 */

// 插件配置参数
$plugin_config = <<<EOT
[config_params]
memos = [{"siteName":"QKCMS","siteUrl":"www.qkcms.com","timestamp":1779334237350},{"siteName":"启肯科技","siteUrl":"www.qiken.cn","timestamp":1778241927097},{"siteName":"启肯网络","siteUrl":"www.qiken.com","timestamp":1765852062545},{"siteName":"野狼音频网","siteUrl":"www.kx778.com","timestamp":1765850209072}]
[/config_params]
EOT;

// 定义插件标识
$plugin_identifier = '14_friendlink';
?>

<div class="memo-container">
    <!-- 输入区域 -->
    <div class="memo-input-wrap">
        <input type="text" id="site-name-input" placeholder="网站名称">
        <input type="text" id="site-url-input" placeholder="网站地址">
        <button class="memo-add-btn" onclick="memo.addMemo()">添加</button>
    </div>
    <!-- 备忘录列表 -->
    <div class="memo-list" id="memo-list"></div>
</div>

<style>
    /* 备忘录容器样式，隔离样式作用域 */
    .memo-container {
        margin: 0 auto;
        font-family: 'Arial', sans-serif;
        padding: 10px;
        box-sizing: border-box;
    }

    /* 输入区域 */
    .memo-input-wrap {
        display: flex;
        gap: 8px;
        margin-bottom: 15px;
        flex-wrap: wrap;
    }

    .memo-container #site-name-input,
    .memo-container #site-url-input {
        flex: 1;
        height: 42px;
        padding: 0 14px;
        border: 1px solid #e2e8f0;
        border-radius: 8px;
        font-size: 14px;
        color: #4a5568;
        outline: none;
        transition: all 0.3s ease;
        box-sizing: border-box;
        background-color: #ffffff;
        margin-right: 8px;
    }

    .memo-container #site-name-input:focus,
    .memo-container #site-url-input:focus {
        border-color: #3b82f6;
        box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
    }

    .memo-container #memo-input {
        flex: 1;
        height: 38px;
        padding: 0 10px;
        border: 1px solid #e5e7eb;
        border-radius: 6px;
        font-size: 14px;
        color: #333;
        outline: none;
        transition: border-color 0.2s;
        box-sizing: border-box;
    }

    .memo-container #memo-input:focus {
        border-color: #6366f1;
    }

    .memo-container .memo-add-btn {
        min-width: 70px;
        height: 42px;
        background-color: #3b82f6;
        color: #ffffff;
        border: none;
        border-radius: 8px;
        font-size: 14px;
        font-weight: 500;
        cursor: pointer;
        transition: all 0.3s ease;
        box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
    }

    .memo-container .memo-add-btn:hover {
        background-color: #2563eb;
        box-shadow: 0 2px 6px rgba(59, 130, 246, 0.25);
    }

    /* 备忘录列表 */
    .memo-container .memo-list {
        max-height: 430px;
        overflow-y: auto;
        gap: 8px;
        display: flex;
        flex-direction: column;
        padding-right: 8px;
        margin-top: 16px;
    }

    /* 自定义滚动条样式 */
    .memo-container .memo-list::-webkit-scrollbar {
        width: 8px;
    }

    .memo-container .memo-list::-webkit-scrollbar-track {
        background: #f1f1f1;
        border-radius: 4px;
    }

    .memo-container .memo-list::-webkit-scrollbar-thumb {
        background: #c1c1c1;
        border-radius: 4px;
    }

    .memo-container .memo-list::-webkit-scrollbar-thumb:hover {
        background: #a8a8a8;
    }

    /* 可编辑输入框样式 */
    .memo-container .memo-edit-input {
        width: 100%;
        padding: 8px 12px;
        border: 1px solid #e2e8f0;
        border-radius: 6px;
        font-size: 14px;
        color: #4a5568;
        outline: none;
        transition: all 0.3s ease;
        box-sizing: border-box;
        background-color: #ffffff;
        font-family: inherit;
    }

    .memo-container .memo-edit-input:focus {
        border-color: #3b82f6;
        box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
    }

    /* 四列表格布局 */
    .memo-container .memo-item {
        padding: 14px 18px;
        background-color: #ffffff;
        border-radius: 8px;
        display: grid;
        grid-template-columns: 40px 1fr 1fr 80px;
        gap: 16px;
        align-items: center;
        border: 1px solid #e2e8f0;
        font-size: 14px;
        transition: all 0.3s ease;
    }

    .memo-container .memo-item:hover {
        border-color: #cbd5e1;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
    }

    /* 列表头部样式 */
    .memo-container .memo-item.header {
        background-color: #f8fafc;
        font-weight: 600;
        color: #334155;
        border: none;
        border-bottom: 2px solid #e2e8f0;
        border-radius: 8px 8px 0 0;
        padding: 12px 18px;
    }

    /* ID列 */
    .memo-container .memo-id {
        text-align: center;
        color: #6b7280;
        font-weight: bold;
    }

    /* 内容列 */
    .memo-container .memo-content {
        color: #111827;
        word-break: break-all;
    }

    /* 时间列 */
    .memo-container .memo-time {
        color: #6b7280;
        text-align: left;
    }

    /* 操作列 */
    .memo-container .memo-actions {
        display: flex;
        gap: 6px;
        justify-content: center;
    }

    .memo-container .memo-del-btn {
        padding: 6px 12px;
        background-color: #ef4444;
        color: #ffffff;
        border: none;
        border-radius: 6px;
        font-size: 13px;
        cursor: pointer;
        transition: all 0.3s ease;
        font-weight: 500;
    }

    .memo-container .memo-del-btn:hover {
        background-color: #dc2626;
        box-shadow: 0 2px 4px rgba(239, 68, 68, 0.2);
    }

    /* 滚动条样式优化 */
    .memo-container .memo-list::-webkit-scrollbar {
        width: 8px;
    }

    .memo-container .memo-list::-webkit-scrollbar-track {
        background: #f1f1f1;
        border-radius: 4px;
    }

    .memo-container .memo-list::-webkit-scrollbar-thumb {
        background: #c1c1c1;
        border-radius: 4px;
    }

    .memo-container .memo-list::-webkit-scrollbar-thumb:hover {
        background: #a8a8a8;
    }
</style>

<script>
    // 立即执行函数，避免全局变量污染
    (function() {
        // 定义全局callParentConfirm函数，确保window.memo可以访问
        window.callParentConfirm = function(message) {
            const id = Math.random().toString(36).substring(2, 15);

            return new Promise((resolve) => {
                // 监听确认结果
                window.addEventListener('message', function listener(event) {
                    if (event.data.type === 'confirm_result' && event.data.id === id) {
                        resolve(event.data.result);
                        window.removeEventListener('message', listener);
                    }
                });

                // 发送确认请求
                window.parent.postMessage({
                    type: 'toast',
                    func: 'confirmDialog',
                    message: message,
                    id: id
                }, window.parent.location.origin);
            });
        }

        // 定义全局callParentToast函数，使用父页面的提示框
        window.callParentToast = function(message, options = {}) {
            window.parent.postMessage({
                type: 'toast',
                func: 'showToast',
                message: message,
                options: options
            }, window.parent.location.origin);
        }
        // 备忘录核心对象
        window.memo = {
            // 初始化：读取[config_params]中的数据并渲染列表
            init: function() {
                this.loadMemos();
            },

            // 使用AJAX从服务器加载备忘录数据
            loadMemos: function() {
                return new Promise((resolve, reject) => {
                    fetch('/admin/Plugin.php', {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/x-www-form-urlencoded',
                            },
                            body: 'action=load_plugin_settings&plugin=14_friendlink'
                        })
                        .then(response => response.json())
                        .then(data => {
                            let memos = [];
                            if (data.success && data.params) {
                                try {
                                    // 在params数组中查找memos参数
                                    const memoParam = data.params.find(p => p.name === 'memos');
                                    if (memoParam && memoParam.value) {
                                        memos = JSON.parse(memoParam.value);
                                        if (!Array.isArray(memos)) {
                                            memos = [];
                                        } else {
                                            // 为没有时间戳的备忘录添加默认时间戳（当前时间）
                                            const now = new Date().getTime();
                                            memos = memos.map(memo => {
                                                if (!memo.timestamp) {
                                                    return {
                                                        ...memo,
                                                        timestamp: now
                                                    };
                                                }
                                                return memo;
                                            });
                                        }
                                    }
                                } catch (e) {

                                    memos = [];
                                }
                            }
                            this.renderMemoList(memos);
                            resolve(memos);
                        })
                        .catch(error => {

                            this.renderMemoList([]);
                            resolve([]);
                        });
                });
            },

            // 将备忘录数据写入[config_params]
            saveMemosToConfig: function(memos) {
                // 限制最多保存50条数据
                if (memos.length > 50) {
                    memos = memos.slice(-50); // 只保留最后50条
                }

                // 发送AJAX请求保存配置
                fetch('/admin/Plugin.php', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/x-www-form-urlencoded',
                        },
                        body: 'action=save_plugin_settings&plugin=14_friendlink&settings=' + encodeURIComponent(JSON.stringify({
                            memos: memos
                        }))
                    })
                    .then(response => response.json())
                    .then(data => {
                        if (!data.success) {
                            // 使用父页面的提示框
                            callParentToast('保存失败：' + (data.message || '未知错误'), {
                                type: 'error'
                            });
                            return;
                        }

                        // 保存成功后重新加载数据，确保界面显示与服务器一致
                        this.loadMemos();

                        // 保存成功提示
                        callParentToast('保存成功', {
                            type: 'success'
                        });
                    })
                    .catch(error => {
                        // 使用父页面的提示框
                        callParentToast('保存失败：' + error.message, {
                            type: 'error'
                        });
                    });
            },

            // 格式化时间戳为指定格式 (YYYY-M-D)
            formatDate: function(timestamp) {
                const date = timestamp ? new Date(timestamp) : new Date();
                return `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`;
            },

            // 渲染备忘录列表
            renderMemoList: function(memos) {
                const listEl = document.getElementById('memo-list');
                if (!listEl) return;

                // 清空列表
                listEl.innerHTML = '';

                // 无数据提示
                if (memos.length === 0) {
                    listEl.innerHTML = '<div style="text-align:center; padding:20px; color:#9ca3af; font-size:14px;">暂无备忘录记录</div>';
                    return;
                }

                // 按时间倒序排序（最新的排在前面）
                memos.sort((a, b) => (b.timestamp || 0) - (a.timestamp || 0));

                // 渲染列表头部
                const headerEl = document.createElement('div');
                headerEl.className = 'memo-item header';
                headerEl.innerHTML = `
                <div class="memo-id">ID</div>
                <div class="memo-content">网站名称</div>
                <div class="memo-time">网站地址</div>
                <div class="memo-actions">操作</div>
            `;
                listEl.appendChild(headerEl);

                // 渲染每条备忘录
                memos.forEach((item, index) => {
                    const itemEl = document.createElement('div');
                    itemEl.className = 'memo-item';
                    itemEl.innerHTML = `
                    <div class="memo-id">${memos.length - index}</div>
                    <div class="memo-content">
                        <input type="text" value="${item.siteName || item.content || ''}" 
                               onblur="memo.saveMemoField(${index}, 'siteName', this.value)"
                               class="memo-edit-input">
                    </div>
                    <div class="memo-time">
                        <input type="text" value="${item.siteUrl || ''}" 
                               onblur="memo.saveMemoField(${index}, 'siteUrl', this.value)"
                               class="memo-edit-input">
                    </div>
                    <div class="memo-actions">
                        <button class="memo-del-btn" onclick="memo.deleteMemo(${index})")">删除</button>
                    </div>
                `;
                    listEl.appendChild(itemEl);
                });
            },

            // 添加备忘录
            addMemo: function() {
                const siteNameEl = document.getElementById('site-name-input');
                const siteUrlEl = document.getElementById('site-url-input');

                if (!siteNameEl || !siteUrlEl) return;

                const siteName = siteNameEl.value.trim();
                const siteUrl = siteUrlEl.value.trim();

                if (!siteName) {
                    // 使用父页面的提示框
                    callParentToast('请输入网站名称', {
                        type: 'error'
                    });
                    return;
                }

                if (!siteUrl) {
                    // 使用父页面的提示框
                    callParentToast('请输入网站地址', {
                        type: 'error'
                    });
                    return;
                }

                // 先加载现有数据，再添加新记录
                this.loadMemos().then(memos => {
                    // 添加新记录，包含当前时间戳
                    const newMemo = {
                        siteName: siteName,
                        siteUrl: siteUrl,
                        timestamp: new Date().getTime() // 保存时间戳
                    };
                    memos.push(newMemo);
                    // 保存并重新渲染
                    this.saveMemosToConfig(memos);
                    // 清空输入框
                    siteNameEl.value = '';
                    siteUrlEl.value = '';
                });
            },

            // 保存单个字段的修改
            saveMemoField: function(index, fieldName, value) {
                // 加载当前数据
                this.loadMemos().then(memos => {
                    if (!memos || memos.length === 0) return;

                    // 按时间倒序排序
                    memos.sort((a, b) => (b.timestamp || 0) - (a.timestamp || 0));

                    // 验证输入不能为空
                    if (value.trim() === '') {
                        callParentToast(fieldName === 'siteName' ? '网站名称不能为空' : '网站地址不能为空', {
                            type: 'error'
                        });
                        // 恢复原来的值
                        const itemEl = document.querySelector(`#memo-list .memo-item:nth-child(${index + 2}) .memo-edit-input`);
                        if (itemEl) {
                            itemEl.value = memos[index][fieldName] || '';
                        }
                        return;
                    }

                    // 检查值是否有变化
                    const oldValue = memos[index][fieldName] || '';
                    if (value.trim() === oldValue.trim()) {
                        // 值没有变化，不保存也不提示
                        return;
                    }

                    // 更新字段值
                    memos[index][fieldName] = value;

                    // 保存数据
                    this.saveMemosToConfig(memos);

                    // 提示保存成功
                    callParentToast('保存成功', {
                        type: 'success'
                    });
                }).catch(err => {

                    callParentToast('保存失败', {
                        type: 'error'
                    });
                });
            },

            // 删除备忘录
            deleteMemo: function(index) {
                // 直接执行删除操作，不显示确认框
                // 先加载现有数据
                this.loadMemos().then(memos => {
                    // 按时间倒序排序（与renderMemoList中的排序一致）
                    memos.sort((a, b) => (b.timestamp || 0) - (a.timestamp || 0));

                    // 现在索引是基于排序后的数组
                    if (index < 0 || index >= memos.length) return;

                    // 删除指定索引记录
                    memos.splice(index, 1);
                    // 保存并重新渲染
                    this.saveMemosToConfig(memos);
                });
            }

        };

        // 页面加载完成后初始化备忘录
        window.addEventListener('load', function() {
            memo.init();
        });
    })();
</script>
