chat.html 33.8 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>小羚羊 AI 助手</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/markdown-it/13.0.1/markdown-it.min.js"></script>
<style>
:root {
    --bg: #f7f7f8;
    --panel: #ffffff;
    --border: #e5e5e7;
    --text: #1d1d1f;
    --text2: #6e6e73;
    --accent: #0a7d50;
    --accent-weak: #e6f4ee;
    --danger: #c0392b;
    --radius: 10px;
}
* { box-sizing: border-box; margin: 0; padding: 0; }
html, body { height: 100%; }
body {
    font: 14px/1.6 -apple-system, "PingFang SC", "Microsoft YaHei", sans-serif;
    color: var(--text);
    background: var(--bg);
    display: flex;
    overflow: hidden;
}

/* ---------- 侧栏 ---------- */
#sidebar {
    width: 250px;
    min-width: 250px;
    background: var(--panel);
    border-right: 1px solid var(--border);
    display: flex;
    flex-direction: column;
    transition: margin-left .2s ease;
}
#sidebar.hidden { margin-left: -250px; }
#sidebar .side-head {
    padding: 14px 14px 10px;
    display: flex;
    align-items: center;
    justify-content: space-between;
}
#sidebar .side-head .brand { font-size: 15px; font-weight: 600; }
#newConvBtn {
    border: 1px solid var(--border);
    background: var(--panel);
    border-radius: 8px;
    padding: 4px 10px;
    cursor: pointer;
    color: var(--accent);
}
#newConvBtn:hover { background: var(--accent-weak); }
#convList { flex: 1; overflow-y: auto; padding: 4px 8px 12px; }
.conv-item {
    padding: 8px 10px;
    border-radius: 8px;
    cursor: pointer;
    display: flex;
    align-items: center;
    gap: 6px;
    color: var(--text2);
}
.conv-item:hover { background: var(--bg); }
.conv-item.active { background: var(--accent-weak); color: var(--text); }
.conv-item .t { flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.conv-item .del { visibility: hidden; border: 0; background: none; cursor: pointer; color: var(--text2); }
.conv-item:hover .del { visibility: visible; }

/* ---------- 主区 ---------- */
#main { flex: 1; display: flex; flex-direction: column; min-width: 0; }
#topbar {
    height: 52px;
    background: var(--panel);
    border-bottom: 1px solid var(--border);
    display: flex;
    align-items: center;
    gap: 10px;
    padding: 0 16px;
}
#toggleSide {
    border: 1px solid var(--border);
    background: var(--panel);
    border-radius: 8px;
    width: 32px;
    height: 32px;
    cursor: pointer;
    color: var(--text2);
}
#topbar .title { font-weight: 600; }
#topbar .sub { color: var(--text2); font-size: 12px; }

#scroll { flex: 1; overflow-y: auto; }
#messages { max-width: 860px; margin: 0 auto; padding: 24px 20px 12px; }

