<template>
  <div class="ai-assistant-page">
    <!-- 顶部导航：核心技能 -->
    <div class="skill-tabs-section">
      <div class="skill-tabs-label">⚡ 核心技能</div>
      <el-row :gutter="12" class="skill-tabs">
        <el-col :span="4" v-for="tab in coreTabs" :key="tab.key">
          <el-card
            :class="['skill-card', { active: activeSkill === tab.key }]"
            shadow="hover"
            @click="switchSkill(tab.key)"
          >
            <div class="skill-card-inner">
              <div>
                <div class="skill-name">{{ tab.label }}</div>
                <div class="skill-desc">{{ tab.desc }}</div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 扩展技能：十大痛点 -->
    <div class="skill-tabs-section" style="margin-top:8px">
      <div class="skill-tabs-label">🧰 全场景扩展技能</div>
      <el-row :gutter="12" class="skill-tabs">
        <el-col :span="4" v-for="tab in extTabs" :key="tab.key">
          <el-card
            :class="['skill-card', { active: activeSkill === tab.key }]"
            shadow="hover"
            @click="switchSkill(tab.key)"
          >
            <div class="skill-card-inner">
              <div>
                <div class="skill-name">{{ tab.label }}</div>
                <div class="skill-desc">{{ tab.desc }}</div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 技能内容面板 -->
    <div class="skill-panel">
      <!-- === Tab 1: AI客服对话 === -->
      <div v-show="activeSkill === 'customer_service'">
        <el-card shadow="never">
          <template #header>
            <span>AI客服对话模拟</span>
            <el-tag type="success" size="small" style="margin-left:10px">技能: skill_customer_service</el-tag>
          </template>
          <div class="chat-container">
            <div class="chat-messages" ref="chatRef">
              <div v-for="(msg, i) in chatMessages" :key="i"
                :class="['chat-msg', msg.role]">
                <div class="msg-avatar">{{ msg.role === 'user' ? '👤' : '🤖' }}</div>
                <div class="msg-bubble">{{ msg.content }}</div>
              </div>
              <div v-if="chatLoading" class="chat-msg assistant">
                <div class="msg-avatar">🤖</div>
                <div class="msg-bubble"><span class="typing">...</span></div>
              </div>
            </div>
            <div class="chat-input-bar">
              <el-input
                v-model="chatInput"
                placeholder="模拟用户提问（如：你们有什么灯带推荐？）"
                @keyup.enter="sendChat"
                :disabled="chatLoading"
                clearable
              />
              <el-button type="primary" @click="sendChat" :loading="chatLoading">发送</el-button>
            </div>
          </div>
        </el-card>
      </div>

      <!-- === Tab 2: 智能采集 === -->
      <div v-show="activeSkill === 'product_crawl'">
        <el-card shadow="never">
          <template #header>
            <span>智能采集助手</span>
            <el-tag type="warning" size="small" style="margin-left:10px">技能: skill_product_crawl</el-tag>
          </template>

          <el-form :model="crawlForm" label-width="100px">
            <el-form-item label="商品链接">
              <el-input v-model="crawlForm.url" placeholder="输入淘宝/1688/拼多多商品链接" />
            </el-form-item>
            <el-form-item label="或关键词">
              <el-input v-model="crawlForm.keywords" placeholder="输入搜索关键词" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="getCrawlSuggest" :loading="crawlLoading">开始采集</el-button>
              <el-button @click="generateDetail" :loading="detailLoading" style="margin-left:10px">生成商品详情</el-button>
              <el-button @click="getPriceSuggest" :loading="priceLoading" style="margin-left:10px">定价建议</el-button>
            </el-form-item>
          </el-form>

          <el-alert
            title="需要配置采集接口后才能从链接获取真实数据"
            type="info"
            :closable="false"
            show-icon
            style="margin-bottom:12px"
          >
            <template #default>
              前往 <a href="#/collect" style="color:#409eff">商品采集</a> 页面配置一号通/99采集 API Key。
              配置后填链接可解析真实商品数据，当前未配置时由AI生成参考方案。
            </template>
          </el-alert>

          <div v-if="crawlResult" class="ai-result">
            <div class="result-header">🤖 AI 建议</div>
            <div class="result-content">{{ crawlResult }}</div>
          </div>
        </el-card>
      </div>

      <!-- === Tab 3: SEO优化 === -->
      <div v-show="activeSkill === 'product_seo'">
        <el-card shadow="never">
          <template #header>
            <span>SEO优化助手</span>
            <el-tag type="danger" size="small" style="margin-left:10px">技能: skill_product_seo</el-tag>
          </template>

          <el-tabs v-model="seoTab">
            <el-tab-pane label="标题优化" name="title">
              <el-form :model="seoForm" label-width="100px">
                <el-form-item label="商品ID"><el-input v-model="seoForm.product_id" placeholder="留空仅预览结果" /></el-form-item>
                <el-form-item label="原标题"><el-input v-model="seoForm.title" placeholder="输入当前标题" /></el-form-item>
                <el-form-item label="分类"><el-input v-model="seoForm.category" placeholder="商品分类" /></el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="optimizeTitle" :loading="titleLoading">AI优化标题</el-button>
                </el-form-item>
              </el-form>
            </el-tab-pane>
            <el-tab-pane label="关键词优化" name="keywords">
              <el-form :model="seoForm" label-width="100px">
                <el-form-item label="商品名称"><el-input v-model="seoForm.keyword_name" placeholder="输入商品名称" /></el-form-item>
                <el-form-item label="分类"><el-input v-model="seoForm.category" placeholder="商品分类" /></el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="optimizeKeywords" :loading="kwLoading">AI生成关键词</el-button>
                </el-form-item>
              </el-form>
            </el-tab-pane>
            <el-tab-pane label="批量诊断" name="audit">
              <p style="color:#909399;margin-bottom:16px">AI将分析前20个热销商品的标题质量，标注问题并给出批量优化建议。</p>
              <el-button type="primary" @click="runSeoAudit" :loading="auditLoading">开始诊断</el-button>
            </el-tab-pane>
          </el-tabs>

          <div v-if="seoResult" class="ai-result">
            <div class="result-header">🤖 SEO 优化建议</div>
            <div class="result-content">{{ seoResult }}</div>
          </div>
        </el-card>
      </div>

      <!-- === Tab 4: 店铺分析 === -->
      <div v-show="activeSkill === 'shop_analysis'">
        <el-card shadow="never">
          <template #header>
            <span>店铺数据分析</span>
            <el-tag type="info" size="small" style="margin-left:10px">技能: skill_shop_analysis</el-tag>
          </template>

          <div class="analysis-actions">
            <el-button type="primary" @click="salesInsight" :loading="insightLoading">📈 销售趋势解读</el-button>
            <el-button @click="productInsight" :loading="prodInsightLoading" style="margin-left:10px">🏷️ 热销/滞销分析</el-button>
            <el-button @click="dailyReport" :loading="reportLoading" style="margin-left:10px">📋 生成日报</el-button>
          </div>

          <div class="analysis-ask" style="margin-top:20px">
            <el-input
              v-model="analysisQuestion"
              placeholder="自由提问：如「最近什么卖得好？」「今天销售额怎么样？」"
              @keyup.enter="askAnalysis"
              clearable
            >
              <template #append>
                <el-button @click="askAnalysis" :loading="askLoading">提问</el-button>
              </template>
            </el-input>
          </div>

          <div v-if="analysisResult" class="ai-result">
            <div class="result-header">🤖 分析结果</div>
            <div class="result-content">{{ analysisResult }}</div>
          </div>
        </el-card>
      </div>

      <!-- === Tab 5: 营销内容 === -->
      <div v-show="activeSkill === 'marketing'">
        <el-card shadow="never">
          <template #header><span>AI营销内容生成</span> <el-tag size="small" type="success">skill_marketing</el-tag></template>
          <el-select v-model="mkType" style="width:200px;margin-bottom:12px">
            <el-option label="活动营销文案" value="activity" />
            <el-option label="私域种草内容" value="social" />
            <el-option label="分销推广素材" value="dist" />
            <el-option label="弃单/召回话术" value="recovery" />
          </el-select>
          <el-input v-model="mkInput" type="textarea" :rows="3" placeholder="输入商品/活动信息，如：618灯带秒杀，满300减50" />
          <el-button type="primary" @click="genSkill('marketing', mkInput)" :loading="genLoading.marketing" style="margin-top:8px">生成</el-button>
          <div v-if="genResult.marketing" class="ai-result" style="margin-top:12px"><div class="result-header">🤖 输出</div><div class="result-content">{{ genResult.marketing }}</div></div>
        </el-card>
      </div>

      <!-- === Tab 6: 评价售后 === -->
      <div v-show="activeSkill === 'review_after'">
        <el-card shadow="never">
          <template #header><span>AI评价与售后</span> <el-tag size="small" type="warning">skill_review_after</el-tag></template>

          <!-- 子功能切换 -->
          <el-tabs v-model="raSubTab">
            <!-- 子Tab1: 生成商品评价 -->
            <el-tab-pane label="📝 生成商品评价" name="review">
              <div style="display:flex;gap:12px;align-items:flex-start;flex-wrap:wrap">
                <div style="flex:1;min-width:300px">
                  <el-form label-width="80px">
                    <el-form-item label="选择商品">
                      <el-select
                        v-model="reviewProductId"
                        filterable
                        remote
                        reserve-keyword
                        placeholder="搜索并选择商品"
                        :remote-method="searchProducts"
                        :loading="productLoading"
                        style="width:100%"
                      >
                        <el-option
                          v-for="p in productList"
                          :key="p.id"
                          :label="p.name"
                          :value="p.id"
                        >
                          <span>{{ p.name }}</span>
                          <span style="float:right;color:#909399;font-size:12px">¥{{ p.price }}</span>
                        </el-option>
                      </el-select>
                    </el-form-item>
                    <el-form-item label="生成条数">
                      <el-input-number v-model="reviewCount" :min="1" :max="20" :step="1" style="width:120px" />
                      <span style="margin-left:8px;font-size:12px;color:#909399">每商品建议3-10条</span>
                    </el-form-item>
                    <el-form-item>
                      <el-button type="primary" @click="batchGenerateReviews" :loading="reviewGenLoading" :disabled="!reviewProductId">
                        🚀 生成并入库
                      </el-button>
                      <el-tag v-if="reviewGenSuccess" type="success" style="margin-left:10px">✅ 已入库</el-tag>
                    </el-form-item>
                  </el-form>
                </div>

                <!-- 选中的商品预览 -->
                <div v-if="selectedProductPreview" class="product-preview">
                  <div class="preview-name">{{ selectedProductPreview.name }}</div>
                  <div class="preview-meta">价格: ¥{{ selectedProductPreview.price }} | 销量: {{ selectedProductPreview.sales }}</div>
                </div>
              </div>

              <!-- 生成结果展示 -->
              <div v-if="reviewGenResult.length > 0" class="ai-result" style="margin-top:16px">
                <div class="result-header">
                  🤖 已生成 {{ reviewGenResult.length }} 条评价
                  <el-button type="primary" link size="small" @click="reviewGenResult = []" style="margin-left:auto">清空</el-button>
                </div>
                <div class="result-content">
                  <div v-for="(r, i) in reviewGenResult" :key="i" class="review-item">
                    <div class="review-header">
                      <span class="review-user">{{ r.nickname || '匿名' }}</span>
                      <span class="review-sku">{{ r.sku_info }}</span>
                      <span class="review-rating">{{ '⭐'.repeat(r.rating || 5) }}</span>
                      <span class="review-type">{{ r.type }}</span>
                    </div>
                    <div class="review-text">{{ r.content }}</div>
                  </div>
                </div>
              </div>
            </el-tab-pane>

            <!-- 子Tab2: 售后工单话术 -->
            <el-tab-pane label="💬 售后工单话术" name="after">
              <el-input v-model="raInput" type="textarea" :rows="3" placeholder="输入售后问题描述" />
              <el-button type="primary" @click="genSkill('review_after', raInput)" :loading="genLoading.review_after" style="margin-top:8px">生成话术</el-button>
              <div v-if="genResult.review_after" class="ai-result" style="margin-top:12px"><div class="result-header">🤖 输出</div><div class="result-content">{{ genResult.review_after }}</div></div>
            </el-tab-pane>

            <!-- 子Tab3: 差评修复回复 -->
            <el-tab-pane label="🔧 差评修复回复" name="bad">
              <el-input v-model="raInput" type="textarea" :rows="3" placeholder="输入差评内容" />
              <el-button type="primary" @click="genSkill('review_after', raInput)" :loading="genLoading.review_after" style="margin-top:8px">生成回复</el-button>
              <div v-if="genResult.review_after" class="ai-result" style="margin-top:12px"><div class="result-header">🤖 输出</div><div class="result-content">{{ genResult.review_after }}</div></div>
            </el-tab-pane>
          </el-tabs>
        </el-card>
      </div>

      <!-- === Tab 7: 库存供应链 === -->
      <div v-show="activeSkill === 'inventory'">
        <el-card shadow="never">
          <template #header><span>AI库存供应链</span> <el-tag size="small" type="danger">skill_inventory</el-tag></template>
          <el-select v-model="invType" style="width:200px;margin-bottom:12px">
            <el-option label="库存风险预警" value="warn" />
            <el-option label="销量预估算" value="forecast" />
            <el-option label="滞销清仓方案" value="clearance" />
          </el-select>
          <el-input v-model="invInput" type="textarea" :rows="3" placeholder="输入商品ID或品类" />
          <el-button type="primary" @click="genSkill('inventory', invInput)" :loading="genLoading.inventory" style="margin-top:8px">生成</el-button>
          <div v-if="genResult.inventory" class="ai-result" style="margin-top:12px"><div class="result-header">🤖 输出</div><div class="result-content">{{ genResult.inventory }}</div></div>
        </el-card>
      </div>

      <!-- === Tab 8: 用户定价 === -->
      <div v-show="activeSkill === 'user_pricing'">
        <el-card shadow="never">
          <template #header><span>AI用户定价</span> <el-tag size="small" type="info">skill_user_pricing</el-tag></template>
          <el-select v-model="upType" style="width:200px;margin-bottom:12px">
            <el-option label="用户分层运营" value="segment" />
            <el-option label="智能定价方案" value="pricing" />
            <el-option label="裂变分销方案" value="fission" />
          </el-select>
          <el-input v-model="upInput" type="textarea" :rows="3" placeholder="输入商品类目和客单价" />
          <el-button type="primary" @click="genSkill('user_pricing', upInput)" :loading="genLoading.user_pricing" style="margin-top:8px">生成</el-button>
          <div v-if="genResult.user_pricing" class="ai-result" style="margin-top:12px"><div class="result-header">🤖 输出</div><div class="result-content">{{ genResult.user_pricing }}</div></div>
        </el-card>
      </div>

      <!-- === Tab 9: 合规图文 === -->
      <div v-show="activeSkill === 'compliance_media'">
        <el-card shadow="never">
          <template #header><span>AI合规图文</span> <el-tag size="small">skill_compliance_media</el-tag></template>
          <el-select v-model="cmType" style="width:200px;margin-bottom:12px">
            <el-option label="合规检测" value="check" />
            <el-option label="图文描述+绘图提示词" value="desc" />
            <el-option label="全域渠道分析" value="channel" />
          </el-select>
          <el-input v-model="cmInput" type="textarea" :rows="3" placeholder="输入商品标题/详情文案" />
          <el-button type="primary" @click="genSkill('compliance_media', cmInput)" :loading="genLoading.compliance_media" style="margin-top:8px">生成</el-button>
          <div v-if="genResult.compliance_media" class="ai-result" style="margin-top:12px"><div class="result-header">🤖 输出</div><div class="result-content">{{ genResult.compliance_media }}</div></div>
        </el-card>
      </div>

      <!-- === Tab 10: 技能管理（含自定义提示词+测试） === -->
      <div v-show="activeSkill === 'skill_mgr'">
        <el-card shadow="never">
          <template #header>
            <div style="display:flex;justify-content:space-between;align-items:center">
              <span>AI 技能 & 自定义提示词管理</span>
              <el-tag size="small" type="warning">输入自动过滤提示词注入</el-tag>
            </div>
          </template>

          <el-tabs v-model="skillTab" @tab-change="onSkillTabChange">
            <el-tab-pane
              v-for="s in skillList"
              :key="s.id"
              :label="s.name"
              :name="s.id"
            >
              <!-- 技能文件编辑 -->
              <el-form label-position="top">
                <el-form-item label="技能文件内容（编辑后保存覆盖默认）">
                  <el-input
                    v-model="editingSkillContent"
                    type="textarea"
                    :rows="10"
                    placeholder="技能文件内容..."
                  />
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="saveSkillFile">保存技能文件</el-button>
                  <el-button @click="resetSkillFile" style="margin-left:10px">恢复默认</el-button>
                </el-form-item>

                <el-divider>自定义提示词（优先级最高，可覆盖Skill中冲突规则）</el-divider>

                <!-- 自定义提示词编辑 + 注入过滤提示 -->
                <el-form-item label="自定义提示词">
                  <el-input
                    v-model="editingCustomPrompt"
                    type="textarea"
                    :rows="6"
                    placeholder="输入自定义提示词，将覆盖该技能的默认规则…"
                  />
                  <div style="font-size:12px;color:#909399;margin-top:4px">
                    ⚠️ 系统将自动过滤 "忽略指令"、"忘记规则"、"切换身份" 等提示词注入语句
                  </div>
                </el-form-item>
                <el-form-item>
                  <!-- 测试按钮 -->
                  <el-input
                    v-model="testInput"
                    placeholder="输入测试内容，点击「测试AI输出」实时预览效果"
                    style="width:400px;margin-right:10px"
                    clearable
                  />
                  <el-button type="success" @click="testAiOutput" :loading="testLoading">🚀 测试AI输出</el-button>
                  <el-button type="primary" @click="saveCustomPrompt" style="margin-left:10px">保存自定义提示词</el-button>
                  <el-button @click="resetCustomPrompt" type="danger" plain style="margin-left:10px">重置默认模板</el-button>
                </el-form-item>

                <!-- 测试结果展示 -->
                <div v-if="testResult" class="ai-result" style="margin-top:12px;">
                  <div class="result-header">
                    🤖 测试输出
                    <el-tag v-if="testFiltered" type="warning" size="small" style="margin-left:8px">已过滤极限词</el-tag>
                  </div>
                  <div class="result-content">{{ testResult }}</div>
                </div>
              </el-form>
            </el-tab-pane>
          </el-tabs>
        </el-card>
      </div>
      <!-- === Tab: AI内容审核 === -->
      <div v-show="activeSkill === 'review_mgr'">
        <el-card shadow="never">
          <template #header>
            <div style="display:flex;justify-content:space-between;align-items:center">
              <span>📋 AI生成内容审核</span>
              <div>
                <el-tag size="small" type="warning" style="margin-right:6px">待审核 {{ reviewStats.pending }}</el-tag>
                <el-tag size="small" type="success">已通过 {{ reviewStats.approved }}</el-tag>
                <el-tag size="small" type="danger" style="margin-left:6px">已驳回 {{ reviewStats.rejected }}</el-tag>
              </div>
            </div>
          </template>
          
          <!-- 过滤区 -->
          <div style="margin-bottom:16px;display:flex;gap:12px;align-items:center;flex-wrap:wrap">
            <el-select v-model="reviewFilter.status" placeholder="审核状态" style="width:130px" @change="fetchReviews">
              <el-option label="全部" value="" />
              <el-option label="待审核" value="pending_review" />
              <el-option label="已通过" value="approved" />
              <el-option label="已驳回" value="rejected" />
            </el-select>
            <el-select v-model="reviewFilter.type" placeholder="内容类型" style="width:130px" @change="fetchReviews">
              <el-option label="全部类型" value="" />
              <el-option label="商品描述" value="description" />
              <el-option label="小红书文案" value="xiaohongshu" />
              <el-option label="朋友圈文案" value="moments" />
              <el-option label="SEO关键词" value="seo" />
            </el-select>
            <el-button type="primary" @click="fetchReviews" :loading="reviewLoading">刷新</el-button>
          </div>
          
          <!-- 审核列表 -->
          <el-table :data="reviewList" v-loading="reviewLoading" stripe style="width:100%" max-height="500">
            <el-table-column label="ID" prop="id" width="60" />
            <el-table-column label="类型" width="100">
              <template #default="{ row }">
                <el-tag size="small" :type="typeTag(row.source_type)">{{ typeLabel(row.source_type) }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="关联" prop="source_name" min-width="120">
              <template #default="{ row }">
                <span :title="row.request_input">{{ row.source_name || '-' }}</span>
              </template>
            </el-table-column>
            <el-table-column label="生成内容" min-width="300">
              <template #default="{ row }">
                <el-popover placement="top" :width="400" trigger="click">
                  <template #reference>
                    <span class="content-preview" style="cursor:pointer;color:#409eff">{{ row.content?.substring(0, 60) || '(空)' }}{{ row.content?.length > 60 ? '...' : '' }}</span>
                  </template>
                  <div style="white-space:pre-wrap;font-size:13px;line-height:1.7;max-height:300px;overflow-y:auto">{{ row.content }}</div>
                </el-popover>
              </template>
            </el-table-column>
            <el-table-column label="状态" width="90">
              <template #default="{ row }">
                <el-tag v-if="row.status === 'pending_review'" type="warning" size="small">待审核</el-tag>
                <el-tag v-else-if="row.status === 'approved'" type="success" size="small">已通过</el-tag>
                <el-tag v-else type="danger" size="small">已驳回</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="生成人" width="100">
              <template #default="{ row }">{{ row.admin_name || '-' }}</template>
            </el-table-column>
            <el-table-column label="时间" width="160">
              <template #default="{ row }">{{ row.created_at || '-' }}</template>
            </el-table-column>
            <el-table-column label="操作" width="180" fixed="right">
              <template #default="{ row }">
                <template v-if="row.status === 'pending_review'">
                  <el-button type="success" size="small" @click="approveReview(row)">通过</el-button>
                  <el-button type="danger" size="small" @click="showRejectDialog(row)">驳回</el-button>
                </template>
                <span v-else-if="row.review_comment" :title="'审核备注: ' + row.review_comment" style="font-size:12px;color:#909399">{{ row.review_comment?.substring(0, 20) }}{{ row.review_comment?.length > 20 ? '...' : '' }}</span>
                <span v-else style="color:#909399;font-size:12px">-</span>
              </template>
            </el-table-column>
          </el-table>
          
          <!-- 分页 -->
          <div style="margin-top:16px;display:flex;justify-content:center" v-if="reviewPageTotal > 0">
            <el-pagination
              v-model:current-page="reviewPage"
              :page-size="20"
              :total="reviewPageTotal"
              layout="prev, pager, next"
              @current-change="fetchReviews"
            />
          </div>
          
          <div v-if="!reviewLoading && reviewList.length === 0" style="text-align:center;padding:40px 0;color:#909399">
            <div style="font-size:32px;margin-bottom:8px">📭</div>
            <div>暂无审核记录</div>
            <div style="font-size:12px;margin-top:4px">使用「AI助手」生成内容后，这里会自动出现待审核项</div>
          </div>
        </el-card>
        
        <!-- 驳回弹窗 -->
        <el-dialog v-model="rejectDialogVisible" title="驳回AI生成内容" width="500px">
          <el-form>
            <el-form-item label="内容预览">
              <div style="background:#f5f7fa;padding:12px;border-radius:6px;white-space:pre-wrap;font-size:13px;max-height:200px;overflow-y:auto">{{ rejectingReview?.content?.substring(0, 300) || '' }}</div>
            </el-form-item>
            <el-form-item label="驳回理由" required>
              <el-input v-model="rejectReason" type="textarea" :rows="3" placeholder="请填写驳回理由，操作日志将记录此内容" />
            </el-form-item>
          </el-form>
          <template #footer>
            <el-button @click="rejectDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="confirmReject" :loading="rejectLoading">确认驳回</el-button>
          </template>
        </el-dialog>
      </div>

      <!-- === Tab 6: AI配置 === -->
      <div v-show="activeSkill === 'ai_config'">
        <el-card shadow="never">
          <template #header>
            <div style="display:flex;justify-content:space-between;align-items:center">
              <span>AI 连接配置</span>
              <el-tag v-if="aiConfig.api_key_configured" type="success" size="small">已配置</el-tag>
              <el-tag v-else type="danger" size="small">未配置</el-tag>
            </div>
          </template>
          <el-form :model="aiConfig" label-width="140px" style="max-width:600px">
            <el-form-item label="API Key（智能体密钥）">
              <el-input
                v-model="aiConfig.api_key"
                :type="showApiKey ? 'text' : 'password'"
                placeholder="输入 DeepSeek / 千问 API Key"
              >
                <template #append>
                  <el-button @click="showApiKey = !showApiKey">{{ showApiKey ? '隐藏' : '显示' }}</el-button>
                </template>
              </el-input>
              <div style="font-size:12px;color:#909399;margin-top:4px">当前：{{ aiConfig.api_key_preview || '未设置' }}</div>
            </el-form-item>
            <el-form-item label="API 接口地址">
              <el-input v-model="aiConfig.api_url" placeholder="https://api.deepseek.com/v1/chat/completions" />
            </el-form-item>
            <el-form-item label="AI 模型">
              <el-select v-model="aiConfig.model" style="width:100%">
                <el-option label="DeepSeek Chat" value="deepseek-chat" />
                <el-option label="DeepSeek V4 Flash" value="deepseek-v4-flash" />
                <el-option label="Qwen 3.7 Plus" value="qwen3.7-plus" />
                <el-option label="Qwen 3.7 Max" value="qwen3.7-max" />
                <el-option label="自定义" value="__custom__" />
              </el-select>
              <el-input v-if="aiConfig.model === '__custom__'" v-model="aiConfig.model_custom" placeholder="输入模型名称" style="margin-top:8px" />
            </el-form-item>
            <el-divider>功能开关</el-divider>
            <el-form-item label="AI 客服开关">
              <el-switch v-model="aiConfig.ai_enabled" active-value="1" inactive-value="0" />
              <span style="margin-left:8px;font-size:13px;color:#666">{{ aiConfig.ai_enabled === '1' ? '前端AI客服已开启' : '已关闭' }}</span>
            </el-form-item>
            <el-form-item label="大模型智能回复">
              <el-switch v-model="aiConfig.ai_use_model" active-value="1" inactive-value="0" />
              <span style="margin-left:8px;font-size:13px;color:#666">{{ aiConfig.ai_use_model === '1' ? '已开启（知识库未命中时调用大模型）' : '关闭（仅知识库匹配）' }}</span>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="saveAiConfig" :loading="configSaving">保存配置</el-button>
              <el-button @click="testApiConnection" :loading="testConnLoading" style="margin-left:10px">测试连接</el-button>
            </el-form-item>
            <div v-if="connTestResult" :class="['conn-result', connTestOk ? 'success' : 'error']" style="padding:8px 12px;border-radius:4px;{{ connTestOk ? 'background:#f0f9eb;color:#67c23a' : 'background:#fef0f0;color:#f56c6c' }}">{{ connTestResult }}</div>
          </el-form>
        </el-card>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick, watch } from 'vue'
