<template>
  <section class="system-extension-workbench">
    <header class="extension-workbench-head">
      <div>
        <p class="eyebrow">系统管理</p>
        <h2>系统拓展</h2>
      </div>
      <div class="extension-status-strip" aria-label="系统拓展状态概览">
        <article
          v-for="card in statusCards"
          :key="card.label"
          class="extension-status-pill"
          :class="`extension-status-${card.tone}`"
        >
          <span>{{ card.label }}</span>
          <strong>{{ card.value }}</strong>
        </article>
      </div>
    </header>

    <div v-if="feedbackMessage" class="feedback-banner">{{ feedbackMessage }}</div>
    <div v-if="errorMessage" class="feedback-banner error-banner">{{ errorMessage }}</div>

    <section class="extension-config-shell">
      <nav class="extension-nav-rail" aria-label="系统拓展配置目录">
        <button
          v-for="section in extensionSections"
          :key="section.key"
          class="extension-nav-button"
          :class="[{ active: activeSection === section.key }, `extension-nav-${section.accent}`]"
          type="button"
          :aria-pressed="activeSection === section.key"
          @click="activeSection = section.key"
        >
          <span class="extension-nav-mark" aria-hidden="true"></span>
          <strong>{{ section.title }}</strong>
        </button>
      </nav>

      <main class="extension-module-panel">
        <div class="extension-module-head">
          <div>
            <h3>{{ activeSectionMeta.title }}</h3>
          </div>
          <span v-if="activeSectionDirty" class="panel-tag warning-tag">有未保存修改</span>
          <span v-else class="panel-tag">已同步</span>
        </div>

        <section v-if="activeSection === 'broadcast'" class="extension-broadcast-ledger">
          <section class="extension-list-card extension-list-card-full">
            <div class="form-section-title extension-list-title">
              <div class="extension-title-stack">
                <strong>广播记录</strong>
                <span class="panel-tag">{{ filteredBroadcasts.length }} 条</span>
              </div>
              <button
                class="primary-button extension-add-button"
                type="button"
                data-semantic-label="新增广播"
                @click="openNewBroadcastDialog"
              >
                新增广播
              </button>
            </div>

            <TableControls
              v-model:search="broadcastControls.search.value"
              v-model:sort-key="broadcastControls.sortKey.value"
              v-model:sort-direction="broadcastControls.sortDirection.value"
              :sort-options="broadcastControls.sortOptions"
              placeholder="搜索标题、内容、状态、类型"
            />

            <div class="table-wrap extension-table-wrap">
              <table class="data-table compact-table">
                <thead>
                  <tr>
                    <th>标题</th>
                    <th>考勤点</th>
                    <th>内容</th>
                    <th>类型</th>
                    <th>状态</th>
                    <th>开始</th>
                    <th>结束</th>
                    <th>排序</th>
                    <th>操作</th>
                  </tr>
                </thead>
                <tbody>
                  <tr v-for="item in paginatedBroadcasts" :key="item.broadcast_id">
                    <td>{{ item.title }}</td>
                    <td>{{ formatAttendancePoints(item.attendance_point_names) }}</td>
                    <td>{{ item.content }}</td>
                    <td><span class="status-chip" :class="`status-${String(item.tone || 'INFO').toLowerCase()}`">{{ formatToneLabel(item.tone) }}</span></td>
                    <td><span class="status-chip" :class="item.status === 'ACTIVE' ? 'status-active' : 'status-paused'">{{ item.status === "ACTIVE" ? "启用" : "暂停" }}</span></td>
                    <td>{{ formatDateTime(item.starts_at) }}</td>
                    <td>{{ formatDateTime(item.ends_at) }}</td>
                    <td>{{ item.sort_no }}</td>
                    <td class="action-row">
                      <button class="ghost-button" type="button" @click="editBroadcast(item)">编辑</button>
                    </td>
                  </tr>
                  <tr v-if="!filteredBroadcasts.length">
                    <td colspan="9" class="empty-row">暂无广播内容</td>
                  </tr>
                </tbody>
              </table>
            </div>
            <PaginationBar v-model:page="broadcastPage" v-model:page-size="broadcastPageSize" :total="filteredBroadcasts.length" />
          </section>
        </section>

        <form
          v-else-if="activeSection === 'rawLotPrefix'"
          id="extension-form-rawLotPrefix"
          class="stack-form extension-form-card"
          @submit.prevent="saveActiveSection"
        >
          <div class="extension-setting-block" title="序号达到 9999 后自然扩展为下一位数，不截断、不补新规则。">
            <span class="setting-kicker">当前规则</span>
            <strong>{{ rawLotPrefixForm.config_value || "YL" }}0001</strong>
            <em>自动递增</em>
          </div>

          <div class="extension-field-grid extension-field-grid-2">
            <label class="form-field">
              <span>前缀</span>
              <input v-model.trim="rawLotPrefixForm.config_value" type="text" maxlength="20" placeholder="默认 YL" />
            </label>
            <label class="form-field">
              <span>说明</span>
              <input v-model.trim="rawLotPrefixForm.remark" type="text" placeholder="例如：原材料库存批次号默认前缀" />
            </label>
          </div>
        </form>

        <form
          v-else-if="activeSection === 'productionMode'"
          id="extension-form-productionMode"
          class="stack-form extension-form-card"
          @submit.prevent="saveActiveSection"
        >
          <label class="extension-mode-switch" :class="{ active: smartOperationReportForm.enabled }">
            <input v-model="smartOperationReportForm.enabled" type="checkbox" />
            <span class="switch-track" aria-hidden="true"></span>
            <span>
              <strong>对接智能报工小程序</strong>
              <small class="extension-inline-state">{{ smartOperationReportForm.enabled ? "当前：已对接" : "当前：未对接" }}</small>
            </span>
          </label>

          <details class="extension-detail-note">
            <summary>查看影响范围</summary>
            <p>开启时显示工序报工和小程序证据；关闭时隐藏工序报工，生产按 ERP 入库闭环推进。</p>
          </details>

          <label class="form-field">
            <span>说明</span>
            <input v-model.trim="smartOperationReportForm.remark" type="text" placeholder="例如：客户未购买小程序模块，暂按ERP入库反推" />
          </label>
        </form>

        <form
          v-else-if="activeSection === 'assistant'"
          id="extension-form-assistant"
          class="stack-form extension-form-card"
          @submit.prevent="saveActiveSection"
        >
          <div class="extension-field-grid extension-field-grid-3">
            <label class="form-field">
              <span>助手名称</span>
              <input v-model.trim="assistantForm.assistant_name" type="text" required />
            </label>
            <label class="form-field">
              <span>供应商</span>
              <input v-model.trim="assistantForm.provider_name" type="text" placeholder="例如：OpenRouter / SiliconFlow" />
            </label>
            <label class="form-field">
              <span>模型名称</span>
              <input v-model.trim="assistantForm.model_name" type="text" placeholder="例如：deepseek-chat" />
            </label>
          </div>

          <div class="extension-field-grid extension-field-grid-2">
            <label class="form-field">
              <span>API Base URL</span>
              <input v-model.trim="assistantForm.api_base_url" type="text" placeholder="https://api.example.com/v1" />
            </label>
            <label class="form-field">
              <span>API Key</span>
              <input v-model.trim="assistantForm.api_key" type="password" :placeholder="assistantConfig.api_key_configured ? '留空表示不修改现有密钥' : '请输入 API Key'" />
            </label>
          </div>

          <div class="extension-field-grid extension-field-grid-2">
            <label class="form-field">
              <span>温度</span>
              <input v-model.number="assistantForm.temperature" type="number" min="0" max="2" step="0.1" />
            </label>
            <label class="extension-mode-switch" :class="{ active: assistantForm.enabled }">
              <input v-model="assistantForm.enabled" type="checkbox" />
              <span class="switch-track" aria-hidden="true"></span>
              <span>
                <strong>启用真实 LLM 调用</strong>
                <small class="extension-inline-state">{{ assistantConfig.api_key_configured ? "密钥已配置" : "未配置密钥" }}</small>
              </span>
            </label>
          </div>

          <label class="form-field">
            <span>每次新建对话的系统提示词</span>
            <textarea v-model.trim="assistantForm.system_prompt" rows="6"></textarea>
          </label>
        </form>
      </main>
    </section>

    <Teleport to="body">
      <div v-if="showBroadcastDialog" class="extension-modal-backdrop" @click.self="closeBroadcastDialog">
        <section class="extension-modal-card" role="dialog" aria-modal="true" aria-labelledby="broadcast-dialog-title">
          <header class="extension-modal-head">
            <div>
              <p class="eyebrow">广播通知</p>
              <h3 id="broadcast-dialog-title">{{ editingBroadcastId ? "编辑广播" : "新增广播" }}</h3>
            </div>
            <button class="ghost-button extension-modal-close" type="button" @click="closeBroadcastDialog">关闭</button>
          </header>

          <form id="extension-form-broadcast" class="stack-form extension-dialog-form" @submit.prevent="saveBroadcast">
            <div class="extension-field-grid extension-field-grid-2">
              <label class="form-field">
                <span>广播标题 <i class="required-mark">*</i></span>
                <input v-model.trim="broadcastForm.title" type="text" required />
              </label>
              <label class="form-field">
                <span>提示类型</span>
                <select v-model="broadcastForm.tone">
                  <option value="INFO">信息</option>
                  <option value="SUCCESS">成功</option>
                  <option value="WARNING">预警</option>
                  <option value="DANGER">重要</option>
                </select>
              </label>
            </div>

            <label class="form-field">
              <span>广播内容 <i class="required-mark">*</i></span>
              <input v-model.trim="broadcastForm.content" type="text" required />
            </label>

            <div class="form-field">
              <span>通知考勤点 <i class="required-mark">*</i></span>
              <div class="checkbox-grid extension-checkbox-grid">
                <label v-for="point in attendancePoints" :key="point.name" class="checkbox-field">
                  <input v-model="broadcastForm.attendance_point_names" type="checkbox" :value="point.name" />
                  <span>{{ point.name }}</span>
                </label>
              </div>
            </div>

            <div class="extension-field-grid extension-field-grid-3">
              <label class="form-field">
                <span>开始时间</span>
                <input v-model="broadcastForm.starts_at" type="datetime-local" />
              </label>
              <label class="form-field">
                <span>结束时间</span>
                <input v-model="broadcastForm.ends_at" type="datetime-local" />
              </label>
              <label class="form-field">
                <span>排序号</span>
                <input v-model.number="broadcastForm.sort_no" type="number" step="1" />
              </label>
            </div>

            <div class="extension-field-grid extension-broadcast-status-row">
              <label class="form-field">
                <span>状态</span>
                <select v-model="broadcastForm.status">
                  <option value="ACTIVE">启用</option>
                  <option value="PAUSED">暂停</option>
                </select>
              </label>
              <details class="extension-preview-disclosure">
                <summary>查看横幅预览</summary>
                <div class="extension-banner-preview">
                  <div class="broadcast-banner" :class="`broadcast-${broadcastForm.tone.toLowerCase()}`">
                    <span class="broadcast-speaker" aria-hidden="true">
                      <svg viewBox="0 0 24 24" role="img">
                        <path d="M4 10.5H7.5L16 6.5V17.5L7.5 13.5H4V10.5Z" />
                        <path d="M7.5 13.5L9.2 19H12.2L10.4 14.8" />
                        <path d="M18.3 9.2L20.5 8" />
                        <path d="M18.7 12H21.4" />
                        <path d="M18.3 14.8L20.5 16" />
                      </svg>
                    </span>
                    <strong>{{ broadcastForm.title || "广播标题" }}</strong>
                    <span>{{ broadcastForm.content || "广播内容" }}</span>
                  </div>
                </div>
              </details>
            </div>

            <footer class="extension-dialog-actions">
              <button class="ghost-button" type="button" @click="closeBroadcastDialog">取消</button>
              <button class="primary-button" type="submit">{{ editingBroadcastId ? "保存修改" : "保存广播" }}</button>
            </footer>
          </form>
        </section>
      </div>
    </Teleport>

    <div v-if="activeSectionDirty" class="extension-save-dock">
      <span>{{ activeSectionMeta.title }}有未保存修改</span>
      <button class="ghost-button" type="button" @click="resetActiveSection">放弃修改</button>
      <button class="primary-button" type="submit" :form="activeSectionFormId">保存配置</button>
    </div>
  </section>
