/**
 * 工作日志本地总结插件
 * 收集当日私聊和@我的消息，生成本地HTML报告
 * 零上传、零AI依赖
 */
const fs = require('fs');
const path = require('path');

module.exports = {
    name: '工作日志本地总结',
    description: '本地收集消息生成工作日志HTML报告，不上传任何数据',
    version: '1.0.0-local',

    async init(config, pluginManager) {
        console.log('[WorkLogLocal] 初始化工作日志本地总结插件...');
        this._pm = pluginManager;
        this._cacheDir = path.join(__dirname, 'cache');
        if (!fs.existsSync(this._cacheDir)) fs.mkdirSync(this._cacheDir, { recursive: true });
        this._instance = { panel: null };
        this._injectStyles();
        this._injectNavIcon();
        this._cleanOldCache();
        return this._instance;
    },

    _injectStyles() {
        if (document.querySelector('#work-log-local-styles')) return;
        try {
            const cssPath = path.join(__dirname, 'styles.css');
            if (fs.existsSync(cssPath)) {
                const style = document.createElement('style');
                style.id = 'work-log-local-styles';
                style.textContent = fs.readFileSync(cssPath, 'utf-8');
                document.head.appendChild(style);
            }
        } catch (e) { console.error('[WorkLogLocal] 样式加载失败:', e); }
    },

    _injectNavIcon() {
        try {
            const self = this;
            const NAV_ID = 'wll-nav';

            const tryInject = () => {
                try {
                    var navTab = document.querySelector('body > div.rong-im > div > div.rong-nav > ul.rong-nav-tab');
                    if (!navTab) { setTimeout(tryInject, 2000); return; }
                    if (document.querySelector('#' + NAV_ID)) return;

                    // 注入 hover 切换 CSS（与 config-panel.js 1489-1492 一致）
                    if (!document.querySelector('#wll-nav-hover-css')) {
                        var s = document.createElement('style');
                        s.id = 'wll-nav-hover-css';
                        s.textContent =
                            '#' + NAV_ID + ' .rong-nav-icon.hover { display: none; }' +
                            '#' + NAV_ID + ' .rong-nav-icon:not(.hover) { display: block; }' +
                            '#' + NAV_ID + ':hover .rong-nav-icon.hover { display: block; }' +
                            '#' + NAV_ID + ':hover .rong-nav-icon:not(.hover) { display: none; }';
                        document.head.appendChild(s);
                    }

                    var defaultColor = (window.PluginTheme && window.PluginTheme.getNavIconColor()) || '#808CA4';
                    var hoverColor = '#3A6EE7';

                    // 文档/文件图标（带横线的文档）
                    var makeSvg = function(color) {
                        return '<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 512 512" fill="' + color + '">' +
                            '<path d="M288 48H160c-26.5 0-48 21.5-48 48v320c0 26.5 21.5 48 48 48h192c26.5 0 48-21.5 48-48V160L320 48zm96 416c0 8.8-7.2 16-16 16H160c-8.8 0-16-7.2-16-16V96c0-8.8 7.2-16 16-16h128v96c0 17.7 14.3 32 32 32h96v240z"/>' +
                            '<path d="M208 240h160v32H208v-32zm0 64h160v32H208v-32zm0 64h128v32H208v-32z"/>' +
                            '</svg>';
                    };

                    var navItem = document.createElement('li');
                    navItem.id = NAV_ID;
                    navItem.className = 'rong-nav-tab-item';
                    navItem.style.position = 'relative';
                    navItem.innerHTML =
                        '<em class="item-content" style="cursor: pointer;">' +
                            '<span class="rong-nav-icon" style="background-image: url(\'data:image/svg+xml;base64,' + btoa(makeSvg(defaultColor)) + '\');"></span>' +
                            '<span class="rong-nav-icon hover" style="background-image: url(\'data:image/svg+xml;base64,' + btoa(makeSvg(hoverColor)) + '\');"></span>' +
                            '<span class="rong-nav-text">日志</span>' +
                        '</em>';

                    navItem.addEventListener('click', () => {
                        self._togglePanel();
                    });

                    navTab.appendChild(navItem);
                    console.log('[WorkLogLocal] ✅ 导航图标已添加');
                } catch(e) { console.error('[WorkLogLocal] nav inject error:', e); }
            };
            setTimeout(tryInject, 3000);
        } catch(e) { console.error('[WorkLogLocal] _injectNavIcon error:', e); }
    },

    _togglePanel() {
        try {
        if (this._instance && this._instance.panel) {
            this._instance.panel.style.display = this._instance.panel.style.display === 'none' ? 'block' : 'none';
            return;
        }
        this._createPanel();
        } catch(e) { console.error('[WorkLogLocal] togglePanel error:', e); }
    },

    _createPanel() { try {
        const panel = document.createElement('div');
        panel.id = 'wll-panel';
        const today = new Date().toISOString().split('T')[0];
        panel.innerHTML = `
            <div class="wll-header">
                <div class="wll-header-title">📝 工作日志 <span style="font-size:12px;font-weight:400;color:#86868b;">本地版</span></div>
                <button class="wll-header-close" id="wll-close">✕</button>
            </div>
            <div class="wll-body">
                <p class="wll-desc">收集指定日期的私聊和@我的消息，本地生成HTML报告。<br>零上传 · 零AI依赖 · 数据不出本机</p>
                <div style="margin-bottom:12px;">
                    <label class="wll-desc" style="margin:0 0 6px;display:block;">选择日期</label>
                    <input id="wll-date" type="date" value="${today}" style="width:100%;height:38px;border:1.5px solid #d0d0d0;border-radius:8px;padding:0 12px;font-size:14px;box-sizing:border-box;">
                </div>
                <button id="wll-collect" class="wll-btn-primary">📥 收集消息</button>
                <button id="wll-generate" class="wll-btn-primary" style="display:none;margin-top:8px;">📄 生成报告</button>
                <div id="wll-status" class="wll-status"></div>
            </div>
        `;
        document.body.appendChild(panel);
        this._instance.panel = panel;

        panel.querySelector('#wll-close').addEventListener('click', () => panel.style.display = 'none');
        panel.querySelector('#wll-collect').addEventListener('click', () => this._collectAndGenerate());
        panel.querySelector('#wll-generate').addEventListener('click', () => this._generateReport());
    } catch(e) { console.error('[WorkLogLocal] createPanel error:', e); }
    },

    async _collectAndGenerate() {
        const statusEl = document.querySelector('#wll-status');
        statusEl.className = 'wll-status';
        statusEl.textContent = '正在收集消息...';

        const generateBtn = document.querySelector('#wll-generate');
        generateBtn.style.display = 'none';

        const RongIMLib = window.RongIMLib;
        if (!RongIMLib || !RongIMLib.RongIMClient) {
            statusEl.textContent = '❌ 融云 SDK 未就绪';
            return;
        }

        try {
            const RongIMClient = RongIMLib.RongIMClient;
            const myId = RongIMClient.getInstance().getCurrentUserId();
            const today = document.querySelector('#wll-date').value || new Date().toISOString().split('T')[0];

            // 获取会话列表
            const convList = await new Promise((resolve, reject) => {
                RongIMClient.getInstance().getConversationList(
                    { onSuccess: (list) => resolve(list || []), onError: reject },
                    [1, 3], 100
                );
            });

            const collected = [];
            for (const conv of convList) {
                try {
                    const msgs = await new Promise((resolve, reject) => {
                        RongIMClient.getInstance().getHistoryMessages(
                            conv.conversationType, conv.targetId, 0, 200,
                            { onSuccess: (list) => resolve(list || []), onError: reject }
                        );
                    });

                    const todayStart = new Date(today).getTime();
                    const todayEnd = todayStart + 86400000;

                    for (const msg of msgs) {
                        if (msg.sentTime < todayStart || msg.sentTime >= todayEnd) continue;
                        if (!msg.content) continue;

                        // 根据消息类型提取内容
                        const msgType = msg.objectName || '';
                        let textContent = '';
                        if (msgType === 'RC:TxtMsg' || msgType === 'RC:ReferenceMessage') {
                            textContent = msg.content.content || '';
                        } else if (msgType === 'RC:ImgMsg') {
                            textContent = '[图片]';
                        } else if (msgType === 'RC:FileMsg') {
                            textContent = '[文件] ' + (msg.content.name || '');
                        } else if (msgType === 'RC:VcMsg' || msgType === 'RC:HQVCMsg') {
                            textContent = '[语音消息]';
                        } else if (msgType === 'RC:SightMsg') {
                            textContent = '[短视频]';
                        } else if (msgType === 'RC:ImgTextMsg' || msgType === 'RC:PSImgTxtMsg') {
                            textContent = '[图文消息] ' + (msg.content.title || '');
                        } else if (msgType === 'RC:CombineMsg' || msgType === 'RC:CombineV2Msg') {
                            textContent = '[合并转发]';
                        } else if (msg.content.content && msg.content.content.length < 500 && !msg.content.content.startsWith('data:') && !msg.content.content.startsWith('/9j/')) {
                            textContent = msg.content.content;
                        } else {
                            continue; // 跳过无法识别的非文本消息
                        }
                        if (!textContent) continue;

                        const isMine = msg.senderUserId === myId;
                        const isAtMe = textContent.includes('@');

                        if (conv.conversationType === 1) {
                            collected.push({
                                time: msg.sentTime,
                                sender: msg.senderUserName || msg.senderUserId,
                                senderId: msg.senderUserId,
                                content: textContent,
                                type: '私聊',
                                target: conv.conversationTitle || conv.targetId,
                                isMine
                            });
                        } else if (conv.conversationType === 3) {
                            if (isMine || isAtMe) {
                                collected.push({
                                    time: msg.sentTime,
                                    sender: msg.senderUserName || msg.senderUserId,
                                    senderId: msg.senderUserId,
                                    content: textContent,
                                    type: '群聊',
                                    target: conv.conversationTitle || conv.targetId,
                                    isMine, isAtMe
                                });
                            }
                        }
                    }
                } catch (e) { /* skip failed conversations */ }
            }

            collected.sort((a, b) => a.time - b.time);

            // 解析用户ID为真实姓名
            statusEl.textContent = '正在解析用户信息...';
            const userIds = [...new Set(collected.map(m => m.senderId))];
            const userMap = await this._resolveUsers(userIds);
            for (const m of collected) {
                const info = userMap[m.senderId];
                if (info) m.sender = info.name || info.alias || m.senderId;
            }

            // 保存缓存
            const cacheFile = path.join(this._cacheDir, `work-log-${today}.json`);
            fs.writeFileSync(cacheFile, JSON.stringify({ date: today, messages: collected }, null, 2), 'utf-8');

            // 缓存到实例供后续生成报告使用
            this._instance.lastCollected = collected;
            this._instance.lastDate = today;

            // 统计概览
            const privateCount = collected.filter(m => m.type === '私聊').length;
            const groupCount = collected.filter(m => m.type === '群聊').length;
            const total = collected.length;

            statusEl.className = 'wll-status success';
            statusEl.textContent = `✅ 收集完成！共 ${total} 条消息（私聊 ${privateCount} 条，群聊 ${groupCount} 条）`;

            // 显示「生成报告」按钮
            generateBtn.style.display = 'block';
        } catch (e) {
            console.error('[WorkLogLocal] 收集失败:', e);
            statusEl.className = 'wll-status error';
            statusEl.textContent = '❌ 收集失败: ' + e.message;
        }
    },

    async _generateReport() {
        const statusEl = document.querySelector('#wll-status');
        const collected = this._instance.lastCollected;
        const today = this._instance.lastDate;

        if (!collected || !collected.length) {
            statusEl.className = 'wll-status error';
            statusEl.textContent = '⚠️ 请先收集消息';
            return;
        }

        try {
            statusEl.className = 'wll-status';
            statusEl.textContent = '正在生成报告...';

            // 生成 HTML 报告
            const html = this._buildHtml(collected, today);
            const reportDir = path.join(process.env.APPDATA || '', 'EpointMsgPluginsLocal', 'reports');
            if (!fs.existsSync(reportDir)) fs.mkdirSync(reportDir, { recursive: true });
            const reportFile = path.join(reportDir, `工作日志_${today}.html`);
            fs.writeFileSync(reportFile, html, 'utf-8');

            try {
                const { shell } = require('electron');
                shell.openPath(reportFile);
            } catch (e) {}

            statusEl.className = 'wll-status success';
            statusEl.textContent = `✅ 报告已生成并打开！${collected.length} 条消息`;
        } catch (e) {
            console.error('[WorkLogLocal] 生成报告失败:', e);
            statusEl.className = 'wll-status error';
            statusEl.textContent = '❌ 生成报告失败: ' + e.message;
        }
    },

    _buildHtml(messages, date) {
        const byTarget = {};
        messages.forEach(m => {
            const key = `[${m.type}] ${m.target}`;
            if (!byTarget[key]) byTarget[key] = [];
            byTarget[key].push(m);
        });

        let sections = '';
        for (const [target, msgs] of Object.entries(byTarget)) {
            const lines = msgs.map(m => {
                const time = new Date(m.time).toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' });
                const tag = m.isMine ? '📤' : (m.isAtMe ? '📢' : '📩');
                const bg = m.isMine ? '#e3f2fd' : (m.isAtMe ? '#fff8e1' : '#f8f8fa');
                return `<div style="display:flex;align-items:flex-start;padding:8px 12px;margin:3px 0;background:${bg};border-radius:8px;gap:8px;">
                    <span style="color:#86868b;font-size:12px;white-space:nowrap;min-width:44px;">${time}</span>
                    <span style="font-size:13px;">${tag}</span>
                    <span style="font-weight:500;font-size:13px;min-width:60px;">${m.sender}</span>
                    <span style="font-size:13px;color:#333;word-break:break-all;">${m.content}</span>
                </div>`;
            }).join('');
            const typeColor = target.includes('私聊') ? '#e8f5e9' : '#e3f2fd';
            const typeTextColor = target.includes('私聊') ? '#2e7d32' : '#1565c0';
            sections += `<div style="margin:20px 0;background:#fff;border-radius:14px;padding:16px;box-shadow:0 1px 4px rgba(0,0,0,0.06);">
                <h3 style="margin:0 0 10px;font-size:15px;color:#1d1d1f;display:flex;align-items:center;gap:8px;">
                    <span style="display:inline-block;padding:2px 8px;border-radius:4px;font-size:11px;font-weight:500;background:${typeColor};color:${typeTextColor};">${target.includes('私聊') ? '私聊' : '群聊'}</span>
                    ${target.replace(/^\[(私聊|群聊)\] /, '')}
                    <span style="font-size:12px;color:#86868b;font-weight:400;">${msgs.length} 条</span>
                </h3>
                ${lines}
            </div>`;
        }

        const mineCount = messages.filter(m => m.isMine).length;
        const atMeCount = messages.filter(m => m.isAtMe).length;
        const targetCount = Object.keys(byTarget).length;

        return `<!DOCTYPE html><html><head><meta charset="UTF-8"><title>工作日志 ${date}</title>
<style>
*{margin:0;padding:0;box-sizing:border-box;}
body{font-family:-apple-system,BlinkMacSystemFont,'Segoe UI','PingFang SC','Hiragino Sans GB',sans-serif;max-width:900px;margin:0 auto;padding:32px 24px;background:#f8f8fa;color:#1d1d1f;}
.header{margin-bottom:28px;padding-bottom:20px;border-bottom:1px solid #e5e5e7;}
.header h1{font-size:24px;font-weight:700;display:flex;align-items:center;gap:10px;}
.stats{display:flex;gap:12px;margin-top:12px;flex-wrap:wrap;}
.stat-card{background:#fff;padding:12px 18px;border-radius:10px;box-shadow:0 1px 3px rgba(0,0,0,0.06);min-width:120px;}
.stat-value{font-size:22px;font-weight:700;color:#1d1d1f;}
.stat-label{font-size:12px;color:#86868b;margin-top:2px;}
.footer{margin-top:24px;text-align:center;color:#86868b;font-size:12px;}
</style></head>
<body>
<div class="header">
    <h1>📝 工作日志 ${date}</h1>
    <div class="stats">
        <div class="stat-card"><div class="stat-value">${messages.length}</div><div class="stat-label">总消息数</div></div>
        <div class="stat-card"><div class="stat-value">${mineCount}</div><div class="stat-label">我发送的</div></div>
        <div class="stat-card"><div class="stat-value">${atMeCount}</div><div class="stat-label">@我的</div></div>
        <div class="stat-card"><div class="stat-value">${targetCount}</div><div class="stat-label">会话数</div></div>
    </div>
</div>
${sections || '<div style="background:#fff;padding:40px;border-radius:14px;text-align:center;color:#86868b;">今日无相关消息</div>'}
<div class="footer">由 EpointMsgPlugins 本地生成 · ${new Date().toLocaleString('zh-CN')} · 零上传</div>
</body></html>`;
    },

    /**
     * 批量解析用户ID为姓名
     */
    _resolveUsers(userIds) {
        return new Promise((resolve) => {
            const RongIM = window.RongIM;
            if (!RongIM || !RongIM.dataModel || !RongIM.dataModel.User) {
                resolve({});
                return;
            }
            const map = {};
            let done = 0;
            const total = userIds.length;
            if (total === 0) { resolve(map); return; }
            const timeout = setTimeout(() => resolve(map), 15000);
            userIds.forEach(uid => {
                try {
                    RongIM.dataModel.User.get(uid, (err, user) => {
                        done++;
                        if (!err && user) map[uid] = { name: user.name || '', alias: user.alias || '' };
                        if (done >= total) { clearTimeout(timeout); resolve(map); }
                    });
                } catch (e) {
                    done++;
                    if (done >= total) { clearTimeout(timeout); resolve(map); }
                }
            });
        });
    },

    _cleanOldCache() {
        try {
            const files = fs.readdirSync(this._cacheDir);
            const cutoff = Date.now() - 30 * 86400000;
            for (const f of files) {
                const fp = path.join(this._cacheDir, f);
                const stat = fs.statSync(fp);
                if (stat.mtimeMs < cutoff) fs.unlinkSync(fp);
            }
        } catch (e) {}
    },

    destroy() {
        if (this._instance.panel) this._instance.panel.remove();
        const nav = document.querySelector('#wll-nav');
        if (nav) nav.remove();
        console.log('[WorkLogLocal] 已销毁');
    }
};