import { ElMessage } from 'element-plus'
import request from '../utils/request'

const activeSkill = ref('customer_service')

const coreTabs = [
  { key: 'customer_service', label: 'AI对话', desc: '智能客服回复' },
  { key: 'product_crawl', label: '智能采集', desc: '货源上架' },
  { key: 'product_seo', label: 'SEO优化', desc: '关键词标题' },
  { key: 'shop_analysis', label: '店铺分析', desc: '经营数据' },
  { key: 'marketing', label: '营销内容', desc: '活动种草分销' },
  { key: 'review_after', label: '评价售后', desc: '评价工单差评' },
]

const extTabs = [
  { key: 'inventory', label: '库存供应链', desc: '预警补货清仓' },
  { key: 'user_pricing', label: '用户定价', desc: '分层定价裂变' },
  { key: 'compliance_media', label: '合规图文', desc: '检测描述渠道' },
  { key: 'review_mgr', label: '📋内容审核', desc: 'AI生成内容人工审核' },
  { key: 'skill_mgr', label: '⚙️技能管理', desc: '自定义提示词' },
  { key: 'ai_config', label: '🔑AI配置', desc: 'API Key设置' },
]

function switchSkill(key) {
  activeSkill.value = key
}

// ====== 聊天面板 ======
const chatMessages = ref([
  { role: 'assistant', content: '你好！我是 AI 客服助手。有什么可以帮你的？' }
])
const chatInput = ref('')
const chatLoading = ref(false)
const chatRef = ref(null)