</template>

<script setup>
import { computed, onMounted, reactive, ref } from "vue";

import PaginationBar from "../components/PaginationBar.vue";
import TableControls from "../components/TableControls.vue";
import { fetchResource, postResource, putResource } from "../services/api";
import { resetSmartOperationReportConfigCache } from "../services/systemFeatures";
import { dictionaryFallback, normalizeDictionaryKey } from "../utils/dictionaries";
import { formatDateTime } from "../utils/formatters";
import { usePagination } from "../utils/pagination";
import { useTableControls } from "../utils/tableControls";

const broadcasts = ref([]);
const attendancePoints = ref([]);
const assistantConfig = ref({});
const rawLotPrefixConfig = ref({});
const smartOperationReportConfig = ref({});
const feedbackMessage = ref("");
const errorMessage = ref("");
const editingBroadcastId = ref(null);
const showBroadcastDialog = ref(false);
const activeSection = ref("broadcast");
const extensionLoaded = ref(false);
const sectionSnapshots = reactive({
  broadcast: "",
  rawLotPrefix: "",
  productionMode: "",
  assistant: ""
});

const extensionSections = [
  {
    key: "broadcast",
    eyebrow: "Broadcast",
    title: "广播通知",
    desc: "维护右上角小喇叭通知",
    accent: "blue"
  },
  {
    key: "rawLotPrefix",
    eyebrow: "Lot Rule",
    title: "库存批次规则",
    desc: "维护原材料库存批次号前缀",
    accent: "steel"
  },
  {
    key: "productionMode",
    eyebrow: "Production",
    title: "生产对接模式",
    desc: "控制是否对接智能报工小程序",
    accent: "green"
  },
  {
    key: "assistant",
    eyebrow: "AI Assistant",
    title: "AI 助手配置",
    desc: "维护 LLM 供应商、模型与提示词",
    accent: "orange"
  }
];

