/**
 * 最近搜索联系人插件
 * 在搜索对话框 (.rong-dialog-searchdetail) 的「搜索历史」区块后面，
 * 展示最近搜索过的联系人列表（姓名 + 头像），
 * 点击后直接发起/跳转会话，无需再次搜索。
 *
 * 实现原理：
 *   1. MutationObserver 监听搜索对话框 (.rong-dialog-searchdetail) 出现
 *   2. 对话框出现后，将"最近搜索联系人"区块注入到 .search-record 后面
 *   3. 拦截搜索结果中的联系人点击，记录其 id/name/avatar
 *   4. 点击最近联系人 → 直接调用 RongIM 路由跳转到会话
 */

const fs = require('fs');
const path = require('path');

module.exports = {
    name: '最近联系人',
    description: '搜索框聚焦时展示最近搜索过的联系人，点击可快速发起会话',
    version: 'dev',
    author: 'zfeng',
    defaultEnabled: false,

    defaultConfig: {},

    // ---- 内部常量 ----
    STYLE_ID: 'recent-contacts-styles',
    SECTION_ID: 'recent-contacts-section',
    MAX_RECORDS: 40,

    // ---- 颜色池 ----
    _avatarColors: [
        '#4E8BF7', '#FF6B6B', '#51CF66', '#FFA94D',
        '#845EF7', '#20C997', '#339AF0', '#F06595',
        '#5C7CFA', '#FF922B', '#22B8CF', '#E64980',
    ],

    // ---- 数据文件路径 ----
    _getDataPath() {
        try {
            const cacheDir = path.join(__dirname, 'cache');
            if (!fs.existsSync(cacheDir)) {
                fs.mkdirSync(cacheDir, { recursive: true });
            }
            return path.join(cacheDir, 'recent-contacts.json');
        } catch (e) {
            return null;
        }
    },

    _loadContacts() {
        const dataPath = this._getDataPath();
        if (!dataPath) return [];
        try {
            if (fs.existsSync(dataPath)) {
                const data = fs.readFileSync(dataPath, 'utf-8');
                return JSON.parse(data);
            }
        } catch (e) {
            console.error('[最近搜索联系人] 加载数据失败:', e);
        }
        return [];
    },

    _saveContacts(contacts) {
        const dataPath = this._getDataPath();
        if (!dataPath) return;
        try {
            fs.writeFileSync(dataPath, JSON.stringify(contacts, null, 2), 'utf-8');
        } catch (e) {
            console.error('[最近搜索联系人] 保存数据失败:', e);
        }
    },

    _addContact(instance, contact) {
        if (!contact || !contact.id) return;
        // 去重
        instance.contacts = instance.contacts.filter(c => c.id !== contact.id);
        instance.contacts.unshift(contact);
        if (instance.contacts.length > this.MAX_RECORDS) {
            instance.contacts = instance.contacts.slice(0, this.MAX_RECORDS);
        }
        this._saveContacts(instance.contacts);
        // 如果当前搜索对话框已打开，刷新显示
        this._tryInjectSection(instance);
        console.log('[最近搜索联系人] ✅ 记录联系人:', contact.name);
    },

    _removeContact(instance, contactId) {
        instance.contacts = instance.contacts.filter(c => c.id !== contactId);
        this._saveContacts(instance.contacts);
        this._tryInjectSection(instance);
    },

    _clearAll(instance) {
        instance.contacts = [];
        this._saveContacts([]);
        this._tryInjectSection(instance);
    },

    // ---- 注入样式 ----
    _injectStyles() {
        if (document.getElementById(this.STYLE_ID)) return;
        try {
            const cssPath = path.join(__dirname, 'styles.css');
            const cssContent = fs.readFileSync(cssPath, 'utf-8');
            const style = document.createElement('style');
            style.id = this.STYLE_ID;
            style.textContent = cssContent;
            document.head.appendChild(style);
        } catch (e) {
            console.error('[最近搜索联系人] 加载样式文件失败:', e);
        }
    },

    _getAvatarColor(name) {
        let hash = 0;
        for (let i = 0; i < (name || '').length; i++) {
            hash = name.charCodeAt(i) + ((hash << 5) - hash);
        }
        return this._avatarColors[Math.abs(hash) % this._avatarColors.length];
    },

    _escapeHtml(text) {
        return (text || '')
            .replace(/&/g, '&amp;')
            .replace(/</g, '&lt;')
            .replace(/>/g, '&gt;')
            .replace(/"/g, '&quot;');
    },

    // ---- 尝试在搜索对话框中注入最近联系人区块 ----
    _tryInjectSection(instance) {
        // 查找已打开的搜索对话框
        const dialog = document.querySelector('.rong-dialog-searchdetail .rong-dialog-inner');
        if (!dialog) return;

        // 移除已有的区块（刷新）
        const existing = dialog.querySelector('#' + this.SECTION_ID);
        if (existing) existing.remove();

        const contacts = instance.contacts;
        if (contacts.length === 0) return;

        // 找到 .search-record，在其后面插入
        const searchRecord = dialog.querySelector('.search-record');
        const insertAfter = searchRecord || dialog.querySelector('.search-classify');

        if (!insertAfter) {
            // 找不到参考元素，直接 append
            dialog.appendChild(this._buildSection(instance));
        } else {
            insertAfter.parentNode.insertBefore(this._buildSection(instance), insertAfter.nextSibling);
        }
    },

    // ---- 构建最近联系人区块 DOM（网格块状布局） ----
    _buildSection(instance) {
        const self = this;
        const contacts = instance.contacts;
        const section = document.createElement('div');
        section.id = this.SECTION_ID;
        section.className = 'recent-contacts-section';

        const privates = contacts.filter(c => c.conversationType === 1).slice(0, 9);
        const groups = contacts.filter(c => c.conversationType === 3).slice(0, 9);

        const buildGroup = (title, list, retainFilter) => {
            if (list.length === 0) return;

            const groupWrap = document.createElement('div');
            groupWrap.className = 'recent-contacts-group';

            // 标题
            const header = document.createElement('div');
            header.className = 'recent-contacts-header';
            header.innerHTML = `
                <span class="recent-contacts-title">${title}</span>
                <span class="recent-contacts-clear">清空</span>
            `;

            header.querySelector('.recent-contacts-clear').addEventListener('click', (e) => {
                e.stopPropagation();
                instance.contacts = instance.contacts.filter(c => retainFilter(c));
                self._saveContacts(instance.contacts);
                self._tryInjectSection(instance);
            });

            groupWrap.appendChild(header);

            // 网格容器
            const grid = document.createElement('div');
            grid.className = 'recent-contacts-grid';

            list.forEach(contact => {
                const block = document.createElement('div');
                block.className = 'recent-contact-block';

                // 头像
                const hasAvatars = contact.avatars && contact.avatars.length > 1;
                const hasAvatar = contact.avatar && contact.avatar.trim();

                if (hasAvatars) {
                    const avatarDiv = document.createElement('div');
                    avatarDiv.className = 'recent-contact-avatar recent-contact-avatar-grid';
                    avatarDiv.dataset.count = contact.avatars.length;
                    contact.avatars.forEach(src => {
                        const img = document.createElement('img');
                        img.src = src;
                        img.onerror = function() {
                            img.style.display = 'none';
                        };
                        avatarDiv.appendChild(img);
                    });
                    block.appendChild(avatarDiv);
                } else if (hasAvatar) {
                    const avatarDiv = document.createElement('div');
                    avatarDiv.className = 'recent-contact-avatar';
                    const img = document.createElement('img');
                    img.src = contact.avatar;
                    img.onerror = function () {
                        const textAvatar = document.createElement('div');
                        textAvatar.className = 'recent-contact-avatar-text';
                        textAvatar.style.background = self._getAvatarColor(contact.name);
                        textAvatar.textContent = (contact.name || '?').charAt(0);
                        avatarDiv.replaceWith(textAvatar);
                    };
                    avatarDiv.appendChild(img);
                    block.appendChild(avatarDiv);
                } else {
                    const textAvatar = document.createElement('div');
                    textAvatar.className = 'recent-contact-avatar-text';
                    textAvatar.style.background = self._getAvatarColor(contact.name);
                    textAvatar.textContent = (contact.name || '?').charAt(0);
                    block.appendChild(textAvatar);
                }

                // 名称
                const nameSpan = document.createElement('span');
                nameSpan.className = 'recent-contact-name';
                nameSpan.textContent = contact.name || contact.id;
                block.appendChild(nameSpan);

                // 删除按钮（右上角）
                const removeBtn = document.createElement('span');
                removeBtn.className = 'recent-contact-remove';
                removeBtn.title = '移除';
                removeBtn.textContent = '✕';
                removeBtn.addEventListener('click', (e) => {
                    e.stopPropagation();
                    self._removeContact(instance, contact.id);
                });
                block.appendChild(removeBtn);

                // 点击 → 打开会话
                block.addEventListener('click', (e) => {
                    if (e.target.closest('.recent-contact-remove')) return;
                    e.stopPropagation();
                    self._openConversation(instance, contact.conversationType || 1, contact.id);
                });

                grid.appendChild(block);
            });

            groupWrap.appendChild(grid);
            section.appendChild(groupWrap);
        };

        buildGroup('最近搜索私聊', privates, c => c.conversationType !== 1);
        buildGroup('最近搜索群聊', groups, c => c.conversationType !== 3);

        return section;
    },

    // ---- 打开会话 ----
    _openConversation(instance, conversationType, targetId) {
        try {
            const RongIM = window.RongIM;
            if (!RongIM) {
                console.warn('[最近搜索联系人] RongIM 不可用');
                return;
            }

            const im = RongIM.instance;
            if (!im) {
                console.warn('[最近搜索联系人] RongIM.instance 不可用');
                return;
            }

            const dataModel = im.dataModel || RongIM.dataModel;
            if (!dataModel) {
                console.warn('[最近搜索联系人] dataModel 不可用');
                return;
            }

            const conversationApi = dataModel.Conversation;
            const params = { conversationType, targetId };

            // 清除未读
            if (conversationApi) {
                conversationApi.getOne(conversationType, targetId, (errorCode, conversation) => {
                    if (!errorCode && conversation && conversation.unreadMessageCount > 0) {
                        conversationApi.clearUnReadCount(conversationType, targetId);
                        im.$emit('conversationchange', conversation);
                    }
                });
                conversationApi.add(params, () => {});
            }

            // 路由跳转
            if (im.$router) {
                im.$router.push({
                    name: 'conversation',
                    params: params,
                });
                im.$emit('messageinputfocus');
            }

            // 关闭搜索对话框 —— 点击关闭按钮
            const closeBtn = document.querySelector('.rong-dialog-searchdetail .rong-dialog-close');
            if (closeBtn) {
                closeBtn.click();
            }

            console.log(`[最近搜索联系人] 🚀 打开会话: type=${conversationType}, id=${targetId}`);
        } catch (e) {
            console.error('[最近搜索联系人] 打开会话失败:', e);
        }
    },

    // ---- 监听搜索对话框出现，自动注入区块 ----
    _setupDialogObserver(instance) {
        const self = this;

        const observer = new MutationObserver((mutations) => {
            for (const mutation of mutations) {
                for (const node of mutation.addedNodes) {
                    if (node.nodeType !== 1) continue;
                    // 检查是否是搜索对话框
                    const isSearchDialog = node.classList?.contains('rong-dialog-searchdetail')
                        || node.querySelector?.('.rong-dialog-searchdetail');
                    if (isSearchDialog) {
                        // 短暂延迟，等 Vue 渲染完 search-record
                        setTimeout(() => {
                            self._tryInjectSection(instance);
                            self._watchSearchInput(instance);
                        }, 100);
                    }
                }
            }
        });

        observer.observe(document.body, { childList: true, subtree: true });
        instance._dialogObserver = observer;

        console.log('[最近搜索联系人] 👁 搜索对话框监听已启动');
    },

    // ---- 监听搜索对话框内的输入框，输入时隐藏/清空时显示 ----
    _watchSearchInput(instance) {
        const self = this;
        const dialog = document.querySelector('.rong-dialog-searchdetail');
        if (!dialog) return;

        const searchInput = dialog.querySelector('.rong-search-main .rong-field-search');
        if (!searchInput) return;

        const onInput = () => {
            const section = document.getElementById(self.SECTION_ID);
            if (!section) return;
            if (searchInput.value && searchInput.value.trim() !== '') {
                section.style.display = 'none';
            } else {
                section.style.display = '';
            }
        };

        searchInput.addEventListener('input', onInput);
        // 初始检查
        onInput();
    },

    // ---- 监听搜索结果中的联系人点击，记录数据 ----
    _setupSearchClickCapture(instance) {
        const self = this;

        const clickHandler = (e) => {
            // 必须在搜索对话框内
            const dialog = e.target.closest('.rong-dialog-searchdetail');
            if (!dialog) return;

            // 检查是否点击了搜索结果中的条目
            const resultItem = e.target.closest('.rong-result-item');
            if (!resultItem) return;

            // 提取联系人信息
            try {
                const nameEl = resultItem.querySelector('.rong-search-name span')
                    || resultItem.querySelector('.rong-profile-name');
                const name = nameEl ? (nameEl.textContent || '').replace(/<[^>]+>/g, '').trim() : '';

                // 头像
                let avatar = '';
                let avatars = [];
                const avatarEl = resultItem.querySelector('.rong-result-item-aside');
                if (avatarEl) {
                    const urlSet = new Set();

                    // 1. 尝试获取所有 img 标签
                    const imgTags = avatarEl.querySelectorAll('img');
                    imgTags.forEach(img => {
                        if (img.src) urlSet.add(img.src);
                    });

                    // 2. 尝试获取所有 background-image
                    const bgEls = avatarEl.querySelectorAll('[style*="background-image"]');
                    bgEls.forEach(el => {
                        const match = el.style.backgroundImage.match(/url\(['"]*(.+?)['"]*\)/);
                        if (match && match[1]) {
                            // 移除可能的转义符号或引号
                            let url = match[1].replace(/\\/g, '').replace(/^["']|["']$/g, '');
                            urlSet.add(url);
                        }
                    });

                    const urlArray = Array.from(urlSet);

                    if (urlArray.length === 1) {
                        avatar = urlArray[0];
                    } else if (urlArray.length > 1) {
                        avatars = urlArray.slice(0, 9);
                    }
                }

                if (!name) return;

                // 延迟获取 targetId（点击后路由会跳转）
                setTimeout(() => {
                    const RongIM = window.RongIM;
                    const im = RongIM && RongIM.instance;
                    if (im && im.$route && im.$route.params && im.$route.params.targetId) {
                        const contactId = im.$route.params.targetId;
                        const conversationType = parseInt(im.$route.params.conversationType, 10) || 1;

                        self._addContact(instance, {
                            id: contactId,
                            name: name,
                            avatar: avatar,
                            avatars: avatars,
                            conversationType: conversationType,
                            lastSearchTime: new Date().toISOString(),
                        });
                    }
                }, 500);
            } catch (e) {
                console.warn('[最近搜索联系人] 提取联系人信息失败:', e);
            }
        };

        document.addEventListener('click', clickHandler, true);
        instance._clickHandler = clickHandler;

        console.log('[最近搜索联系人] 🔍 搜索结果点击监听已启动');
    },

    // ========== 生命周期 ==========

    async init(config, pluginManager) {
        console.log('[最近搜索联系人] 🚀 初始化...');

        const instance = {
            contacts: [],
            _dialogObserver: null,
            _clickHandler: null,
        };

        instance.contacts = this._loadContacts();

        this._injectStyles();
        this._setupDialogObserver(instance);
        this._setupSearchClickCapture(instance);

        console.log(`[最近搜索联系人] ✅ 插件已启动，已有 ${instance.contacts.length} 条记录`);
        return instance;
    },

    async destroy(instance) {
        console.log('[最近搜索联系人] 🔄 销毁...');

        if (instance._dialogObserver) {
            instance._dialogObserver.disconnect();
            instance._dialogObserver = null;
        }
        if (instance._clickHandler) {
            document.removeEventListener('click', instance._clickHandler, true);
            instance._clickHandler = null;
        }

        // 移除已注入的区块
        const section = document.getElementById(this.SECTION_ID);
        if (section) section.remove();

        // 移除样式
        const style = document.getElementById(this.STYLE_ID);
        if (style) style.remove();

        console.log('[最近搜索联系人] ✅ 已销毁');
    },
};