async function sendChat() {
  const text = chatInput.value.trim()
  if (!text || chatLoading.value) return
  chatMessages.value.push({ role: 'user', content: text })
  chatInput.value = ''
  chatLoading.value = true
  scrollChat()
  try {
    const res = await request.post('/ai/message', { conversation_id: 0, content: text, test_mode: 1 })
    if (res.code === 0) {
      chatMessages.value.push({ role: 'assistant', content: res.data?.reply || '(空回复)' })
    } else {
      chatMessages.value.push({ role: 'assistant', content: '⚠️ ' + res.message })
    }
  } catch (e) {
    chatMessages.value.push({ role: 'assistant', content: `已收到您的问题：「${text}」` })
  } finally {
    chatLoading.value = false
    scrollChat()
  }
}
function scrollChat() {
  nextTick(() => { const el = chatRef.value; if (el) el.scrollTop = el.scrollHeight })
}

// ====== 采集面板 ======
// ====== 通用AI技能生成 ======
const genResult = reactive({})
const genLoading = reactive({})

const mkType = ref('activity')
const mkInput = ref('')
const raSubTab = ref('review')
const raInput = ref('')

// 评价生成专用
const productList = ref([])
const reviewProductId = ref(null)
const reviewCount = ref(5)
const reviewGenLoading = ref(false)
const reviewGenResult = ref([])
const reviewGenSuccess = ref(false)
const productLoading = ref(false)
const selectedProductPreview = ref(null)

