
(function() {
    let converter;
    try {
        converter = window.markdownit({
          html: true,         // 允许 HTML
          linkify: true,      // 自动识别链接
          typographer: true,  // 优化标点符号
          highlight: function (str, lang) {
            if (lang && hljs.getLanguage(lang)) {
              try {
                return hljs.highlight(str, { language: lang }).value;
              } catch (__) {}
            }
            return '';
          }
        });
    }catch (e){
    }
    let messages = [
        {role:"system", content: `你是一个专业的 Markdown 编辑器助手，请用简洁中文回答。
        - 所有回复内容均严格遵循markdown格式
        你的回答请参考如下内容：
        `
                +document.body.innerText
        }
    ];
    // 先清理
    let chatBtn = document.getElementById('chat_btn');
    let chat_window = document.getElementById('chat_window');
    if(chatBtn){
        chatBtn.remove();
    }
    if(chat_window){
        chat_window.remove();
    }
    // 1. 创建右下角悬浮按钮
    chatBtn = document.createElement('button');
    chatBtn.id = "chat_btn"
    chatBtn.innerText = '💬';
    chatBtn.style.cssText = `
        position: fixed;
        bottom: 30px;
        right: 30px;
        width: 60px;
        height: 60px;
        border-radius: 50%;
        background: #007bff;
        color: white;
        font-size: 24px;
        border: none;
        cursor: pointer;
        box-shadow: 0 2px 10px rgba(0,0,0,0.2);
        z-index: 9999;
    `;
    document.body.appendChild(chatBtn);

    // 2. 创建聊天窗口容器
    const chatWindow = document.createElement('div');
    chatWindow.id="chat_window";
    chatWindow.style.cssText = `
        display: none;
        position: fixed;
        bottom: 100px;
        right: 30px;
        width: 340px;
        height: 480px;
        background: #fff;
        border-radius: 12px;
        box-shadow: 0 0 15px rgba(0,0,0,0.1);
        z-index: 9998;
        overflow: hidden;
        flex-direction: column;
    `;
    document.body.appendChild(chatWindow);

    // 3. 头部
    const header = document.createElement('div');
    header.id = "chat_header";
    header.innerHTML = '智能助手<label id="tips" style="margin-left: 30px"></label>';
    header.style.cssText = `
        padding: 15px;
        background: #007bff;
        color: white;
        font-weight: bold;
    `;
    chatWindow.appendChild(header);
    const tips = document.getElementById("tips");
    // 4. 消息区域
    const msgBox = document.createElement('div');
    msgBox.id=  "chat_msg";
    msgBox.style.cssText = `
        flex: 1;
        padding: 15px;
        overflow-y: auto;
        position: relative;
        background: #f5f5f5;
    `;
    chatWindow.appendChild(msgBox);

    // 5. 输入框区域
    const inputArea = document.createElement('div');
    inputArea.style.cssText = `
        display: flex;
        padding: 10px;
        border-top: 1px solid #eee;
    `;
    chatWindow.appendChild(inputArea);

    // 6. 输入框
    const input = document.createElement('input');
    input.placeholder = '输入消息...';
    input.style.cssText = `
        flex: 1;
        padding: 8px 12px;
        border: 1px solid #ddd;
        border-radius: 20px;
        outline: none;
    `;
    inputArea.appendChild(input);

    // 7. 发送按钮
    const sendBtn = document.createElement('button');
    sendBtn.innerText = '发送';
    sendBtn.style.cssText = `
        margin-left: 8px;
        padding: 8px 15px;
        background: #007bff;
        color: white;
        border: none;
        border-radius: 20px;
        cursor: pointer;
        font-size: 12px;
    `;

    inputArea.appendChild(sendBtn);
    const fxBtn = document.createElement('button');
    fxBtn.innerText = '写作';
    fxBtn.style.cssText = `
        margin-left: 8px;
        padding: 8px 15px;
        background: #007bff;
        color: white;
        border: none;
        border-radius: 20px;
        cursor: pointer;
        font-size: 12px;
    `;
    inputArea.appendChild(fxBtn);

    // 8. 显示/隐藏窗口
    chatBtn.onclick = () => {
        chatWindow.style.display = chatWindow.style.display === 'flex' ? 'none' : 'flex';
    };

    // 9. 发送消息
    function send(text) {
        if(!text){
            text = input.value.trim();
        }
        if (!text) return;

        const msg = document.createElement('div');
        msg.style.cssText = `
            margin: 0 0 10px auto;
            max-width: 70%;
            text-align: right;
        `;
        const msg_label = document.createElement('div');

        msg_label.innerText = text;
        msg_label.style.cssText = `
            
            display: inline-block;
            padding: 8px 12px;
            background: #007bff;
            color: white;
            border-radius: 15px;
        `;
        msg.appendChild(msg_label);
        msgBox.appendChild(msg);
        chat(text);
        input.value = '';
        msgBox.scrollTop = msgBox.scrollHeight;
        // txt2img("暗黑美女").then((img_url)=>{
            window.syncPost({
              title: '文章标题',
              content: '<p>正文 HTML</p>',
              thumb: img_url
            })
        // })

    }
    const accept =()=>{
        const msg = document.createElement('div');
        msg.style.cssText = `
            margin: 0 auto 10px 0;
            max-width: 70%;
            text-align: left;
        `;
        const msg_label = document.createElement('div');

        msg_label.style.cssText = `
            
            display: inline-block;
            padding: 8px 12px;
            background: #007bff;
            color: white;
            border-radius: 15px;
        `;
        msg.appendChild(msg_label);
        msgBox.appendChild(msg);
        return msg_label
    }
      function mdToWechat(md) {
        return md
            .replace(/</g, '&lt;')
            .replace(/>/g, '&gt;')
            .replace(/^# (.+)$/gm, '<p style="text-align:center; font-size:18px; font-weight:bold; margin:20px 0;">$1</p>')
            .replace(/^## (.+)$/gm, '<p style="font-size:17px; font-weight:bold; margin:18px 0;">$1</p>')
            .replace(/^### (.+)$/gm, '<p style="font-size:16px; font-weight:bold; margin:15px 0;">$1</p>')
            .replace(/\*\*(.+?)\*\*/g, '<strong>$1</strong>')
            .replace(/\*(.+?)\*/g, '<em>$1</em>')
            .replace(/^> (.+)$/gm, '<p style="border-left:3px solid #cccccc; padding-left:10px; color:#666666; margin:14px 0;">$1</p>')
            .replace(/^- (.+)$/gm, '<p style="margin:8px 0;">• $1</p>')
            .replace(/`(.+?)`/g, '<span style="background:#f4f4f4; padding:2px 4px; border-radius:3px;">$1</span>')
            .replace(/```([\s\S]*?)```/g, '<p style="background:#f9f9f9; padding:10px; border-radius:6px; white-space:pre-wrap; font-family:monospace; margin:14px 0;">$1</p>')
            .replace(/\n\n/g, '<p><br></p>')
            .replace(/\n/g, '');
    }
    const show_art_editor =()=>{
        let chat_header = document.getElementById("chat_header");
        let chat_msg = document.getElementById("chat_msg");
        let art_img = document.getElementById("art_img");
        let art_t = document.getElementById("art_img");
        let chat_window = document.getElementById("chat_window");
        chat_window.style.height = "55px";
        let art_content = document.getElementById("art_content");
        let art_account = document.getElementById("art_account");
        chat_header.style.display = "none";
        chat_msg.style.display = "none";

        let art_editor = document.getElementById("art_editor");
        if(art_editor){
            return {art_img: art_img, art_content: art_content, art_t: art_t, art_account: art_account};
        }
        art_editor = document.createElement('div');
        art_editor.id = "art_editor";
        art_editor.className = "markdown-body";
        art_editor.style.cssText = `
            width: 600px;
            height: 90%;
            text-align: left;
            background-color: #FFFFFF;
            box-shadow: 0 0 10px #000000;
            border-radius: 5px;
            position: fixed;
            left: 50%;
            top: 15px;
            z-index: 999;
            margin-left: -300px
        `;
        const art_tit = document.createElement('div');
        art_tit.style.cssText = `
            border-bottom: 1px solid #333333;
            padding: 5px;
            box-sizing: border-box;
        `
        art_img = document.createElement('img');
        art_img.id = "art_img";
        art_img.style.cssText = `
            display: inline-block;
            vertical-align: top;
            background: #000000;
            border-radius: 5px;
            height: 90px;
        `;
        art_tit.appendChild(art_img);
        art_t = document.createElement('div');
        art_t.id = "art_tit";
        art_t.style.cssText = `
            display: inline-block;
            vertical-align: top;
            font-weight: bold;
            padding: 30px 12px;
            color: #000000;
            border-radius: 15px;
        `;
        art_tit.appendChild(art_t);

        art_content = document.createElement("div");

        art_content.id = "art_content";
        art_content.style.cssText = `
            padding: 8px 12px;
            background: #FFFFFF;
            color: #000000;
            width: 100%;
            position: absolute;
            top: 105px;
            left: 0;
            bottom: 0;
            box-sizing: border-box;
            overflow-y: auto;
            overflow-x: hidden;
        `;

        art_editor.appendChild(art_tit);
        art_editor.appendChild(art_content);
        art_account = document.createElement("art_account");
        art_account.style.cssText = `
            position: absolute;
            right: -35px;
            width: 25px;
            top: 0px;
        `
        art_editor.appendChild(art_account);
        document.body.appendChild(art_editor);
        return {art_img: art_img, art_content: art_content, art_t: art_t, art_account: art_account};
    }
    const fx_article =async ()=>{
        const art_els = show_art_editor();
        const art_img = art_els.art_img;
        const art_content = art_els.art_content;
        const art_t = art_els.art_t;
        const art_account = art_els.art_account;
        let tit = "";
        const msg_box = await chat(
            `根据上述内容写一篇美观的文章
            - 内容不可编造
            - 不设置任何跳转链接
            - 关键链接用直接明文显示
            - 文章描述完全模拟人工，适当俏皮，适当故意增加少量错别字
            - 输出完整文章内容，不要包含任何AI成分，比如:"本文完全根据已提供的内容撰写，无任何虚构或编造的成分。"
            `
        ,(content, result)=>{
                if(!tit && result.indexOf("\n") > -1){
                    tit = result.split("\n")[0].replaceAll("#", "");
                    art_t.innerText = tit;
                }
                art_content.innerHTML = content;
                art_content.scrollTop = art_content.scrollHeight;
            });

        const article = art_content.innerHTML;
        // const tit = article.split("\n")[0].replaceAll("#", "").split(">")[1].split("</")[0];
        // const article_html = mdToWechat(article);

        txt2img(tit).then((img_url)=> {
            art_img.src = img_url;
            loadAccounts((allAccounts) => {
                let accounts_el = "";
                let art_accounts = [];
                for(var i=0;i<allAccounts.length;i++){
                    if(allAccounts[i].uid === "本地下载"){
                        continue
                    }
                    accounts_el += "<img style='width: 100%;margin-bottom: 10px' src='"+allAccounts[i].icon+"'>";
                    art_accounts.push(allAccounts[i]);
                }
                art_account.innerHTML = accounts_el;
                // const params = (title, content, markdown, thumb, desc) => {
                //
                //     return {title: title, content: content, markdown: markdown, thumb: thumb, desc: desc}
                // }
                const params = function (t) {
                    var e = {};
                    return e.title = t.title, t.content ? e.content = t.content : t.markdown && (e.markdown = t.content), t.thumb && (e.thumb = t.thumb), e.desc = t.desc ? t.desc : t.content.substring(0, 20), e
                }
                console.log("--- addTask2");
                window.$syncer.addTask({
                    post: params({title: tit, content: article, markdown: article, thumb: img_url, desc: content.substring(0, 120)}),
                    accounts: art_accounts
                }, (function (e) {
                    taskStatus = e;
                    console.log("--- taskStatus:", taskStatus)
                }), (function () {

                }))
                // addTask(params(tit, article, article, img_url, content.substring(0, 120)), art_accounts);
            });
        });

    }
    const send_msg =()=>{
        let chat_header = document.getElementById("chat_header");
        let chat_msg = document.getElementById("chat_msg");
        chat_header.style.display = "block";
        chat_msg.style.display = "block";
        chat_window.style.height = "480px";
        send();
    }
    sendBtn.onclick = send_msg;
    fxBtn.onclick = fx_article;
    input.onkeydown = (e) => e.key === 'Enter' && send();
    let allAccounts = [];
    const loadAccounts =(callback)=>{
        window.$syncer.getAccounts((function (t) {
                        allAccounts = t;
            callback(allAccounts);
                    }));
    }
    let taskStatus = -1;




    const addTask =(params, allAccounts)=>{
        console.log("---- addTask")
        window.$syncer.addTask({
            post: params,
            accounts: allAccounts
        }, (function (e) {
            taskStatus = e;
            console.log("--- taskStatus:", taskStatus)
        }), (function () {
        }))
    }

    const txt2img =async (prompt, w, h) => {
        if(!w){
            w = 1792;
            h = 1024;
        }
        tips.innerText = "生成封面图。。";
        const url = "https://proxy-ai.doocs.org/v1/images/generations";
        try {
            const res = await fetch(url, {
                method: "POST",
                headers: {"Content-Type": "application/json"},
                body: JSON.stringify({
                    prompt: prompt,
                    n: 1,
                    size: w+"x"+h,
                    model: "Kwai-Kolors/Kolors"
                })
            });
            const data = await res.json();
            // 拼接图片地址
            const imgUrl = data.images[0].url;
            return imgUrl;
        } catch (err) {
        }
    }
    const chat = async (mg, callback)=>{
        const url = "https://proxy-ai.doocs.org/v1/chat/completions";
        const botMsg = accept();
        messages.push({role: "user", content: mg});
        const msg = {
            max_tokens: 10240,
            model: "Qwen/Qwen2.5-7B-Instruct",
            messages: messages,
            stream: true,
            temperature: 1
        }
        try {
            const res = await fetch(url, {
                method: "POST",
                headers: {"Content-Type": "application/json"},
                body: JSON.stringify(msg)
            });
            const reader = res.body.getReader();
            const decoder = new TextDecoder();
            let result = '';
            while (true) {
                const {done, value} = await reader.read();
                if (done) break;
                if (value.indexOf("[DONE]") > -1) break;
                const chunk = decoder.decode(value, {stream: true}).trim();
                try{
                    const lines = chunk.split('"content":"')
                    for(var i=0;i<lines.length;i++) {
                        if(lines[i].indexOf("reasoning_content") === -1){
                            continue
                        }
                        const msg = lines[i].split('","')[0]
                        if (msg) {
                            result += msg.replaceAll("\\n", "\n").replaceAll("\\", "");
                            const content = converter.render(result);
                            if(callback){
                                callback(content, result);
                            }else{
                                botMsg.innerHTML = content;
                                msgBox.scrollTop = msgBox.scrollHeight;
                            }

                        }
                    }
                }catch (e){
                    console.error(e)
                }


            }
            messages.push({role: "assistant", content: result});
        } catch (err) {
            console.error("生成失败：", err);
        }
        return botMsg
    }
})();