.msg { display: flex; margin-bottom: 18px; }
.msg.user { justify-content: flex-end; }
.bubble {
    max-width: 82%;
    padding: 10px 14px;
    border-radius: var(--radius);
    word-break: break-word;
}
.msg.user .bubble { background: var(--accent); color: #fff; white-space: pre-wrap; }
.msg.ai .bubble { background: var(--panel); border: 1px solid var(--border); }
.msg.ai .bubble.thinking { color: var(--text2); }

/* markdown 内容 */
.bubble p { margin: 4px 0; }
.bubble h1, .bubble h2, .bubble h3 { margin: 8px 0 4px; font-size: 15px; }
.bubble ul, .bubble ol { padding-left: 20px; margin: 4px 0; }
.bubble code { background: var(--bg); padding: 1px 5px; border-radius: 4px; font-size: 13px; }
.bubble pre { background: var(--bg); padding: 10px; border-radius: 8px; overflow-x: auto; margin: 6px 0; }
.bubble table { border-collapse: collapse; margin: 8px 0; max-width: 100%; display: block; overflow-x: auto; }
.bubble th, .bubble td { border: 1px solid var(--border); padding: 5px 10px; white-space: nowrap; }
.bubble th { background: var(--bg); }

/* 卡片(提议 / 表单 / 追问)*/
.card {
    background: var(--panel);
    border: 1px solid var(--border);
    border-radius: var(--radius);
    padding: 14px 16px;
    margin: 0 0 18px;
    max-width: 82%;
}
.card .card-title { font-weight: 600; margin-bottom: 8px; }
.card .muted { color: var(--text2); font-size: 13px; }
.btn {
    border: 1px solid var(--border);
    background: var(--panel);
    border-radius: 8px;
    padding: 6px 16px;
    cursor: pointer;
    font-size: 14px;
}
.btn:hover { background: var(--bg); }
.btn.primary { background: var(--accent); border-color: var(--accent); color: #fff; }
.btn.primary:hover { filter: brightness(1.08); }
.btn:disabled { opacity: .5; cursor: default; }
.card .actions { display: flex; gap: 10px; margin-top: 10px; }
.card .result { margin-top: 10px; font-size: 13px; }
.card .result.ok { color: var(--accent); }
.card .result.bad { color: var(--danger); }

/* 追问选项片 */
.chips { display: flex; flex-wrap: wrap; gap: 8px; margin-top: 10px; }
.chip {
    border: 1px solid var(--border);
    background: var(--panel);
    border-radius: 16px;
    padding: 5px 14px;
    cursor: pointer;
}
.chip:hover { border-color: var(--accent); color: var(--accent); }
.chip-free { display: flex; gap: 6px; margin-top: 10px; }
.chip-free input {
    flex: 1;
    border: 1px solid var(--border);
    border-radius: 8px;
    padding: 6px 10px;
    font-size: 14px;
}

/* collectForm 表单 */
.form-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
    gap: 10px 16px;
    margin-top: 10px;
}
.ffield label { display: block; font-size: 12px; color: var(--text2); margin-bottom: 3px; }
.ffield label .req { color: var(--danger); margin-left: 2px; }
.ffield input, .ffield select {
    width: 100%;
    border: 1px solid var(--border);
    border-radius: 8px;
    padding: 7px 10px;
    font-size: 14px;
    background: var(--panel);
}
.ffield input:focus, .ffield select:focus { outline: none; border-color: var(--accent); }
.ffield .fkrow { display: flex; gap: 6px; }
.ffield .fkrow input { flex: 1; background: var(--bg); }
.ffield .hint { font-size: 12px; color: var(--text2); margin-top: 2px; }

/* previewChange 预览卡 */
.ffield.changed label { color: var(--accent); font-weight: 600; }
.ffield.changed input, .ffield.changed select { border-color: var(--accent); background: var(--accent-weak); }
.ffield .oldval { font-size: 12px; color: var(--text2); margin-top: 2px; text-decoration: line-through; }
.preview-ro { display: flex; gap: 8px; padding: 3px 0; font-size: 13px; }
.preview-ro .l { color: var(--text2); min-width: 90px; }
.status-change {
    margin-top: 10px;
    padding: 8px 12px;
    background: var(--accent-weak);
    border-radius: 8px;
    font-weight: 600;
}
.status-change .from { color: var(--text2); text-decoration: line-through; margin-right: 6px; }
.status-change .to { color: var(--accent); }

/* 输入区 */
#inputbar { background: var(--bg); padding: 8px 20px 16px; }
#inputbox {
    max-width: 860px;
    margin: 0 auto;
    background: var(--panel);
    border: 1px solid var(--border);
    border-radius: 14px;
    display: flex;
    align-items: flex-end;
    padding: 8px 10px;
    gap: 8px;
}
#inputbox:focus-within { border-color: var(--accent); }
#messageInput {
    flex: 1;
    border: 0;
    resize: none;
    font: inherit;
    max-height: 140px;
    outline: none;
    background: transparent;
}
#sendBtn {
    border: 0;
    background: var(--accent);
    color: #fff;
    border-radius: 10px;
    padding: 7px 18px;
    cursor: pointer;
    font-size: 14px;
}
#sendBtn:disabled { opacity: .5; cursor: default; }