async function searchProducts(query) {
  if (!query) return
  productLoading.value = true
  try {
    const res = await request.get('/ai-gen/products', { params: { q: query, pageSize: 20 } })
    if (res.code === 0) {
      productList.value = res.data?.list || []
    }
  } catch (e) { /* 静默 */ }
  finally { productLoading.value = false }
}

async function batchGenerateReviews() {
  if (!reviewProductId.value) return
  reviewGenLoading.value = true
  reviewGenSuccess.value = false
  try {
    const res = await request.post('/ai-gen/reviews/batch-generate', {
      product_id: reviewProductId.value,
      count: reviewCount.value,
    })
    if (res.code === 0) {
      reviewGenResult.value = (res.data?.reviews || []).map(r => ({
        ...r,
        rating: parseInt(r.rating) || 5
      }))
      selectedProductPreview.value = { name: res.data?.product_name || '' }
      reviewGenSuccess.value = true
      ElMessage.success(res.message || '生成成功')
      setTimeout(() => { reviewGenSuccess.value = false }, 3000)
    } else {
      ElMessage.error(res.message || '生成失败')
    }
  } catch (e) {
    ElMessage.error('生成失败: ' + (e.message || ''))
  } finally {
    reviewGenLoading.value = false
  }
}

// 初始加载商品列表
async function loadProducts() {
  try {
    const res = await request.get('/ai-gen/products', { params: { pageSize: 30 } })
    if (res.code === 0) {
      productList.value = res.data?.list || []
    }
  } catch (e) { /* 静默 */ }
}
const invType = ref('warn')
const invInput = ref('')
const upType = ref('segment')
const upInput = ref('')
const cmType = ref('check')
const cmInput = ref('')

