<template>
  <section class="settings-page">
    <div class="settings-shell panel">
      <aside class="settings-nav" aria-label="系统设置分类">
        <div class="settings-nav-head">
          <span class="nav-kicker">Settings</span>
          <h2>系统设置</h2>
          <p>已完成 {{ completedSectionCount }} / {{ sections.length }} 项配置</p>
        </div>

        <nav class="settings-nav-list">
          <button
            v-for="section in sections"
            :key="section.id"
            class="settings-nav-item"
            :class="{
              active: activeSection === section.id
            }"
            type="button"
            @click="activateSection(section.id)"
          >
            <span class="nav-item-copy">
              <strong>{{ section.label }}</strong>
              <small>{{ section.desc }}</small>
            </span>
          </button>
        </nav>
      </aside>

      <div class="settings-body">
        <header class="settings-toolbar">
          <div class="settings-toolbar-copy">
            <span class="settings-breadcrumb">首页 / 系统设置 / {{ activeSectionConfig.label }}</span>
            <h3>{{ activeSectionConfig.title }}</h3>
            <p>{{ activeSectionConfig.longDesc }}</p>
          </div>

          <div class="settings-toolbar-actions">
            <button v-if="activeSectionConfig.actionLabel" class="save-button" type="button" @click="saveActiveSection">
              <i class="mdi mdi-content-save-outline"></i>
              <span>{{ activeSectionConfig.actionLabel }}</span>
            </button>
          </div>
        </header>

        <div
          class="settings-content"
          :class="{ 'settings-content-fill': ['systemLogs'].includes(activeSection) }"
        >
          <template v-if="activeSection === 'profile'">
            <section class="settings-card">
              <div class="card-head">
                <div class="card-title-with-icon">
                  <div class="model-icon-box slate">
                    <i class="mdi mdi-domain"></i>
                  </div>
                  <div>
                    <h4>系统基本信息</h4>
                    <p>统一维护企业名称、系统显示名称和版权信息，保存后会同步更新当前系统品牌名称。</p>
                  </div>
                </div>
              </div>

              <div class="form-grid profile-grid">
                <label class="field logo-field">
                  <span><em>*</em> 系统图标</span>
                  <div class="logo-tile" aria-hidden="true" @click="triggerLogoUpload" style="cursor: pointer; overflow: hidden;" title="点击上传图片">
                    <img v-if="pageState.companyForm.logo" :src="pageState.companyForm.logo" style="width:100%;height:100%;object-fit:contain;" />
                    <i v-else class="mdi mdi-domain"></i>
                  </div>
                  <input type="file" ref="logoInputRef" accept="image/*" style="display: none;" @change="handleLogoUpload" />
                  <small style="color:#64748b; font-size:12px; margin-top:4px;">建议尺寸 64x64，PNG/JPG 格式</small>
                </label>

                <label class="field">
                  <span><em>*</em> 企业名称</span>
                  <input v-model="pageState.companyForm.companyName" type="text" placeholder="请输入企业法定名称" />
                </label>

                <label class="field">
                  <span>企业编码</span>
                  <input v-model="pageState.companyForm.companyCode" type="text" placeholder="例如 XF-001" />
                </label>

                <label class="field field-wide">
                  <span><em>*</em> 系统显示名称</span>
                  <input v-model="pageState.companyForm.displayName" type="text" placeholder="请输入系统对内展示名称" />
                </label>

                <label class="field">
                  <span>备案号</span>
                  <input v-model="pageState.companyForm.recordNumber" type="text" placeholder="请输入备案号" />
                </label>

                <label class="field field-full">
                  <span><em>*</em> 版权信息</span>
                  <input
                    v-model="pageState.companyForm.copyright"
                    type="text"
                    placeholder="例如 Copyright © 2024-2026 X-Financial. All Rights Reserved."
                  />
                </label>
              </div>
            </section>
          </template>

          <template v-else-if="activeSection === 'appearance'">
            <section class="settings-card">
              <div class="card-head">
                <div class="card-title-with-icon">
                  <div class="model-icon-box slate">
                    <i class="mdi mdi-tune-variant"></i>
                  </div>
                  <div>
                    <h4>主题风格与界面体验</h4>
                    <p>选择系统整体体验风格，并联动 AI 模式的对话、图标、卡片和提示样式。</p>
                  </div>
                </div>
              </div>

              <div class="theme-option-grid">
                <button
                  v-for="theme in themeSkinOptions"
                  :key="theme.id"
                  class="theme-option"
                  :class="{ active: activeThemeSkinId === theme.id }"
                  type="button"
                  @click="selectThemeSkin(theme.id)"
                >
                  <span class="theme-style-preview" aria-hidden="true">
                    <i :style="{ background: theme.primary }"></i>
                    <i :style="{ background: theme.primarySoftStrong }"></i>
                    <i :style="{ background: theme.secondary }"></i>
                    <i :style="{ background: theme.chartAmber }"></i>
                  </span>
                  <span class="theme-copy">
                    <strong>{{ theme.label }}</strong>
                    <small>{{ theme.desc }}</small>
                    <span class="theme-keywords">
                      <em v-for="keyword in theme.keywords" :key="keyword">{{ keyword }}</em>
                    </span>
                  </span>
                  <span v-if="activeThemeSkinId === theme.id" class="theme-current">当前</span>
                </button>
              </div>

              <div class="theme-preview-panel">
                <div>
                  <strong>{{ activeThemeSkin.label }}</strong>
                  <span>当前主题会同步到全局按钮、焦点环、表单控件和 AI 对话界面。</span>
                </div>
                <div class="theme-preview-surface" aria-hidden="true">
                  <span></span>
                  <i></i>
                  <b></b>
                </div>
              </div>
            </section>
          </template>

          <template v-else-if="activeSection === 'admin'">
            <section class="settings-card">
              <div class="card-head">
                <div class="card-title-with-icon">
                  <div class="model-icon-box slate">
                    <i class="mdi mdi-account-cog-outline"></i>
                  </div>
                  <div>
                    <h4>管理员账号</h4>
                    <p>维护最高权限管理员的登录账户、密码和安全通知邮箱。</p>
                  </div>
                </div>
              </div>

              <div class="form-grid">
                <label class="field">
                  <span><em>*</em> 管理员账号</span>
                  <input v-model="pageState.adminForm.adminAccount" type="text" placeholder="请输入管理员账号" />
                </label>

                <label class="field">
                  <span><em>*</em> 管理员邮箱</span>
                  <input v-model="pageState.adminForm.adminEmail" type="email" placeholder="请输入管理员邮箱" />
                </label>

                <label class="field">
                  <span>新密码</span>
                  <input
                    v-model="pageState.adminForm.newPassword"
                    type="password"
                    autocomplete="new-password"
                    placeholder="至少 5 位"
                  />
                </label>

                <label class="field">
                  <span>确认密码</span>
                  <input
                    v-model="pageState.adminForm.confirmPassword"
                    type="password"
                    autocomplete="new-password"
                    placeholder="再次输入管理员密码"
                  />
                </label>
              </div>
            </section>

            <section class="settings-card">
              <div class="card-head">
                <div class="card-title-with-icon">
                  <div class="model-icon-box slate">
                    <i class="mdi mdi-shield-lock-outline"></i>
                  </div>
                  <div>
                    <h4>登录安全策略</h4>
                    <p>控制会话超时、登录提醒和管理员高风险操作的基础安全策略。</p>
                  </div>
                </div>
              </div>

              <div class="form-grid compact-grid">
                <label class="field">
                  <span><em>*</em> 会话超时（分钟）</span>
                  <input v-model.number="pageState.adminForm.sessionTimeout" type="number" min="5" max="240" />
                </label>

                <label class="field">
                  <span>安全通知邮箱</span>
                  <input v-model="pageState.adminForm.noticeEmail" type="email" placeholder="用于接收安全提醒" />
                </label>
              </div>

              <div class="switch-group">
                <button class="switch-row" type="button" @click="toggleBoolean('adminForm', 'mfaEnabled')">
                  <span class="switch-copy">
                    <strong>开启双因素验证</strong>
                    <small>要求管理员使用附加验证步骤登录后台。</small>
                  </span>
                  <span class="switch-btn" :class="{ active: pageState.adminForm.mfaEnabled }"><i></i></span>
                </button>

                <button class="switch-row" type="button" @click="toggleBoolean('adminForm', 'strongPassword')">
                  <span class="switch-copy">
                    <strong>启用强密码策略</strong>
                    <small>管理员密码修改时需要满足强度要求。</small>
                  </span>
                  <span class="switch-btn" :class="{ active: pageState.adminForm.strongPassword }"><i></i></span>
                </button>

                <button class="switch-row" type="button" @click="toggleBoolean('adminForm', 'loginAlertEnabled')">
                  <span class="switch-copy">
                    <strong>异常登录提醒</strong>
                    <small>检测到高风险登录时，向安全通知邮箱发送告警。</small>
                  </span>
                  <span class="switch-btn" :class="{ active: pageState.adminForm.loginAlertEnabled }"><i></i></span>
                </button>
              </div>
            </section>
          </template>

          <template v-else-if="activeSection === 'session'">
            <section class="settings-card">
              <div class="card-head">
                <div class="card-title-with-icon">
                  <div class="model-icon-box slate">
                    <i class="mdi mdi-clock-time-three-outline"></i>
                  </div>
                  <div>
                    <h4>会话保留策略</h4>
                    <p>控制智能体会话在系统中的保留时长，超过保留期的历史会话会自动清理。</p>
                  </div>
                </div>
              </div>

              <div class="form-grid compact-grid">
                <label class="field">
                  <span><em>*</em> 保留会话天数</span>
                  <div
                    ref="sessionRetentionPickerRef"
                    class="session-picker-filter"
                    :class="{ open: sessionRetentionPickerOpen }"
                  >
                    <button
                      class="session-picker-trigger"
                      type="button"
                      :aria-expanded="sessionRetentionPickerOpen"
                      aria-haspopup="dialog"
                      @click="toggleSessionRetentionPicker"
                    >
                      <span class="session-picker-label">{{ pageState.sessionForm.conversationRetentionDays }} 天</span>
                      <i class="mdi mdi-chevron-down"></i>
                    </button>

                    <div
                      v-if="sessionRetentionPickerOpen"
                      class="session-picker-popover"
                      role="dialog"
                      aria-label="选择会话保留天数"
                    >
                      <header>
                        <strong>选择会话保留天数</strong>
                        <button type="button" aria-label="关闭会话保留天数选择" @click="closeSessionRetentionPicker">
                          <i class="mdi mdi-close"></i>
                        </button>
                      </header>

                      <div class="session-picker-option-list">
                        <button
                          v-for="option in sessionRetentionOptions"
                          :key="option.value"
                          type="button"
                          class="session-picker-option"
                          :class="{ active: pageState.sessionForm.conversationRetentionDays === option.value }"
                          @click="selectSessionRetentionDays(option.value)"
                        >
                          {{ option.label }}
                        </button>
                      </div>
                    </div>
                  </div>
                  <small>最小 1 天，最大 10 天，按会话最后活跃时间计算。</small>
                </label>
              </div>
            </section>
          </template>

          <template v-else-if="activeSection === 'hermes'">
            <HermesEmployeeSettingsPanel
              :hermes-form="pageState.hermesForm"
              @toggle-master="toggleHermesMaster"
              @toggle-flag="toggleHermesFlag"
              @toggle-task="toggleHermesTask"
              @update-task-time="updateHermesTaskTime"
            />
          </template>

          <template v-else-if="activeSection === 'aiMemory'">
            <ExpenseMemorySettingsPanel />
          </template>

          <template v-else-if="activeSection === 'llm'">
            <LlmSettingsPanel :llm-form="pageState.llmForm" :provider-options="providerOptions" />
          </template>

          <template v-else-if="activeSection === 'rendering'">
            <section class="settings-card rendering-settings-card">
              <div class="card-head">
                <div class="card-title-with-icon">
                  <div class="model-icon-box slate">
                    <i class="mdi mdi-file-document-edit-outline"></i>
                  </div>
                  <div>
                    <h4>ONLYOFFICE 服务配置</h4>
                  </div>
                </div>
              </div>

              <div class="switch-group">
                <button class="switch-row" type="button" @click="toggleBoolean('renderForm', 'enabled')">
                  <span class="switch-copy">
                    <strong>启用 ONLYOFFICE 文件渲染</strong>
                    <small>启用后，知识库中的 Office 文件将优先走 ONLYOFFICE 在线预览。</small>
                  </span>
                  <span class="switch-btn" :class="{ active: pageState.renderForm.enabled }"><i></i></span>
                </button>
              </div>

              <div class="form-grid">
                <label class="field field-full">
                  <span><em>*</em> ONLYOFFICE 服务地址</span>
                  <input
                    v-model="pageState.renderForm.publicUrl"
                    type="text"
                    placeholder="例如 http://10.10.10.122:8082"
                  />
                </label>

                <label class="field field-full">
                  <span><em>*</em> JWT 密钥</span>
                  <input
                    v-model="pageState.renderForm.jwtSecret"
                    type="password"
                    autocomplete="off"
                    @focus="clearRenderSecretMask"
                    :placeholder="pageState.renderForm.jwtSecretConfigured ? '已配置，如需修改请重新输入' : '保存后不会保留在草稿中'"
                  />
                  <small v-if="pageState.renderForm.jwtSecretConfigured" class="secret-bound-state">
                    <i class="mdi mdi-database-lock"></i>
                    <span>已从数据库加密加载，预览签名会使用已保存密钥。</span>
                  </small>
                </label>
              </div>
            </section>
          </template>

          <template v-else-if="activeSection === 'logs'">
            <section class="settings-card log-policy-card">
              <div class="card-head">
                <div class="card-title-with-icon">
                  <div class="model-icon-box slate">
                    <i class="mdi mdi-text-box-search-outline"></i>
                  </div>
                  <div>
                    <h4>日志级别与留存</h4>
                    <p>定义系统记录粒度、归档周期、写入路径和告警接收人，方便后续排障追踪。</p>
                  </div>
                </div>
              </div>

              <div class="chip-row">
                <button
                  v-for="level in logLevels"
                  :key="level"
                  class="level-chip"
                  :class="{ active: pageState.logForm.level === level }"
                  type="button"
                  @click="pageState.logForm.level = level"
                >
                  {{ level }}
                </button>
              </div>

              <div class="form-grid">
                <label class="field">
                  <span><em>*</em> 留存天数</span>
                  <input v-model.number="pageState.logForm.retentionDays" type="number" min="7" />
                </label>

                <label class="field">
                  <span>归档周期</span>
                  <EnterpriseSelect
                    v-model="pageState.logForm.archiveCycle"
                    :options="archiveCycleOptions"
                    placeholder="选择归档周期"
                  />
                </label>

                <label class="field field-full">
                  <span><em>*</em> 日志路径</span>
                  <input v-model="pageState.logForm.logPath" type="text" placeholder="例如 server/logs/app.log" />
                </label>

                <label class="field field-full">
                  <span>告警邮箱</span>
                  <input v-model="pageState.logForm.alertEmail" type="email" placeholder="用于接收日志异常提醒" />
                </label>
              </div>
            </section>
          </template>

          <template v-else-if="activeSection === 'systemLogs'">
            <LogDetailView v-if="systemLogDetailMode" class="settings-log-detail-view" />
            <LogsView v-else class="settings-logs-view" />
          </template>

          <template v-else-if="activeSection === 'cacheManagement'">
            <section class="settings-card cache-management-card">
              <div class="card-head">
                <div class="card-title-with-icon">
                  <div class="model-icon-box slate">
                    <i class="mdi mdi-cached"></i>
                  </div>
                  <div>
                    <h4>应用缓存清理</h4>
                    <p>清理运行时产生的临时结果，释放进程内缓存，并让下一次识别、检索或模型调用重新构建最新状态。</p>
                  </div>
                </div>

                <div class="cache-management-hero-metrics" aria-label="缓存清理范围概览">
                  <span>
                    <strong>4 类</strong>
                    <small>清理范围</small>
                  </span>
                  <span>
                    <strong>0 项</strong>
                    <small>数据删除</small>
                  </span>
                </div>
              </div>

              <div>
                <div class="cache-safety-strip">
                  <i class="mdi mdi-shield-check-outline" aria-hidden="true"></i>
                  <span>不会删除源文件、业务单据和系统日志，只清理可重新生成的进程内缓存。</span>
                </div>
              </div>

              <div class="cache-scope-grid" aria-label="缓存清理范围">
                <article class="cache-scope-item">
                  <i class="mdi mdi-text-recognition" aria-hidden="true"></i>
                  <strong>OCR 识别结果</strong>
                  <span>清空票据识别的内存结果，下次上传或查看时重新识别。</span>
                </article>
                <article class="cache-scope-item">
                  <i class="mdi mdi-robot-outline" aria-hidden="true"></i>
                  <strong>模型失败冷却</strong>
                  <span>解除模型通道失败后的短期冷却，便于恢复后立即重试。</span>
                </article>
                <article class="cache-scope-item">
                  <i class="mdi mdi-book-search-outline" aria-hidden="true"></i>
                  <strong>知识库本地索引</strong>
                  <span>清理本地检索索引缓存，下一次检索会重新读取知识库。</span>
                </article>
                <article class="cache-scope-item">
                  <i class="mdi mdi-tune-variant" aria-hidden="true"></i>
                  <strong>运行时配置缓存</strong>
                  <span>刷新进程内配置读取结果，避免继续使用旧配置快照。</span>
                </article>
              </div>

              <div>
                <div class="cache-management-panel">
                  <div class="cache-management-copy">
                    <strong>立即执行维护清理</strong>
                    <span>建议在 OCR 配置、模型接入或知识库文件调整后使用。</span>
                  </div>
                  <button class="cache-clear-button" type="button" :disabled="cacheClearing" @click="clearAllCaches">
                    <i class="mdi" :class="cacheClearing ? 'mdi-loading mdi-spin' : 'mdi-delete-sweep-outline'"></i>
                    <span>{{ cacheClearing ? '清理中...' : '一键清理缓存' }}</span>
                  </button>
                </div>
              </div>

              <div v-if="cacheClearMessage" class="cache-clear-result" :class="{ 'is-error': cacheClearFailed }">
                <div class="cache-clear-result-head">
                  <i
                    class="mdi"
                    :class="cacheClearFailed ? 'mdi-alert-circle-outline' : 'mdi-check-circle-outline'"
                    aria-hidden="true"
                  ></i>
                  <strong>{{ cacheClearMessage }}</strong>
                </div>
                <ul v-if="cacheClearItems.length">
                  <li v-for="item in cacheClearItems" :key="item.cacheKey">
                    <span>{{ item.label }}</span>
                    <strong>{{ item.clearedCount }} 条</strong>
                  </li>
                </ul>
              </div>
              <div v-else class="cache-clear-empty">
                <i class="mdi mdi-database-clock-outline"></i>
                <span>等待执行缓存清理。</span>
              </div>
            </section>
          </template>

          <template v-else-if="activeSection === 'mail'">
            <MailSettingsPanel :mail-form="pageState.mailForm" />
          </template>
        </div>
      </div>
    </div>
  </section>
</template>

<script src="./scripts/SettingsView.js"></script>

<style scoped src="../assets/styles/views/settings-view-form.css"></style>
<style scoped src="../assets/styles/views/settings-view.css"></style>