/* FK 选择器弹层 */
#modalMask {
    position: fixed;
    inset: 0;
    background: rgba(0,0,0,.35);
    display: none;
    align-items: center;
    justify-content: center;
    z-index: 50;
}
#modalMask.show { display: flex; }
#fkModal {
    background: var(--panel);
    border-radius: 12px;
    width: min(720px, 92vw);
    max-height: 80vh;
    display: flex;
    flex-direction: column;
    box-shadow: 0 12px 40px rgba(0,0,0,.18);
}
#fkModal .m-head {
    padding: 14px 16px;
    border-bottom: 1px solid var(--border);
    display: flex;
    align-items: center;
    gap: 10px;
}
#fkModal .m-head .m-title { font-weight: 600; flex: 1; }
#fkSearch {
    border: 1px solid var(--border);
    border-radius: 8px;
    padding: 6px 10px;
    width: 220px;
    font-size: 14px;
}
#fkClose { border: 0; background: none; font-size: 18px; cursor: pointer; color: var(--text2); }
#fkBody { flex: 1; overflow: auto; padding: 0 16px; }
#fkBody table { width: 100%; border-collapse: collapse; }
#fkBody th, #fkBody td { text-align: left; padding: 8px 10px; border-bottom: 1px solid var(--border); white-space: nowrap; }
#fkBody th { position: sticky; top: 0; background: var(--panel); color: var(--text2); font-weight: 500; }
#fkBody tbody tr { cursor: pointer; }
#fkBody tbody tr:hover { background: var(--accent-weak); }
#fkModal .m-foot {
    padding: 10px 16px;
    border-top: 1px solid var(--border);
    display: flex;
    align-items: center;
    justify-content: flex-end;
    gap: 10px;
    color: var(--text2);
    font-size: 13px;
}
#fkModal .m-foot button { width: 28px; height: 28px; border-radius: 6px; border: 1px solid var(--border); background: var(--panel); cursor: pointer; }
#fkModal .m-foot button:disabled { opacity: .4; cursor: default; }

/* 提示条 */
#toast {
    position: fixed;
    top: 14px;
    left: 50%;
    transform: translateX(-50%);
    background: #333;
    color: #fff;
    padding: 8px 18px;
    border-radius: 8px;
    font-size: 13px;
    display: none;
    z-index: 99;
}
</style>
</head>
<body>

<aside id="sidebar">
    <div class="side-head">
        <span class="brand">小羚羊 AI</span>
        <button id="newConvBtn" title="新会话">+ 新会话</button>
    </div>
    <div id="convList"></div>
</aside>

<div id="main">
    <div id="topbar">
        <button id="toggleSide" title="收起/展开会话栏"></button>
        <span class="title">小羚羊印刷 ERP 智能助手</span>
        <span class="sub" id="convTitle"></span>
    </div>
    <div id="scroll">
        <div id="messages"></div>
    </div>
    <div id="inputbar">
        <div id="inputbox">
            <textarea id="messageInput" rows="1" placeholder="输入消息,如:查一下这个月的报价单 / 给必胜客报价5000个纸盒…"></textarea>
            <button id="sendBtn">发送</button>
        </div>
    </div>
</div>

<div id="modalMask">
    <div id="fkModal">
        <div class="m-head">
            <span class="m-title" id="fkTitle">选择</span>
            <input id="fkSearch" placeholder="输入名称搜索…">
            <button id="fkClose" title="关闭"></button>
        </div>
        <div id="fkBody"></div>
        <div class="m-foot">
            <span id="fkPageInfo"></span>
            <button id="fkPrev"></button>
            <button id="fkNext"></button>
        </div>
    </div>
</div>

<div id="toast"></div>

<script>
/* ================= 身份 =================
   前端只持有 ERP 会话 token,随每个请求以 Authorization 头发出;
   用户是谁、属于哪个租户、有什么权限,全部由后端拿 token 向 ERP 内省决定——
   前端不再自报 userid/brandsid/usertype(自报即可伪造)。
   生产由 ERP 外壳注入 token(window.__ERP_TOKEN__ 或 ?token=);本地留空 → 后端 dev-login(仅本地开启)。 */
const authorization = (window.__ERP_TOKEN__
    || new URLSearchParams(window.location.search).get("token") || "").trim();
const BASE = window.location.origin + "/xlyAi";

/** 统一请求头:带 token(有则带),JSON 内容类型按需。 */
function authHeaders(json) {
    const h = {};
    if (authorization) h["Authorization"] = authorization;
    if (json) h["Content-Type"] = "application/json";
    return h;
}

const md = window.markdownit({ html: false, linkify: true, breaks: true });

let conversationId = null;
let sending = false;