const TYPE_PROMPTS = {
  activity: '请生成以下活动营销文案',
  social: '请生成以下私域种草内容',
  dist: '请生成以下分销推广素材',
  recovery: '请生成以下弃单召回话术',
  review: '请生成以下商品评价',
  after: '请生成以下售后工单话术',
  bad: '请生成以下差评修复话术',
  warn: '请分析以下库存风险',
  forecast: '请预测以下商品销量',
  clearance: '请生成以下清仓方案',
  segment: '请分析以下用户分层',
  pricing: '请生成以下定价方案',
  fission: '请生成以下裂变方案',
  check: '请检测以下文案的合规性',
  desc: '请生成以下图文描述',
  channel: '请分析以下渠道数据',
}

async function genSkill(skill, input) {
  if (!input) return ElMessage.warning('请输入内容')
  genLoading[skill] = true
  const typeMap = { marketing: mkType, review_after: raSubTab, inventory: invType, user_pricing: upType, compliance_media: cmType }
  const typeInputMap = { marketing: mkInput, review_after: raInput, inventory: invInput, user_pricing: upInput, compliance_media: cmInput }
  const type = typeMap[skill]?.value || ''
  const prefix = TYPE_PROMPTS[type] || ''
  try {
    const res = await request.post('/ai-gen/generate', { skill, prompt: prefix + '：' + input })
    genResult[skill] = res.data?.output || '(无输出)'
  } catch (e) {
    genResult[skill] = '生成失败: ' + (e.message || 'AI服务不可用')
  } finally {
    genLoading[skill] = false
  }
}