const broadcastForm = reactive(buildEmptyBroadcastForm());
const assistantForm = reactive(buildEmptyAssistantForm());
const rawLotPrefixForm = reactive({ config_value: "YL", remark: "" });
const smartOperationReportForm = reactive({ enabled: true, remark: "" });

const broadcastControls = useTableControls(broadcasts, {
  searchFields: ["title", "content", "tone", "status", (row) => row.attendance_point_names?.join(" / ")],
  sortOptions: [
    { key: "broadcast_id", label: "创建顺序" },
    { key: "title", label: "标题" },
    { key: "status", label: "状态" },
    { key: "sort_no", label: "排序号" },
    { key: "updated_at", label: "更新时间" }
  ],
  defaultSortKey: "broadcast_id",
  defaultSortDirection: "desc"
});

const filteredBroadcasts = broadcastControls.rows;
const {
  page: broadcastPage,
  pageSize: broadcastPageSize,
  rows: paginatedBroadcasts
} = usePagination(filteredBroadcasts);

function buildEmptyBroadcastForm() {
  return {
    title: "",
    content: "",
    attendance_point_names: [],
    tone: "INFO",
    status: "ACTIVE",
    starts_at: "",
    ends_at: "",
    sort_no: 10
  };
}

function buildEmptyAssistantForm() {
  return {
    assistant_name: "百华工艺助手",
    provider_name: "",
    api_base_url: "",
    api_key: "",
    model_name: "",
    temperature: 0.3,
    system_prompt: "你是宁波百华智能五金 ERP 的企业助手，优先解释业务流程、字段含义、数据异常和操作步骤。",
    enabled: false
  };
}