const $ = (sel) => document.querySelector(sel);
const messagesEl = $("#messages");
const scrollEl = $("#scroll");

function toast(msg) {
    const t = $("#toast");
    t.textContent = msg;
    t.style.display = "block";
    clearTimeout(t._h);
    t._h = setTimeout(() => { t.style.display = "none"; }, 2600);
}

function scrollBottom() {
    scrollEl.scrollTop = scrollEl.scrollHeight;
}

function el(tag, cls, text) {
    const e = document.createElement(tag);
    if (cls) e.className = cls;
    if (text !== undefined) e.textContent = text;
    return e;
}

/* ================= 消息渲染 ================= */
function addUserMsg(text) {
    const row = el("div", "msg user");
    row.appendChild(el("div", "bubble", text));
    messagesEl.appendChild(row);
    scrollBottom();
}

function addAiBubble() {
    const row = el("div", "msg ai");
    const b = el("div", "bubble thinking", "…");
    row.appendChild(b);
    messagesEl.appendChild(row);
    scrollBottom();
    return b;
}

function renderMd(bubble, text) {
    bubble.classList.remove("thinking");
    bubble.innerHTML = md.render(text || "");
}

function addAiMd(text) {
    const b = addAiBubble();
    renderMd(b, text);
    return b;
}

/* ================= 会话管理 ================= */
async function loadConvs() {
    try {
        const r = await fetch(BASE + "/api/agent/conversations", { headers: authHeaders(false) });
        const list = await r.json();
        const box = $("#convList");
        box.innerHTML = "";
        list.forEach(c => {
            const item = el("div", "conv-item" + (c.id === conversationId ? " active" : ""));
            const t = el("span", "t", c.title || "新会话");
            const del = el("button", "del", "✕");
            del.title = "删除会话";
            del.onclick = async (e) => {
                e.stopPropagation();
                await fetch(BASE + "/api/agent/conversations/" + encodeURIComponent(c.id),
                    { method: "DELETE", headers: authHeaders(false) });
                if (c.id === conversationId) newConv();
                loadConvs();
            };
            item.appendChild(t);
            item.appendChild(del);
            item.onclick = () => switchConv(c.id, c.title);
            box.appendChild(item);
        });
    } catch (e) { /* 静默:侧栏失败不影响聊天 */ }
}

async function newConv() {
    try {
        const r = await fetch(BASE + "/api/agent/conversations", {
            method: "POST",
            headers: authHeaders(true)
        });
        conversationId = (await r.json()).conversationId;
    } catch (e) {
        conversationId = "c-" + Date.now() + "-" + Math.random().toString(36).slice(2, 8);
    }
    $("#convTitle").textContent = "";
    messagesEl.innerHTML = "";
    addAiMd("你好,我是小羚羊 AI 助手。可以帮你查询业务数据、新建报价、修改/作废/审核单据。");
    loadConvs();
}

async function switchConv(id, title) {
    conversationId = id;
    $("#convTitle").textContent = title || "";
    messagesEl.innerHTML = "";
    try {
        const r = await fetch(BASE + "/api/agent/conversations/" + encodeURIComponent(id) + "/messages",
            { headers: authHeaders(false) });
        const hist = await r.json();
        hist.forEach(m => {
            if (m.role === "user") addUserMsg(m.content);
            else addAiMd(m.content);
        });
    } catch (e) { }
    loadConvs();
    scrollBottom();
}

/* ================= 发送 & SSE ================= */
async function sendMessage(text) {
    text = (text || "").trim();
    if (!text || sending) return;
    sending = true;
    $("#sendBtn").disabled = true;
    addUserMsg(text);
    const bubble = addAiBubble();
    let buf = "";
    try {
        const resp = await fetch(BASE + "/api/agent/chat", {
            method: "POST",
            headers: authHeaders(true),
            body: JSON.stringify({ text: text, conversationId: conversationId })
        });
        const reader = resp.body.getReader();
        const dec = new TextDecoder();
        let pending = "";
        for (;;) {
            const { done, value } = await reader.read();
            if (done) break;
            pending += dec.decode(value, { stream: true });
            let idx;
            while ((idx = pending.indexOf("\n\n")) >= 0) {
                const frame = pending.slice(0, idx);
                pending = pending.slice(idx + 2);
                const line = frame.split("\n").find(l => l.startsWith("data:"));
                if (!line) continue;
                let ev;
                try { ev = JSON.parse(line.slice(5)); } catch (e) { continue; }
                buf = handleEvent(ev, bubble, buf);
            }
        }
    } catch (e) {
        renderMd(bubble, "⚠️ 连接失败:" + e.message);
    }
    if (bubble.classList.contains("thinking")) {
        bubble.closest(".msg").remove(); // 本轮只有卡片/表单,无正文
    }
    sending = false;
    $("#sendBtn").disabled = false;
    loadConvs(); // 刷新标题
}