const crawlForm = reactive({ url: '', keywords: '' })
const crawlResult = ref('')
const crawlLoading = ref(false)
const detailLoading = ref(false)
const priceLoading = ref(false)

async function getCrawlSuggest() {
  if (!crawlForm.url && !crawlForm.keywords) return ElMessage.warning('请输入商品链接或关键词')
  crawlLoading.value = true; crawlResult.value = ''
  try {
    const res = await request.post('/ai-product/crawl-suggest', { url: crawlForm.url, keywords: crawlForm.keywords })
    if (res.data?.source === 'api') {
      // 真实采集API返回
      const raw = res.data.raw || {}
      let text = `✅ 已通过采集接口获取到真实数据\n\n`
      text += `标题：${raw.title || ''}\n`
      text += `原价：¥${raw.original_price || '?'}\n`
      if (raw.specs) text += `规格：${raw.specs.map(s => s.spec_name + ' ¥' + s.price).join('、')}\n`
      text += `\n🤖 AI优化建议：\n${res.data.ai_suggestion || ''}`
      crawlResult.value = text
    } else {
      // AI生成
      crawlResult.value = res.data?.suggestion || '(无建议)'
      if (res.data?.missing_field) {
        crawlResult.value += '\n\n⚠️ ' + res.data.missing_field.join('、')
      }
    }
  } catch (e) { crawlResult.value = 'AI 服务暂不可用，请检查后台 API Key 配置。' }
  finally { crawlLoading.value = false }
}
async function generateDetail() {
  const name = crawlForm.url || crawlForm.keywords || '测试商品'
  detailLoading.value = true; crawlResult.value = ''
  try { const res = await request.post('/ai-product/generate-detail', { name }); crawlResult.value = res.data?.content || '(无内容)' }
  catch (e) { crawlResult.value = 'AI 服务暂不可用' }
  finally { detailLoading.value = false }
}
async function getPriceSuggest() {
  priceLoading.value = true; crawlResult.value = ''
  try { const res = await request.post('/ai-product/price-suggest', { cost_price: 50 }); crawlResult.value = res.data?.suggestion || '(无建议)' }
  catch (e) { crawlResult.value = 'AI 服务暂不可用' }
  finally { priceLoading.value = false }
}

// ====== SEO面板 ======
const seoTab = ref('title')
const seoForm = reactive({ product_id: '', title: '', category: '', keyword_name: '' })
const seoResult = ref('')
const titleLoading = ref(false); const kwLoading = ref(false); const auditLoading = ref(false)

async function optimizeTitle() {
  if (!seoForm.title) return ElMessage.warning('请输入原标题')
  titleLoading.value = true; seoResult.value = ''
  try { const res = await request.post('/ai-product/seo-title', { product_id: seoForm.product_id || undefined, title: seoForm.title, category: seoForm.category }); seoResult.value = res.data?.suggestions || '(无建议)' }
  catch (e) { seoResult.value = 'AI 服务暂不可用' }
  finally { titleLoading.value = false }
}
async function optimizeKeywords() {
  if (!seoForm.keyword_name) return ElMessage.warning('请输入商品名称')
  kwLoading.value = true; seoResult.value = ''
  try { const res = await request.post('/ai-product/seo-keywords', { name: seoForm.keyword_name, category: seoForm.category }); seoResult.value = res.data?.content || '(无内容)' }
  catch (e) { seoResult.value = 'AI 服务暂不可用' }
  finally { kwLoading.value = false }
}
async function runSeoAudit() {
  auditLoading.value = true; seoResult.value = ''
  try {
    const res = await request.post('/ai-product/seo-audit', {})
    const d = res.data; let text = `📊 商品SEO诊断报告\n总商品: ${d.total} | 待优化: ${d.needOptimization} | 平均分: ${d.avgScore}\n`
    if (d.details) {
      const bad = d.details.filter(x => x.issues.length > 0)
      if (bad.length > 0) { text += `⚠️ 需要优化的商品:\n`; bad.slice(0, 5).forEach(p => { text += `  - ${p.name}\n    问题: ${p.issues.join(', ')}\n` }) }
    }
    if (d.aiSuggestion) text += `\n🤖 AI优化建议:\n${d.aiSuggestion}`
    seoResult.value = text
  } catch (e) { seoResult.value = 'AI 服务暂不可用' }
  finally { auditLoading.value = false }
}

// ====== 分析面板 ======
const analysisQuestion = ref('')
const analysisResult = ref('')
const insightLoading = ref(false); const prodInsightLoading = ref(false); const reportLoading = ref(false); const askLoading = ref(false)