function normalizeDateTime(value) {
  return value ? `${value}:00` : null;
}

function toDateTimeInput(value) {
  return value ? String(value).replace("T", " ").slice(0, 16).replace(" ", "T") : "";
}

function formatToneLabel(value) {
  return {
    INFO: "信息",
    SUCCESS: "成功",
    WARNING: "预警",
    DANGER: "重要"
  }[normalizeDictionaryKey(value)] || dictionaryFallback(value, "-", "未识别通知类型");
}

function resetBroadcastForm() {
  editingBroadcastId.value = null;
  Object.assign(broadcastForm, buildEmptyBroadcastForm());
  broadcastForm.attendance_point_names = attendancePoints.value.map((point) => point.name);
  captureSectionSnapshot("broadcast");
}

function openNewBroadcastDialog() {
  resetBroadcastForm();
  showBroadcastDialog.value = true;
}

function closeBroadcastDialog() {
  showBroadcastDialog.value = false;
  resetBroadcastForm();
}

function editBroadcast(item) {
  editingBroadcastId.value = item.broadcast_id;
  Object.assign(broadcastForm, {
    title: item.title || "",
    content: item.content || "",
    attendance_point_names: item.attendance_point_names?.length
      ? [...item.attendance_point_names]
      : attendancePoints.value.map((point) => point.name),
    tone: item.tone || "INFO",
    status: item.status || "ACTIVE",
    starts_at: toDateTimeInput(item.starts_at),
    ends_at: toDateTimeInput(item.ends_at),
    sort_no: Number(item.sort_no || 0)
  });
  captureSectionSnapshot("broadcast");
  showBroadcastDialog.value = true;
}