function handleEvent(ev, bubble, buf) {
    switch (ev.type) {
        case "token":
            buf += ev.content || "";
            renderMd(bubble, buf);
            scrollBottom();
            return buf;
        case "reset":
            renderMd(bubble, "");
            bubble.classList.add("thinking");
            bubble.textContent = "…";
            return "";
        case "change_preview":
            addPreviewCard(ev);
            return buf;
        case "question":
            addQuestionCard(ev.question, ev.options || [], ev.allowFree !== false);
            return buf;
        case "form_collect":
            addFormCard(ev);
            return buf;
        case "error":
            renderMd(bubble, (buf ? buf + "\n\n" : "") + "⚠️ " + (ev.content || "服务异常"));
            return buf;
        case "done":
        default:
            return buf;
    }
}

/* ================= previewChange 预览卡 =================
   整表当前值 + 改动高亮(update 可继续在卡上修正字段)/ 单据摘要 + 状态变化高亮(状态类只读)。
   点卡上按钮(保存/审核/作废/…)→ 确定性端点 /preview/{id}/save 重校验后写 ai_op_queue;
   点按钮前不写入任何数据。【不用了】仅关闭卡片(服务端预览 30 分钟自动过期)。 */
function addPreviewCard(ev) {
    const card = el("div", "card");
    card.appendChild(el("div", "card-title", ev.title || "写操作预览"));
    if (ev.message) {
        const m = el("div", "muted");
        m.style.whiteSpace = "pre-wrap";
        m.textContent = ev.message;
        card.appendChild(m);
    }
    const controls = []; // {label, get()} —— 仅 editable 预览收集
    const bound = {}; // 已选中记录的 id(字段名→id),供 ERP 级联下拉过滤
    (ev.fields || []).forEach(f => { if (f.boundId) bound[f.name] = f.boundId; }); // 记录原有绑定作初始上下文
    const ctxOf = () => Object.assign({}, bound);
    if (ev.editable) {
        const grid = el("div", "form-grid");
        (ev.fields || []).forEach(f => {
            const wrap = el("div", "ffield" + (f.changed ? " changed" : ""));
            const lab = el("label");
            lab.textContent = f.label || f.name;
            wrap.appendChild(lab);
            const initial = f.changed ? (f.newValue || "") : (f.value || "");
            let getter;
            if (f.type === "fkselect") {
                const row = el("div", "fkrow");
                const inp = el("input");
                inp.readOnly = true;
                inp.placeholder = "点击选择…";
                inp.value = initial;
                const pick = el("button", "btn", "选择");
                pick.onclick = () => openFkPicker(
                    { fkTable: f.fkTable, formId: ev.formId, name: f.name, ctx: ctxOf },
                    f.label || f.name,
                    (name, id) => {
                        inp.value = name;
                        if (id) bound[f.name] = id; else delete bound[f.name];
                    });
                row.appendChild(inp);
                row.appendChild(pick);
                wrap.appendChild(row);
                getter = () => inp.value.trim();
            } else if (f.type === "select" && Array.isArray(f.options) && f.options.length) {
                const sel = el("select");
                sel.appendChild(el("option", null, ""));
                f.options.forEach(o => {
                    const op = el("option", null, o);
                    op.value = o;
                    sel.appendChild(op);
                });
                sel.value = initial;
                wrap.appendChild(sel);
                getter = () => sel.value;
            } else {
                const inp = el("input");
                if (f.type === "number") { inp.type = "text"; inp.inputMode = "decimal"; }
                else if (f.type === "date") inp.type = "date";
                inp.value = initial;
                wrap.appendChild(inp);
                getter = () => inp.value.trim();
            }
            if (f.changed && f.value) wrap.appendChild(el("div", "oldval", "原值:" + f.value));
            grid.appendChild(wrap);
            // 键 = 技术列名(同表两列同中文名时 label 键会串写);空值 = 放弃该字段的改动
            controls.push({ name: f.name, get: getter });
        });
        card.appendChild(grid);
    } else {
        (ev.fields || []).forEach(f => {
            const row = el("div", "preview-ro");
            row.appendChild(el("span", "l", (f.label || f.name) + ":"));
            row.appendChild(el("span", null, f.value == null ? "" : String(f.value)));
            card.appendChild(row);
        });
        if (ev.statusChange && ev.statusChange.label) {
            const sc = el("div", "status-change");
            sc.appendChild(el("span", null, ev.statusChange.label + ":"));
            sc.appendChild(el("span", "from", ev.statusChange.from || ""));
            sc.appendChild(el("span", null, "→ "));
            sc.appendChild(el("span", "to", ev.statusChange.to || ""));
            card.appendChild(sc);
        }
    }

    const actions = el("div", "actions");
    const ok = el("button", "btn primary", ev.buttonLabel || "保存");
    const no = el("button", "btn", "不用了");
    actions.appendChild(ok);
    actions.appendChild(no);
    card.appendChild(actions);
    const result = el("div", "result");
    card.appendChild(result);
    messagesEl.appendChild(card);
    scrollBottom();

    ok.onclick = async () => {
        ok.disabled = no.disabled = true;
        result.className = "result";
        result.textContent = "提交中…";
        try {
            const fields = {};
            controls.forEach(c => { fields[c.name] = c.get(); });
            const r = await fetch(BASE + "/api/agent/preview/" + encodeURIComponent(ev.previewId) + "/save",
                { method: "POST", headers: authHeaders(true), body: JSON.stringify({ fields: fields }) });
            const d = await r.json();
            if (d.queued) {
                result.className = "result ok";
                result.textContent = d.message || "已提交待办。";
            } else {
                ok.disabled = no.disabled = false;
                result.className = "result bad";
                result.textContent = d.error || "提交失败。";
            }
        } catch (e) {
            ok.disabled = no.disabled = false;
            result.className = "result bad";
            result.textContent = "提交失败:" + e.message;
        }
        scrollBottom();
    };
    no.onclick = () => {
        ok.disabled = no.disabled = true;
        result.className = "result";
        result.textContent = "已关闭(未提交任何操作)。";
    };
}