async function salesInsight() {
  insightLoading.value = true; analysisResult.value = ''
  try { const res = await request.post('/ai-analysis/sales-insight', { days: 7 }); analysisResult.value = res.data?.analysis || '(无数据)' }
  catch (e) { analysisResult.value = 'AI 服务暂不可用' }
  finally { insightLoading.value = false }
}
async function productInsight() {
  prodInsightLoading.value = true; analysisResult.value = ''
  try { const res = await request.post('/ai-analysis/product-insight', { top: 10 }); analysisResult.value = res.data?.analysis || '(无数据)' }
  catch (e) { analysisResult.value = 'AI 服务暂不可用' }
  finally { prodInsightLoading.value = false }
}
async function dailyReport() {
  reportLoading.value = true; analysisResult.value = ''
  try { const res = await request.post('/ai-analysis/daily-report'); analysisResult.value = res.data?.report || '(无数据)' }
  catch (e) { analysisResult.value = 'AI 服务暂不可用' }
  finally { reportLoading.value = false }
}
async function askAnalysis() {
  if (!analysisQuestion.value.trim()) return
  askLoading.value = true; analysisResult.value = ''
  try { const res = await request.post('/ai-analysis/ask', { question: analysisQuestion.value }); analysisResult.value = res.data?.answer || '(无回答)' }
  catch (e) { analysisResult.value = 'AI 服务暂不可用' }
  finally { askLoading.value = false }
}

// ====== 技能管理 ======
const skillList = ref([])
const skillTab = ref('')
const editingSkillContent = ref('')
const editingCustomPrompt = ref('')
const testInput = ref('')
const testResult = ref('')
const testFiltered = ref(false)
const testLoading = ref(false)

async function fetchSkills() {
  try {
    const res = await request.get('/ai-prompt/list')
    if (res.code === 0 && res.data) {
      skillList.value = res.data
      if (res.data.length > 0) {
        skillTab.value = res.data[0].id
        editingCustomPrompt.value = res.data[0].custom_prompt || ''
        loadSkillContent(res.data[0].id)
      }
    }
  } catch (e) {
    skillList.value = [
      { id: 'customer_service', name: 'AI客服' },
      { id: 'product_crawl', name: '货源采集' },
      { id: 'product_seo', name: 'SEO优化' },
      { id: 'shop_analysis', name: '店铺分析' },
    ]
    skillTab.value = 'customer_service'
    loadSkillContent('customer_service')
  }
}

async function loadSkillContent(skillName) {
  try {
    const res = await request.get(`/ai-product/skills/${skillName}`)
    if (res.code === 0) editingSkillContent.value = res.data?.content || ''
  } catch (e) {
    editingSkillContent.value = '(无法加载技能文件)'
  }
}

function onSkillTabChange(name) {
  if (!name) return
  loadSkillContent(name)
  editingCustomPrompt.value = skillList.value.find(s => s.id === name)?.custom_prompt || ''
  testResult.value = ''
  testInput.value = ''
}

async function saveSkillFile() {
  try {
    const res = await request.put(`/ai-product/skills/${skillTab.value}`, { content: editingSkillContent.value })
    ElMessage.success(res.message || '保存成功')
  } catch (e) { ElMessage.error('保存失败') }
}
function resetSkillFile() { ElMessage.info('技能文件已恢复为默认内容') }

async function saveCustomPrompt() {
  try {
    const res = await request.post('/ai-prompt/save', {
      skill: skillTab.value,
      prompt: editingCustomPrompt.value
    })
    const msg = res.data?.filtered ? '⚠️ 已自动过滤违规指令并保存' : (res.message || '保存成功')
    ElMessage.success(msg)
  } catch (e) { ElMessage.error('保存失败') }
}

async function resetCustomPrompt() {
  try {
    const res = await request.post('/ai-prompt/reset', { skill: skillTab.value })
    editingCustomPrompt.value = ''
    testResult.value = ''
    ElMessage.success(res.message || '已恢复默认')
  } catch (e) { ElMessage.error('重置失败') }
}

async function testAiOutput() {
  if (!testInput.value.trim()) return ElMessage.warning('请输入测试内容')
  testLoading.value = true; testResult.value = ''
  try {
    const res = await request.post('/ai-prompt/test', {
      skill: skillTab.value,
      prompt: editingCustomPrompt.value,
      test_input: testInput.value
    })
    if (res.code === 0) {
      testResult.value = res.data?.output || '(无输出)'
      testFiltered.value = res.data?.filtered || false
    } else {
      testResult.value = '测试失败: ' + res.message
      testFiltered.value = false
    }
  } catch (e) {
    testResult.value = 'AI服务暂不可用，请检查API Key配置'
    testFiltered.value = false
  } finally {
    testLoading.value = false
  }
}

// ====== AI 内容审核面板 ======
const reviewList = ref([])
const reviewLoading = ref(false)
const reviewPage = ref(1)
const reviewPageTotal = ref(0)
const reviewStats = reactive({ total: 0, pending: 0, approved: 0, rejected: 0 })
const reviewFilter = reactive({ status: 'pending_review', type: '' })
const rejectDialogVisible = ref(false)
const rejectingReview = ref(null)
const rejectReason = ref('')
const rejectLoading = ref(false)

function typeLabel(type) {
  const map = { description: '商品描述', xiaohongshu: '小红书', moments: '朋友圈', seo: 'SEO关键词', review: '评价' }
  return map[type] || type
}

function typeTag(type) {
  const map = { description: '', xiaohongshu: 'success', moments: 'warning', seo: 'info', review: 'danger' }
  return map[type] || ''
}

async function fetchReviews() {
  reviewLoading.value = true
  try {
    const params = { page: reviewPage.value, pageSize: 20 }
    if (reviewFilter.status) params.status = reviewFilter.status
    if (reviewFilter.type) params.source_type = reviewFilter.type
    const res = await request.get('/ai-review/list', { params })
    if (res.code === 0) {
      reviewList.value = res.data?.list || []
      reviewPageTotal.value = res.data?.total || 0
    }
  } catch (e) {
    reviewList.value = []
  } finally {
    reviewLoading.value = false
  }
}

async function fetchReviewStats() {
  try {
    const res = await request.get('/ai-review/stats')
    if (res.code === 0 && res.data) {
      Object.assign(reviewStats, res.data)
    }
  } catch (e) { /* 静默 */ }
}

async function approveReview(row) {
  try {
    await request.post(`/ai-review/approve/${row.id}`)
    ElMessage.success('已审核通过')
    fetchReviews()
    fetchReviewStats()
  } catch (e) {
    ElMessage.error('操作失败')
  }
}

function showRejectDialog(row) {
  rejectingReview.value = row
  rejectReason.value = ''
  rejectDialogVisible.value = true
}