function formatAttendancePoints(pointNames) {
  return pointNames?.length ? pointNames.join(" / ") : "-";
}

function clonePlain(value) {
  return JSON.parse(JSON.stringify(value));
}

function serializeValue(value) {
  return JSON.stringify(value);
}

function getSectionState(sectionKey) {
  if (sectionKey === "broadcast") {
    return {
      editingBroadcastId: editingBroadcastId.value,
      ...clonePlain(broadcastForm)
    };
  }

  if (sectionKey === "rawLotPrefix") {
    return clonePlain(rawLotPrefixForm);
  }

  if (sectionKey === "productionMode") {
    return clonePlain(smartOperationReportForm);
  }

  if (sectionKey === "assistant") {
    return {
      ...clonePlain(assistantForm),
      api_key: ""
    };
  }

  return {};
}

function captureSectionSnapshot(sectionKey) {
  sectionSnapshots[sectionKey] = serializeValue(getSectionState(sectionKey));
}

function captureAllSectionSnapshots() {
  extensionSections.forEach((section) => {
    captureSectionSnapshot(section.key);
  });
}

function restoreSectionSnapshot(sectionKey) {
  const snapshot = sectionSnapshots[sectionKey] ? JSON.parse(sectionSnapshots[sectionKey]) : null;
  if (!snapshot) {
    return false;
  }

  if (sectionKey === "broadcast") {
    editingBroadcastId.value = snapshot.editingBroadcastId ?? null;
    Object.assign(broadcastForm, {
      title: snapshot.title || "",
      content: snapshot.content || "",
      attendance_point_names: Array.isArray(snapshot.attendance_point_names)
        ? [...snapshot.attendance_point_names]
        : attendancePoints.value.map((point) => point.name),
      tone: snapshot.tone || "INFO",
      status: snapshot.status || "ACTIVE",
      starts_at: snapshot.starts_at || "",
      ends_at: snapshot.ends_at || "",
      sort_no: Number(snapshot.sort_no ?? 10)
    });
    return true;
  }

  if (sectionKey === "rawLotPrefix") {
    rawLotPrefixForm.config_value = snapshot.config_value || "YL";
    rawLotPrefixForm.remark = snapshot.remark || "";
    return true;
  }

  if (sectionKey === "productionMode") {
    smartOperationReportForm.enabled = snapshot.enabled !== false;
    smartOperationReportForm.remark = snapshot.remark || "";
    return true;
  }

  if (sectionKey === "assistant") {
    Object.assign(assistantForm, {
      assistant_name: snapshot.assistant_name || "百华工艺助手",
      provider_name: snapshot.provider_name || "",
      api_base_url: snapshot.api_base_url || "",
      api_key: "",
      model_name: snapshot.model_name || "",
      temperature: Number(snapshot.temperature ?? 0.3),
      system_prompt: snapshot.system_prompt || buildEmptyAssistantForm().system_prompt,
      enabled: Boolean(snapshot.enabled)
    });
    return true;
  }

  return false;
}