/* ================= askUser 追问卡(选项片 + 永远保留自由输入) ================= */
function addQuestionCard(question, options, allowFree) {
    const card = el("div", "card");
    card.appendChild(el("div", "card-title", question || "请补充信息"));
    const chips = el("div", "chips");
    options.forEach(o => {
        const c = el("button", "chip", o);
        c.onclick = () => { card.remove(); sendMessage(o); };
        chips.appendChild(c);
    });
    if (options.length) card.appendChild(chips);
    if (allowFree) {
        const free = el("div", "chip-free");
        const inp = el("input");
        inp.placeholder = options.length ? "或输入其他答案…" : "输入你的回答…";
        const go = el("button", "btn", "回复");
        const submit = () => {
            const v = inp.value.trim();
            if (!v) return;
            card.remove();
            sendMessage(v);
        };
        go.onclick = submit;
        inp.onkeydown = (e) => { if (e.key === "Enter") submit(); };
        free.appendChild(inp);
        free.appendChild(go);
        card.appendChild(free);
    }
    messagesEl.appendChild(card);
    scrollBottom();
}

/* ================= collectForm 表单卡 ================= */
function addFormCard(ev) {
    const card = el("div", "card");
    card.appendChild(el("div", "card-title", ev.title || ("新建" + (ev.entity || ""))));
    if (ev.message) card.appendChild(el("div", "muted", ev.message));
    const grid = el("div", "form-grid");
    const controls = []; // {label, required, get()}
    // 已选中记录的 id(字段名→id):ERP 的级联下拉要靠它过滤(如产品限定在已选客户名下)
    const bound = {};
    const ctxOf = () => Object.assign({}, bound);

    (ev.fields || []).forEach(f => {
        const wrap = el("div", "ffield");
        const lab = el("label");
        lab.textContent = f.label || f.name;
        if (f.required) lab.appendChild(el("span", "req", "*"));
        wrap.appendChild(lab);

        let getter;
        if (f.type === "fkselect") {
            const row = el("div", "fkrow");
            const inp = el("input");
            inp.readOnly = true;
            inp.placeholder = "点击选择…";
            if (f.default) inp.value = f.default;
            const pick = el("button", "btn", "选择");
            pick.onclick = () => openFkPicker(
                { fkTable: f.fkTable, formId: ev.formId, name: f.name, ctx: ctxOf },
                f.label || f.name,
                (name, id) => {
                    inp.value = name;
                    if (id) bound[f.name] = id; else delete bound[f.name];
                });
            row.appendChild(inp);
            row.appendChild(pick);
            wrap.appendChild(row);
            getter = () => inp.value.trim();
        } else if (f.type === "select" && Array.isArray(f.options) && f.options.length) {
            const sel = el("select");
            sel.appendChild(el("option", null, ""));
            f.options.forEach(o => {
                const op = el("option", null, o);
                op.value = o;
                sel.appendChild(op);
            });
            if (f.default) sel.value = f.default;
            wrap.appendChild(sel);
            getter = () => sel.value;
        } else {
            const inp = el("input");
            if (f.type === "number") { inp.type = "text"; inp.inputMode = "decimal"; }
            else if (f.type === "date") inp.type = "date";
            if (f.default) inp.value = f.default;
            wrap.appendChild(inp);
            getter = () => inp.value.trim();
        }
        if (f.hint) wrap.appendChild(el("div", "hint", f.hint));
        grid.appendChild(wrap);
        controls.push({ label: f.label || f.name, required: !!f.required, get: getter });
    });
    card.appendChild(grid);

    const actions = el("div", "actions");
    const submit = el("button", "btn primary", "保存");
    const result = el("div", "result");
    actions.appendChild(submit);
    card.appendChild(actions);
    card.appendChild(result);
    messagesEl.appendChild(card);
    scrollBottom();

    submit.onclick = async () => {
        const fields = {};
        for (const c of controls) {
            const v = c.get();
            if (c.required && !v) {
                result.className = "result bad";
                result.textContent = "「" + c.label + "」为必填项。";
                return;
            }
            if (v) fields[c.label] = v;
        }
        if (!Object.keys(fields).length) {
            result.className = "result bad";
            result.textContent = "请至少填写一个字段。";
            return;
        }
        submit.disabled = true;
        result.className = "result";
        result.textContent = "保存中…";
        try {
            // 确定性保存:结构化字段直达 create 校验并写 ai_op_queue(不经 LLM 再编码);执行由 ERP 侧负责
            const r = await fetch(BASE + "/api/agent/form/submit", {
                method: "POST",
                headers: authHeaders(true),
                body: JSON.stringify({
                    entity: ev.entity,
                    fields: fields,
                    conversationId: conversationId
                })
            });
            const d = await r.json();
            if (d.queued) {
                result.className = "result ok";
                result.textContent = d.message || "已提交待办。";
            } else {
                submit.disabled = false;
                result.className = "result bad";
                result.textContent = d.error || "保存失败。";
            }
        } catch (e) {
            submit.disabled = false;
            result.className = "result bad";
            result.textContent = "保存失败:" + e.message;
        }
        loadConvs();
    };
}