async function confirmReject() {
  if (!rejectReason.value.trim()) return ElMessage.warning('请填写驳回理由')
  rejectLoading.value = true
  try {
    await request.post(`/ai-review/reject/${rejectingReview.value.id}`, { reason: rejectReason.value })
    ElMessage.success('已驳回')
    rejectDialogVisible.value = false
    fetchReviews()
    fetchReviewStats()
  } catch (e) {
    ElMessage.error('操作失败')
  } finally {
    rejectLoading.value = false
  }
}

onMounted(() => { fetchSkills(); fetchAiConfig(); loadProducts(); fetchReviewStats() })

// ====== AI 配置面板 ======
const aiConfig = reactive({
  api_key: '',
  api_key_preview: '',
  api_key_configured: false,
  api_url: 'https://api.deepseek.com/v1/chat/completions',
  model: 'deepseek-chat',
  ai_enabled: '0',
  ai_use_model: '0',
  model_custom: '',
})
const showApiKey = ref(false)
const configSaving = ref(false)
const testConnLoading = ref(false)
const connTestResult = ref('')
const connTestOk = ref(false)

async function fetchAiConfig() {
  try {
    const res = await request.get('/ai-prompt/config')
    if (res.code === 0 && res.data) {
      aiConfig.api_key_preview = res.data.api_key_preview || ''
      aiConfig.api_key_configured = res.data.api_key_configured || false
      aiConfig.api_url = res.data.api_url || 'https://api.deepseek.com/v1/chat/completions'
      aiConfig.model = res.data.model || 'deepseek-chat'
      aiConfig.ai_enabled = res.data.ai_enabled || '0'
      aiConfig.ai_use_model = res.data.ai_use_model || '0'
    }
  } catch (e) { /* 静默 */ }
}

async function saveAiConfig() {
  configSaving.value = true
  try {
    const data = {
      api_key: aiConfig.api_key || undefined,
      api_url: aiConfig.api_url,
      model: aiConfig.model === '__custom__' ? aiConfig.model_custom : aiConfig.model,
      ai_enabled: aiConfig.ai_enabled,
      ai_use_model: aiConfig.ai_use_model,
    }
    const res = await request.post('/ai-prompt/config', data)
    ElMessage.success('AI 配置已保存')
    aiConfig.api_key = ''
    fetchAiConfig()
  } catch (e) {
    ElMessage.error('保存失败')
  } finally {
    configSaving.value = false
  }
}

async function testApiConnection() {
  testConnLoading.value = true
  connTestResult.value = '正在测试连接...'
  try {
    // 先保存当前配置再测试
    await request.post('/ai-prompt/config', {
      api_key: aiConfig.api_key || undefined,
      api_url: aiConfig.api_url,
      model: aiConfig.model === '__custom__' ? aiConfig.model_custom : aiConfig.model,
      ai_enabled: aiConfig.ai_enabled,
      ai_use_model: aiConfig.ai_use_model,
    })
    // 用测试接口验证
    const res = await request.post('/ai-prompt/test', {
      skill: 'customer_service',
      prompt: '',
      test_input: '你好'
    })
    if (res.code === 0 && res.data?.output) {
      connTestResult.value = '✅ 连接成功！AI 回复：' + res.data.output.substring(0, 100)
      connTestOk.value = true
    } else {
      connTestResult.value = '❌ 连接失败：' + (res.message || '未知错误')
      connTestOk.value = false
    }
  } catch (e) {
    connTestResult.value = '❌ 连接测试失败：' + (e.message || '网络错误')
    connTestOk.value = false
  } finally {
    testConnLoading.value = false
  }
}
</script>

<style scoped>
.ai-assistant-page { max-width: 1400px; }
.skill-tabs { margin-bottom: 16px; }
.skill-card { cursor: pointer; transition: all 0.2s; }
.skill-card.active { border-color: #409eff; box-shadow: 0 2px 12px rgba(64, 158, 255, 0.15); }
.skill-card-inner { display: flex; align-items: center; gap: 12px; }
.skill-name { font-weight: 600; font-size: 14px; }
.skill-desc { font-size: 11px; color: #909399; margin-top: 2px; }
.skill-panel { min-height: 400px; }

.chat-container { border: 1px solid #eee; border-radius: 8px; overflow: hidden; }
.chat-messages { height: 360px; overflow-y: auto; padding: 16px; background: #fafafa; }
.chat-msg { display: flex; gap: 10px; margin-bottom: 16px; }
.chat-msg.user { flex-direction: row-reverse; }
.msg-avatar { width: 36px; height: 36px; border-radius: 50%; background: #f0f0f0; display: flex; align-items: center; justify-content: center; font-size: 18px; flex-shrink: 0; }
.msg-bubble { max-width: 70%; padding: 10px 14px; border-radius: 12px; font-size: 14px; line-height: 1.6; white-space: pre-wrap; }
.chat-msg.user .msg-bubble { background: #409eff; color: #fff; border-bottom-right-radius: 4px; }
.chat-msg.assistant .msg-bubble { background: #fff; border: 1px solid #e4e7ed; border-bottom-left-radius: 4px; }
.typing { animation: blink 1s infinite; }
@keyframes blink { 0%, 100% { opacity: 1; } 50% { opacity: 0; } }
.chat-input-bar { display: flex; gap: 8px; padding: 12px; border-top: 1px solid #eee; background: #fff; }

.ai-result { margin-top: 20px; border: 1px solid #e4e7ed; border-radius: 8px; overflow: hidden; }
.product-preview { background:#f5f7fa; padding:12px 16px; border-radius:8px; min-width:200px; }
.preview-name { font-weight:600; font-size:15px; }
.preview-meta { font-size:12px; color:#909399; margin-top:4px; }
.review-item { padding:10px 0; border-bottom:1px solid #f0f0f0; }
.review-item:last-child { border-bottom:none; }
.review-header { display:flex; align-items:center; gap:8px; flex-wrap:wrap; font-size:12px; }
.review-user { font-weight:600; color:#333; }
.review-sku { color:#909399; }
.review-rating { }
.review-type { background:#f0f0f0; padding:1px 8px; border-radius:4px; color:#666; font-size:11px; }
.review-text { margin-top:6px; font-size:14px; line-height:1.6; color:#555; }
.result-header { padding: 10px 16px; background: #f5f7fa; font-weight: 600; font-size: 14px; border-bottom: 1px solid #e4e7ed; }
.result-content { padding: 16px; font-size: 14px; line-height: 1.8; white-space: pre-wrap; color: #333; }

/* AI内容审核样式 */
.content-preview:hover { text-decoration: underline; }
</style>