function applyAssistantConfig(config) {
  assistantConfig.value = config || {};
  Object.assign(assistantForm, {
    assistant_name: config?.assistant_name || "百华工艺助手",
    provider_name: config?.provider_name || "",
    api_base_url: config?.api_base_url || "",
    api_key: "",
    model_name: config?.model_name || "",
    temperature: Number(config?.temperature ?? 0.3),
    system_prompt: config?.system_prompt || buildEmptyAssistantForm().system_prompt,
    enabled: Boolean(config?.enabled)
  });
}

function applyRawLotPrefixConfig(config) {
  rawLotPrefixConfig.value = config || {};
  rawLotPrefixForm.config_value = config?.config_value || "YL";
  rawLotPrefixForm.remark = config?.remark || "";
}

function applySmartOperationReportConfig(config) {
  smartOperationReportConfig.value = config || {};
  smartOperationReportForm.enabled = config?.enabled !== false;
  smartOperationReportForm.remark = config?.remark || "";
}

const activeSectionMeta = computed(() => {
  return extensionSections.find((section) => section.key === activeSection.value) || extensionSections[0];
});

const activeSectionFormId = computed(() => `extension-form-${activeSection.value}`);

const activeBroadcastCount = computed(() => {
  return broadcasts.value.filter((item) => item.status === "ACTIVE").length;
});

const assistantStateLabel = computed(() => {
  if (assistantConfig.value.enabled && assistantConfig.value.api_key_configured) {
    return "已启用";
  }
  if (assistantConfig.value.api_key_configured) {
    return "密钥已配置";
  }
  return "占位模式";
});

const statusCards = computed(() => [
  {
    label: "广播启用",
    value: `${activeBroadcastCount.value} 条`,
    tone: activeBroadcastCount.value ? "success" : "muted"
  },
  {
    label: "库存批次前缀",
    value: rawLotPrefixConfig.value.config_value || rawLotPrefixForm.config_value || "YL",
    tone: "info"
  },
  {
    label: "报工小程序",
    value: smartOperationReportForm.enabled ? "已对接" : "未对接",
    tone: smartOperationReportForm.enabled ? "success" : "warning"
  },
  {
    label: "AI 助手",
    value: assistantStateLabel.value,
    tone: assistantConfig.value.enabled ? "success" : "muted"
  }
]);

const activeSectionDirty = computed(() => {
  if (!extensionLoaded.value) {
    return false;
  }
  if (activeSection.value === "broadcast") {
    return false;
  }
  if (activeSection.value === "assistant" && assistantForm.api_key.trim()) {
    return true;
  }
  return sectionSnapshots[activeSection.value] !== serializeValue(getSectionState(activeSection.value));
});

async function loadAll() {
  const [pointRows, broadcastRows, config, rawLotPrefix, smartOperationReport] = await Promise.all([
    fetchResource("/master-data/miniapp-attendance-points", []),
    fetchResource("/system-extension/broadcasts", []),
    fetchResource("/system-extension/assistant-config", buildEmptyAssistantForm()),
    fetchResource("/system-extension/raw-material-lot-prefix", { config_value: "YL", remark: "" }),
    fetchResource("/system-extension/smart-operation-report", { enabled: true, config_value: "开启", remark: "" })
  ]);
  attendancePoints.value = pointRows;
  broadcasts.value = broadcastRows;
  if (!broadcastForm.attendance_point_names.length) {
    broadcastForm.attendance_point_names = pointRows.map((point) => point.name);
  }
  applyAssistantConfig(config);
  applyRawLotPrefixConfig(rawLotPrefix);
  applySmartOperationReportConfig(smartOperationReport);
}