/* ================= FK 二级选择器(列表/搜索/分页/选择) =================
   候选优先由 ERP 按其下拉配置给(带行级权限/级联过滤/联动回填),故要把 formId、字段名、
   以及本表单上**已绑定的其它字段 id**(ctx)一并带上;ERP 说缺上级字段时提示用户先选那一个。 */
const fk = { table: null, formId: null, field: null, ctx: null, q: "", page: 1, pageSize: 20, total: 0, onPick: null };

function openFkPicker(opts, title, onPick) {
    fk.table = opts.fkTable;
    fk.formId = opts.formId || null;
    fk.field = opts.name || null;
    fk.ctx = opts.ctx || null;
    fk.q = "";
    fk.page = 1;
    fk.onPick = onPick;
    $("#fkTitle").textContent = "选择" + (title || "");
    $("#fkSearch").value = "";
    $("#modalMask").classList.add("show");
    loadFkPage();
    $("#fkSearch").focus();
}

async function loadFkPage() {
    const body = $("#fkBody");
    body.innerHTML = '<div style="padding:20px;color:#888">加载中…</div>';
    try {
        let url = BASE + "/api/agent/form/options?table=" + encodeURIComponent(fk.table)
            + "&q=" + encodeURIComponent(fk.q)
            + "&page=" + fk.page + "&pageSize=" + fk.pageSize;
        if (fk.formId && fk.field) {
            url += "&formId=" + encodeURIComponent(fk.formId) + "&field=" + encodeURIComponent(fk.field);
            const ctx = typeof fk.ctx === "function" ? fk.ctx() : fk.ctx;
            if (ctx && Object.keys(ctx).length) url += "&ctx=" + encodeURIComponent(JSON.stringify(ctx));
        }
        const d = await (await fetch(url, { headers: authHeaders(false) })).json();
        if (d.needContext) {
            body.innerHTML = '<div style="padding:20px;color:#8a6d3b">' + (d.message || "请先选择上级字段。") + "</div>";
            $("#fkPageInfo").textContent = "";
            $("#fkPrev").disabled = true;
            $("#fkNext").disabled = true;
            return;
        }
        fk.total = d.total || 0;
        const cols = d.columns || [];
        const rows = d.rows || [];
        const table = el("table");
        const thead = el("thead");
        const trh = el("tr");
        cols.forEach(c => trh.appendChild(el("th", null, c.label)));
        thead.appendChild(trh);
        table.appendChild(thead);
        const tbody = el("tbody");
        const nameCol = d.nameField || (cols.length ? cols[0].col : null);
        const valueCol = d.valueField || "sId";
        rows.forEach(r => {
            const tr = el("tr");
            cols.forEach(c => tr.appendChild(el("td", null, r[c.col] == null ? "" : String(r[c.col]))));
            tr.onclick = () => {
                $("#modalMask").classList.remove("show");
                if (fk.onPick && nameCol) fk.onPick(String(r[nameCol] || ""), r[valueCol] == null ? null : String(r[valueCol]));
            };
            tbody.appendChild(tr);
        });
        table.appendChild(tbody);
        body.innerHTML = "";
        if (!rows.length) {
            body.innerHTML = '<div style="padding:20px;color:#888">没有匹配的记录</div>';
        } else {
            body.appendChild(table);
        }
        const pages = Math.max(1, Math.ceil(fk.total / fk.pageSize));
        $("#fkPageInfo").textContent = "共 " + fk.total + " 条 · 第 " + fk.page + "/" + pages + " 页";
        $("#fkPrev").disabled = fk.page <= 1;
        $("#fkNext").disabled = fk.page >= pages;
    } catch (e) {
        body.innerHTML = '<div style="padding:20px;color:#c0392b">加载失败:' + e.message + "</div>";
    }
}

$("#fkClose").onclick = () => $("#modalMask").classList.remove("show");
$("#modalMask").onclick = (e) => { if (e.target === $("#modalMask")) $("#modalMask").classList.remove("show"); };
$("#fkPrev").onclick = () => { if (fk.page > 1) { fk.page--; loadFkPage(); } };
$("#fkNext").onclick = () => { fk.page++; loadFkPage(); };
let fkSearchTimer;
$("#fkSearch").oninput = (e) => {
    clearTimeout(fkSearchTimer);
    fkSearchTimer = setTimeout(() => { fk.q = e.target.value.trim(); fk.page = 1; loadFkPage(); }, 300);
};

/* ================= 输入框 & 初始化 ================= */
const input = $("#messageInput");
input.addEventListener("keydown", (e) => {
    if (e.key === "Enter" && !e.shiftKey) {
        e.preventDefault();
        const v = input.value;
        input.value = "";
        input.style.height = "auto";
        sendMessage(v);
    }
});
input.addEventListener("input", () => {
    input.style.height = "auto";
    input.style.height = Math.min(input.scrollHeight, 140) + "px";
});
$("#sendBtn").onclick = () => {
    const v = input.value;
    input.value = "";
    input.style.height = "auto";
    sendMessage(v);
};
$("#toggleSide").onclick = () => $("#sidebar").classList.toggle("hidden");
$("#newConvBtn").onclick = newConv;

newConv();
</script>
</body>
</html>