async function saveBroadcast() {
  feedbackMessage.value = "";
  errorMessage.value = "";
  try {
    if (!broadcastForm.attendance_point_names.length) {
      throw new Error("请至少选择一个通知考勤点");
    }
    const payload = {
      title: broadcastForm.title,
      content: broadcastForm.content,
      attendance_point_names: broadcastForm.attendance_point_names,
      tone: broadcastForm.tone,
      status: broadcastForm.status,
      starts_at: normalizeDateTime(broadcastForm.starts_at),
      ends_at: normalizeDateTime(broadcastForm.ends_at),
      sort_no: Number(broadcastForm.sort_no || 0)
    };
    const result = editingBroadcastId.value
      ? await putResource(`/system-extension/broadcasts/${editingBroadcastId.value}`, payload)
      : await postResource("/system-extension/broadcasts", payload);
    feedbackMessage.value = `广播「${result.title}」已保存`;
    showBroadcastDialog.value = false;
    resetBroadcastForm();
    try {
      broadcasts.value = await fetchResource("/system-extension/broadcasts", []);
    } catch (refreshError) {
      errorMessage.value = `广播已保存，但列表刷新失败：${refreshError.message || "请稍后刷新页面"}`;
    }
    captureSectionSnapshot("broadcast");
    return true;
  } catch (error) {
    errorMessage.value = error.message || "广播保存失败";
    return false;
  }
}

async function saveAssistantConfig() {
  feedbackMessage.value = "";
  errorMessage.value = "";
  try {
    const payload = {
      assistant_name: assistantForm.assistant_name,
      provider_name: assistantForm.provider_name || null,
      api_base_url: assistantForm.api_base_url || null,
      api_key: assistantForm.api_key || null,
      model_name: assistantForm.model_name || null,
      temperature: Number(assistantForm.temperature || 0.3),
      system_prompt: assistantForm.system_prompt || null,
      enabled: Boolean(assistantForm.enabled)
    };
    const result = await putResource("/system-extension/assistant-config", payload);
    applyAssistantConfig(result);
    feedbackMessage.value = "AI 机器人配置已保存";
    captureSectionSnapshot("assistant");
    return true;
  } catch (error) {
    errorMessage.value = error.message || "AI 配置保存失败";
    return false;
  }
}

async function saveRawLotPrefixConfig() {
  feedbackMessage.value = "";
  errorMessage.value = "";
  try {
    const result = await putResource("/system-extension/raw-material-lot-prefix", {
      config_value: rawLotPrefixForm.config_value || "YL",
      remark: rawLotPrefixForm.remark || null
    });
    applyRawLotPrefixConfig(result);
    feedbackMessage.value = "原材料库存批次号前缀已保存";
    captureSectionSnapshot("rawLotPrefix");
    return true;
  } catch (error) {
    errorMessage.value = error.message || "原材料库存批次号前缀保存失败";
    return false;
  }
}

async function saveSmartOperationReportConfig() {
  feedbackMessage.value = "";
  errorMessage.value = "";
  try {
    const result = await putResource("/system-extension/smart-operation-report", {
      enabled: Boolean(smartOperationReportForm.enabled),
      remark: smartOperationReportForm.remark || null
    });
    applySmartOperationReportConfig(result);
    resetSmartOperationReportConfigCache(result);
    feedbackMessage.value = "生产模式配置已保存";
    captureSectionSnapshot("productionMode");
    return true;
  } catch (error) {
    errorMessage.value = error.message || "生产模式配置保存失败";
    return false;
  }
}

async function saveActiveSection() {
  if (activeSection.value === "broadcast") {
    return saveBroadcast();
  }

  if (activeSection.value === "rawLotPrefix") {
    return saveRawLotPrefixConfig();
  }

  if (activeSection.value === "productionMode") {
    return saveSmartOperationReportConfig();
  }

  if (activeSection.value === "assistant") {
    return saveAssistantConfig();
  }

  return false;
}

function resetActiveSection() {
  restoreSectionSnapshot(activeSection.value);
}

onMounted(async () => {
  try {
    await loadAll();
  } catch (error) {
    errorMessage.value = error.message || "系统拓展配置加载失败";
  } finally {
    captureAllSectionSnapshots();
    extensionLoaded.value = true;
  }
});
</script>
