<template>
  <div class="marketing-page">
    <div class="marketing-header">
      <div class="header-left">
        <div class="data-title">📧 自动营销</div>
        <p class="header-desc">多渠道自动化营销，AI 智能生成个性化内容</p>
      </div>
      <div class="header-actions">
        <button class="btn btn-secondary" @click="showHistoryModal = true">
          <i class="fas fa-history"></i> 历史活动
        </button>
        <button class="btn btn-secondary" @click="showTemplatesModal = true">
          <i class="fas fa-file-alt"></i> 模板库
        </button>
        <button class="btn btn-primary" @click="openCreateModal">
          <i class="fas fa-plus"></i> 创建营销活动
        </button>
      </div>
    </div>

    <!-- Stats -->
    <div class="stats-row">
      <div class="stat-card-lg">
        <div class="stat-icon-lg blue"><i class="fas fa-paper-plane"></i></div>
        <div class="stat-content-lg">
          <h3>{{ formatNumber(marketingStats.totalSent) }}</h3>
          <p>本月发送</p>
        </div>
      </div>
      <div class="stat-card-lg">
        <div class="stat-icon-lg green"><i class="fas fa-envelope-open"></i></div>
        <div class="stat-content-lg">
          <h3>{{ marketingStats.openRate }}%</h3>
          <p>平均打开率</p>
        </div>
      </div>
      <div class="stat-card-lg">
        <div class="stat-icon-lg purple"><i class="fas fa-mouse-pointer"></i></div>
        <div class="stat-content-lg">
          <h3>{{ marketingStats.clickRate }}%</h3>
          <p>点击率</p>
        </div>
      </div>
      <div class="stat-card-lg">
        <div class="stat-icon-lg orange"><i class="fas fa-reply"></i></div>
        <div class="stat-content-lg">
          <h3>{{ marketingStats.replyRate }}%</h3>
          <p>回复率</p>
        </div>
      </div>
      <div class="stat-card-lg">
        <div class="stat-icon-lg success"><i class="fas fa-shield-alt"></i></div>
        <div class="stat-content-lg">
          <h3>{{ marketingStats.protectedCustomers }}</h3>
          <p>受保护客户</p>
        </div>
      </div>
      <div class="stat-card-lg">
        <div class="stat-icon-lg warning"><i class="fas fa-exclamation-circle"></i></div>
        <div class="stat-content-lg">
          <h3>{{ marketingStats.pendingReview }}</h3>
          <p>待审核</p>
        </div>
      </div>
    </div>

    <!-- Tabs -->
    <div class="tabs-row">
      <div class="tabs">
        <div v-for="tab in tabs" :key="tab.key" 
             class="tab-item" :class="{ active: filterTab === tab.key }"
             @click="filterTab = tab.key">
          {{ tab.label }}
          <span class="tab-count">{{ tab.count }}</span>
        </div>
      </div>
    </div>

    <!-- Campaigns Grid -->
    <div class="campaigns-grid">
      <div v-for="campaign in filteredCampaigns" :key="campaign.id" 
           class="campaign-card" @click="showCampaignDetail(campaign)">
        <div class="card-header">
          <div class="card-icon" :style="{ background: campaign.iconBg }">
            <i :class="campaign.icon" :style="{ color: campaign.iconColor }"></i>
          </div>
          <span class="status-badge" :class="campaign.status">{{ getStatusLabel(campaign.status) }}</span>
        </div>
        <div class="card-title">{{ campaign.name }}</div>
        <div class="card-desc">{{ campaign.description }}</div>
        <div class="card-channels">
          <span v-for="ch in campaign.channels" :key="ch" class="channel-tag">
            <i :class="getChannelIcon(ch)"></i> {{ ch }}
          </span>
        </div>
        <div class="card-stats">
          <div class="stat-item">
            <span class="stat-value">{{ formatNumber(campaign.stats.sent) }}</span>
            <span class="stat-label">已发送</span>
          </div>
          <div class="stat-item">
            <span class="stat-value success">{{ campaign.stats.openRate }}%</span>
            <span class="stat-label">打开率</span>
          </div>
          <div class="stat-item">
            <span class="stat-value primary">{{ campaign.stats.replyRate }}%</span>
            <span class="stat-label">回复率</span>
          </div>
        </div>
        <div class="card-progress">
          <div class="progress-header">
            <span>进度</span>
            <span>{{ campaign.progress }}%</span>
          </div>
          <div class="progress-bar">
            <div class="progress-fill" :style="{ width: campaign.progress + '%' }"></div>
          </div>
        </div>
        <div class="card-actions" @click.stop>
          <button class="btn btn-secondary btn-sm" @click.stop="openOpenedCustomers(campaign)" :title="`打开邮件: ${campaign.openedCustomers}个客户`">
            <i class="fas fa-envelope-open"></i> {{ campaign.openedCustomers }}
          </button>
          <button class="btn btn-secondary btn-sm" @click.stop="openReplyReview(campaign)" :title="`回复邮件: ${campaign.repliedCustomers}个客户`">
            <i class="fas fa-reply"></i> {{ campaign.repliedCustomers }}
          </button>
          <button class="btn btn-secondary btn-sm" @click="openInterventionModal(campaign)" title="人工干预">
            <i class="fas fa-hand-paper"></i>
          </button>
          <button class="btn btn-primary btn-sm" @click="openAIGenerator(campaign)">
            <i class="fas fa-magic"></i> AI生成
          </button>
        </div>
      </div>
    </div>

    <!-- Campaign Detail Modal -->
    <div v-if="showCampaignDetailModal" class="modal-overlay" @click.self="showCampaignDetailModal = false">
      <div class="modal campaign-detail-modal">
        <div class="modal-header">
          <div class="modal-title">
            <i class="fas fa-chart-bar"></i> 活动详情
            <span class="detail-status" :class="selectedCampaign?.status">{{ getStatusLabel(selectedCampaign?.status) }}</span>
          </div>
          <button class="modal-close" @click="showCampaignDetailModal = false"><i class="fas fa-times"></i></button>
        </div>
        <div class="modal-body" v-if="selectedCampaign">
          <!-- 基本信息 -->
          <div class="detail-section">
            <div class="section-header">
              <h4><i class="fas fa-info-circle"></i> 基本信息</h4>
            </div>
            <div class="detail-grid">
              <div class="detail-item">
                <label>活动名称</label>
                <span>{{ selectedCampaign.name }}</span>
              </div>
              <div class="detail-item">
                <label>活动类型</label>
                <span>{{ selectedCampaign.type || '潜客开发' }}</span>
              </div>
              <div class="detail-item">
                <label>优先级</label>
                <span class="priority-badge" :class="selectedCampaign.priority || 'medium'">{{ getPriorityLabel(selectedCampaign.priority || 'medium') }}</span>
              </div>
              <div class="detail-item">
                <label>负责人</label>
                <span>{{ selectedCampaign.owner || '张经理' }}</span>
              </div>
              <div class="detail-item">
                <label>创建时间</label>
                <span>{{ selectedCampaign.createdAt || '2026-03-15 10:30' }}</span>
              </div>
              <div class="detail-item">
                <label>活动周期</label>
                <span>{{ selectedCampaign.dateRange || '2026-03-15 至 2026-04-15' }}</span>
              </div>
              <div class="detail-item full-width">
                <label>活动描述</label>
                <span>{{ selectedCampaign.description }}</span>
              </div>
            </div>
          </div>

          <!-- 核心数据 -->
          <div class="detail-section">
            <div class="section-header">
              <h4><i class="fas fa-chart-line"></i> 核心数据</h4>
              <div class="progress-info">达成 {{ selectedCampaign.progress }}%</div>
            </div>
            <div class="detail-progress-bar">
              <div class="progress-fill" :style="{ width: selectedCampaign.progress + '%' }"></div>
            </div>
            <div class="metrics-grid">
              <div class="metric-card">
                <div class="metric-icon blue"><i class="fas fa-paper-plane"></i></div>
                <div class="metric-content">
                  <div class="metric-value">{{ formatNumber(selectedCampaign.stats.sent) }}</div>
                  <div class="metric-label">已发送</div>
                </div>
              </div>
              <div class="metric-card">
                <div class="metric-icon green"><i class="fas fa-envelope-open"></i></div>
                <div class="metric-content">
                  <div class="metric-value">{{ Math.round(selectedCampaign.stats.sent * selectedCampaign.stats.openRate / 100) }}</div>
                  <div class="metric-label">打开数 ({{ selectedCampaign.stats.openRate }}%)</div>
                </div>
              </div>
              <div class="metric-card">
                <div class="metric-icon purple"><i class="fas fa-reply"></i></div>
                <div class="metric-content">
                  <div class="metric-value">{{ Math.round(selectedCampaign.stats.sent * selectedCampaign.stats.replyRate / 100) }}</div>
                  <div class="metric-label">回复数 ({{ selectedCampaign.stats.replyRate }}%)</div>
                </div>
              </div>
            </div>
          </div>

          <!-- 触达渠道 -->
          <div class="detail-section">
            <div class="section-header">
              <h4><i class="fas fa-bullhorn"></i> 触达渠道</h4>
            </div>
            <div class="channel-detail-list">
              <div v-for="ch in selectedCampaign.channels.filter(ch => ch !== 'WhatsApp' && ch !== 'LinkedIn')" :key="ch" class="channel-detail-item">
                <div class="channel-icon-wrapper" :style="getChannelStyleByName(ch)">
                  <i :class="getChannelIcon(ch)"></i>
                </div>
                <div class="channel-detail-info">
                  <div class="channel-detail-name">{{ ch }}</div>
                  <div class="channel-detail-stats">
                    <span>发送: {{ Math.round(selectedCampaign.stats.sent / selectedCampaign.channels.length) }}</span>
                    <span>打开率: {{ selectedCampaign.stats.openRate }}%</span>
                    <span>回复率: {{ selectedCampaign.stats.replyRate }}%</span>
                  </div>
                </div>
                <div class="channel-status">
                  <span class="status-dot active"></span> 运行中
                </div>
              </div>
            </div>
          </div>

          <!-- 目标客户 -->
          <div class="detail-section">
            <div class="section-header">
              <h4><i class="fas fa-users"></i> 目标客户</h4>
            </div>
            <div class="target-info">
              <div class="target-stat">
                <div class="target-value">{{ selectedCampaign.targetCount || 847 }}</div>
                <div class="target-label">目标客户数</div>
              </div>
              <div class="target-stat">
                <div class="target-value">{{ selectedCampaign.reachedCount || 623 }}</div>
                <div class="target-label">已触达</div>
              </div>
              <div class="target-stat">
                <div class="target-value">{{ selectedCampaign.pendingCount || 224 }}</div>
                <div class="target-label">待触达</div>
              </div>
            </div>
          </div>

          <!-- SOP 序列 -->
          <div class="detail-section">
            <div class="section-header">
              <h4><i class="fas fa-robot"></i> SOP 自动化序列</h4>
            </div>
            <div class="sop-detail">
              <div class="sop-header-info">
                <span class="sop-name">{{ selectedCampaign.sopTemplate || '标准开发序列' }}</span>
                <span class="sop-steps">4 步序列</span>
              </div>
              <div class="sop-timeline-detail">
                <div class="sop-step-item completed">
                  <div class="step-marker"><i class="fas fa-check"></i></div>
                  <div class="step-content">
                    <div class="step-title">首封介绍邮件</div>
                    <div class="step-meta">第1天 · 邮件 · 已完成</div>
                  </div>
                </div>
                <div class="sop-step-item completed">
                  <div class="step-marker"><i class="fas fa-check"></i></div>
                  <div class="step-content">
                    <div class="step-title">产品优势介绍</div>
                    <div class="step-meta">第3天 · 邮件 · 已完成</div>
                  </div>
                </div>
                <div class="sop-step-item current">
                  <div class="step-marker">3</div>
                  <div class="step-content">
                    <div class="step-title">案例分享</div>
                    <div class="step-meta">第7天 · LinkedIn · 进行中</div>
                  </div>
                </div>
                <div class="sop-step-item pending">
                  <div class="step-marker">4</div>
                  <div class="step-content">
                    <div class="step-title">电话跟进</div>
                    <div class="step-meta">第14天 · 电话 · 待执行</div>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <!-- 最近互动 -->
          <div class="detail-section">
            <div class="section-header">
              <h4><i class="fas fa-comments"></i> 最近互动</h4>
              <button class="btn-link" @click="showAllInteractions">查看全部</button>
            </div>
            <div class="interactions-list">
              <div class="interaction-item">
                <div class="interaction-avatar">M</div>
                <div class="interaction-content">
                  <div class="interaction-header">
                    <span class="interaction-name">Mohammed Al-Rashid</span>
                    <span class="interaction-time">10分钟前</span>
                  </div>
                  <div class="interaction-text">回复了您的邮件，询问价格和交期</div>
                  <div class="interaction-tags">
                    <span class="tag reply">回复</span>
                    <span class="tag interested">高意向</span>
                  </div>
                </div>
              </div>
              <div class="interaction-item">
                <div class="interaction-avatar">A</div>
                <div class="interaction-content">
                  <div class="interaction-header">
                    <span class="interaction-name">Ahmed Hassan</span>
                    <span class="interaction-time">1小时前</span>
                  </div>
                  <div class="interaction-text">打开了您的邮件</div>
                  <div class="interaction-tags">
                    <span class="tag open">打开</span>
                  </div>
                </div>
              </div>
              <div class="interaction-item">
                <div class="interaction-avatar">S</div>
                <div class="interaction-content">
                  <div class="interaction-header">
                    <span class="interaction-name">Sarah Williams</span>
                    <span class="interaction-time">3小时前</span>
                  </div>
                  <div class="interaction-text">点击了邮件中的产品链接</div>
                  <div class="interaction-tags">
                    <span class="tag click">点击</span>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div class="modal-footer">
          <button class="btn btn-secondary" @click="duplicateCampaign(selectedCampaign)">
            <i class="fas fa-copy"></i> 复制活动
          </button>
          <button class="btn btn-secondary" @click="exportCampaignReport(selectedCampaign)">
            <i class="fas fa-download"></i> 导出报告
          </button>
          <button class="btn btn-secondary" @click="showCampaignDetailModal = false">关闭</button>
          <button class="btn btn-primary" @click="editCampaign(selectedCampaign)">
            <i class="fas fa-edit"></i> 编辑活动
          </button>
        </div>
      </div>
    </div>

    <!-- All Interactions Modal -->
    <div v-if="showInteractionsModal" class="modal-overlay" @click.self="showInteractionsModal = false">
      <div class="modal interactions-detail-modal">
        <div class="modal-header">
          <div class="modal-title">
            <i class="fas fa-comments"></i> 互动详情 - {{ selectedCampaign?.name }}
            <span class="interaction-count">{{ selectedCampaignInteractions.length }}条记录</span>
          </div>
          <button class="modal-close" @click="showInteractionsModal = false"><i class="fas fa-times"></i></button>
        </div>
        <div class="modal-body">
          <!-- 筛选 -->
          <div class="interactions-filters">
            <button class="filter-btn active">全部</button>
            <button class="filter-btn"><i class="fas fa-reply"></i> 回复</button>
            <button class="filter-btn"><i class="fas fa-envelope-open"></i> 打开</button>
            <button class="filter-btn"><i class="fas fa-mouse-pointer"></i> 点击</button>
          </div>

          <!-- 互动列表 -->
          <div class="all-interactions-list">
            <div v-for="item in selectedCampaignInteractions" :key="item.id" class="interaction-detail-item">
              <div class="interaction-detail-avatar" :class="item.type">{{ item.avatar }}</div>
              <div class="interaction-detail-content">
                <div class="interaction-detail-header">
                  <div class="interaction-detail-info">
                    <span class="interaction-detail-name">{{ item.name }}</span>
                    <span class="interaction-detail-company">{{ item.company }}</span>
                  </div>
                  <div class="interaction-detail-time">{{ item.time }}</div>
                </div>
                <div class="interaction-detail-action">
                  <span class="action-badge" :class="item.type">
                    <i :class="{
                      'reply': 'fas fa-reply',
                      'open': 'fas fa-envelope-open',
                      'click': 'fas fa-mouse-pointer'
                    }[item.type]"></i>
                    {{ item.action }}
                  </span>
                  <span class="sentiment-badge" :class="item.sentiment">{{ item.sentiment }}</span>
                  <span class="priority-badge" :class="item.priority">{{ item.priority }}优先级</span>
                </div>
                <div class="interaction-detail-text">{{ item.content }}</div>
                <div class="interaction-detail-contact">
                  <span><i class="fas fa-envelope"></i> {{ item.email }}</span>
                  <span><i class="fas fa-phone"></i> {{ item.phone }}</span>
                </div>
              </div>
              <div class="interaction-detail-actions">
                <button class="btn btn-sm btn-primary" v-if="item.interested">
                  <i class="fas fa-user-plus"></i> 立即跟进
                </button>
                <button class="btn btn-sm btn-secondary">
                  <i class="fas fa-envelope"></i> 发邮件
                </button>
              </div>
            </div>
          </div>
        </div>
        <div class="modal-footer">
          <button class="btn btn-secondary" @click="showInteractionsModal = false">关闭</button>
        </div>
      </div>
    </div>

    <!-- Create Campaign Modal -->
    <AddMarketing ref="addMarketingRef" />

    <!-- AI Email Generator Modal -->
    <div v-if="showAIModal" class="modal-overlay" @click.self="showAIModal = false">
      <div class="modal ai-modal">
        <div class="modal-header">
          <div class="modal-title"><i class="fas fa-magic"></i> AI 邮件生成器</div>
          <button class="modal-close" @click="showAIModal = false"><i class="fas fa-times"></i></button>
        </div>
        <div class="modal-body">
          <div class="ai-generator">
            <div class="generator-input">
              <h4>输入要求</h4>
              <div class="form-group">
                <label class="form-label">邮件类型</label>
                <select class="form-select" v-model="aiGenerator.type">
                  <option value="introduction">首次介绍信</option>
                  <option value="followup">跟进邮件</option>
                  <option value="product">产品推荐</option>
                  <option value="offer">报价邮件</option>
                </select>
              </div>
              <div class="form-group">
                <label class="form-label">产品/服务</label>
                <select class="form-select" v-model="aiGenerator.product">
                  <option value="ssd">固态硬盘 SSD</option>
                  <option value="hdd">机械硬盘 HDD</option>
                  <option value="memory">内存条</option>
                  <option value="storage">存储方案</option>
                </select>
              </div>
              <div class="form-group">
                <label class="form-label">核心卖点</label>
                <div class="checkbox-grid">
                  <label v-for="point in sellingPoints" :key="point.id" class="checkbox-item">
                    <input type="checkbox" v-model="aiGenerator.selectedPoints" :value="point.id">
                    <span>{{ point.label }}</span>
                  </label>
                </div>
              </div>
              <div class="form-group">
                <label class="form-label">语气风格</label>
                <div class="tone-options">
                  <span v-for="tone in toneOptions" :key="tone.value"
                        class="tone-option" :class="{ active: aiGenerator.tone === tone.value }"
                        @click="aiGenerator.tone = tone.value">{{ tone.label }}</span>
                </div>
              </div>
              <div class="form-group">
                <label class="form-label">语言</label>
                <div class="language-options">
                  <span v-for="lang in languageOptions" :key="lang.value"
                        class="language-option" :class="{ active: aiGenerator.language === lang.value }"
                        @click="aiGenerator.language = lang.value">{{ lang.label }}</span>
                </div>
              </div>
              <div class="form-group">
                <label class="form-label">额外要求</label>
                <textarea class="form-textarea" v-model="aiGenerator.additionalRequirements" rows="2"
                          placeholder="例如：强调价格优势、提及促销信息"></textarea>
              </div>
              <button class="btn btn-primary btn-block" @click="generateEmail" :disabled="isGenerating">
                <i class="fas fa-magic" :class="{ 'fa-spin': isGenerating }"></i>
                {{ isGenerating ? '生成中...' : '生成邮件' }}
              </button>
            </div>
            <div class="generator-output">
              <h4>效果预览</h4>
              <div v-if="!generatedEmail.subject" class="output-placeholder">
                <i class="fas fa-envelope-open-text"></i>
                <p>填写表单并点击生成</p>
              </div>
              <div v-else class="email-preview">
                <div class="email-field">
                  <label>主题：</label>
                  <div class="email-value subject">{{ generatedEmail.subject }}</div>
                </div>
                <div class="email-field">
                  <label>正文：</label>
                  <div class="email-body" v-html="generatedEmail.body"></div>
                </div>
                <div class="email-stats">
                  <span><i class="fas fa-font"></i> {{ generatedEmail.wordCount }} 字</span>
                  <span><i class="fas fa-clock"></i> {{ generatedEmail.readTime }}秒</span>
                  <span class="success"><i class="fas fa-star"></i> {{ generatedEmail.readability }}/10</span>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div class="modal-footer">
          <button class="btn btn-secondary" @click="showAIModal = false">关闭</button>
          <button v-if="generatedEmail.subject" class="btn btn-primary" @click="useEmail">
            <i class="fas fa-check"></i> 保存使用
          </button>
        </div>
      </div>
    </div>

    <!-- History Modal -->
    <div v-if="showHistoryModal" class="modal-overlay" @click.self="showHistoryModal = false">
      <div class="modal history-modal">
        <div class="modal-header">
          <div class="modal-title"><i class="fas fa-history"></i> 历史活动</div>
          <button class="modal-close" @click="showHistoryModal = false"><i class="fas fa-times"></i></button>
        </div>
        <div class="modal-body">
          <!-- 搜索和筛选 -->
          <div class="history-filters">
            <div class="search-box">
              <i class="fas fa-search"></i>
              <input type="text" v-model="historySearch" placeholder="搜索活动名称...">
            </div>
            <div class="filter-group">
              <select class="filter-select" v-model="historyFilter.status">
                <option value="">全部状态</option>
                <option value="completed">已完成</option>
                <option value="paused">已暂停</option>
                <option value="cancelled">已取消</option>
              </select>
              <select class="filter-select" v-model="historyFilter.type">
                <option value="">全部类型</option>
                <option value="prospect">潜客开发</option>
                <option value="nurture">客户培育</option>
                <option value="reactivate">客户唤醒</option>
                <option value="promote">产品推广</option>
              </select>
              <select class="filter-select" v-model="historyFilter.dateRange">
                <option value="">全部时间</option>
                <option value="week">最近一周</option>
                <option value="month">最近一月</option>
                <option value="quarter">最近三月</option>
                <option value="year">最近一年</option>
              </select>
            </div>
          </div>
          
          <!-- 统计概览 -->
          <div class="history-stats">
            <div class="history-stat">
              <div class="stat-value">{{ historyCampaigns?.length || 0 }}</div>
              <div class="stat-label">历史活动</div>
            </div>
            <div class="history-stat">
              <div class="stat-value">{{ totalHistoricalSent }}</div>
              <div class="stat-label">总发送量</div>
            </div>
            <div class="history-stat">
              <div class="stat-value">{{ avgHistoricalOpenRate }}%</div>
              <div class="stat-label">平均打开率</div>
            </div>
            <div class="history-stat">
              <div class="stat-value">{{ avgHistoricalReplyRate }}%</div>
              <div class="stat-label">平均回复率</div>
            </div>
            <div class="history-stat highlight">
              <div class="stat-value">{{ totalHistoricalOpportunities }}</div>
              <div class="stat-label">转化商机</div>
            </div>
          </div>

          <!-- 活动列表 -->
          <div class="history-list">
            <div v-for="campaign in historyCampaigns" :key="campaign.id" class="history-item">
              <div class="history-item-header">
                <div class="history-item-icon" :style="{ background: campaign.iconBg }">
                  <i :class="campaign.icon" :style="{ color: campaign.iconColor }"></i>
                </div>
                <div class="history-item-info">
                  <div class="history-item-name">{{ campaign.name }}</div>
                  <div class="history-item-meta">
                    <span><i class="fas fa-calendar"></i> {{ campaign.dateRange }}</span>
                    <span><i class="fas fa-user"></i> {{ campaign.owner }}</span>
                    <span class="status-tag" :class="campaign.status">{{ getStatusLabel(campaign.status) }}</span>
                  </div>
                </div>
                <div class="history-item-actions">
                  <button class="btn-icon" @click="duplicateCampaign(campaign)" title="复制活动">
                    <i class="fas fa-copy"></i>
                  </button>
                  <button class="btn-icon" @click="viewHistoryDetail(campaign)" title="查看详情">
                    <i class="fas fa-eye"></i>
                  </button>
                  <button class="btn-icon" @click="exportHistoryReport(campaign)" title="导出报告">
                    <i class="fas fa-download"></i>
                  </button>
                </div>
              </div>
              <div class="history-item-stats">
                <div class="mini-stat">
                  <i class="fas fa-paper-plane"></i>
                  <span class="value">{{ campaign.stats.sent }}</span>
                  <span class="label">发送</span>
                </div>
                <div class="mini-stat">
                  <i class="fas fa-envelope-open"></i>
                  <span class="value">{{ campaign.stats.opened }}</span>
                  <span class="label">打开 ({{ campaign.stats.openRate }}%)</span>
                </div>
                <div class="mini-stat">
                  <i class="fas fa-reply"></i>
                  <span class="value">{{ campaign.stats.replied }}</span>
                  <span class="label">回复 ({{ campaign.stats.replyRate }}%)</span>
                </div>
                <div class="mini-stat">
                  <i class="fas fa-mouse-pointer"></i>
                  <span class="value">{{ campaign.stats.clicked }}</span>
                  <span class="label">点击</span>
                </div>
                <div class="mini-stat highlight">
                  <i class="fas fa-bullseye"></i>
                  <span class="value">{{ campaign.stats.opportunities }}</span>
                  <span class="label">商机</span>
                </div>
              </div>
              <div class="history-item-channels">
                <span v-for="ch in campaign.channels" :key="ch" class="channel-mini-tag">
                  <i :class="getChannelIcon(ch)"></i> {{ ch }}
                </span>
              </div>
            </div>
            <div v-if="historyCampaigns?.length === 0" class="empty-state">
              <i class="fas fa-inbox"></i>
              <p>暂无历史活动数据</p>
            </div>
          </div>
        </div>
        <div class="modal-footer">
          <button class="btn btn-secondary" @click="exportAllHistory">
            <i class="fas fa-file-export"></i> 导出全部报告
          </button>
          <button class="btn btn-secondary" @click="showHistoryModal = false">关闭</button>
        </div>
      </div>
    </div>

    <!-- History Detail Modal -->
    <div v-if="showHistoryDetailModal" class="modal-overlay" @click.self="showHistoryDetailModal = false">
      <div class="modal history-detail-modal">
        <div class="modal-header">
          <div class="modal-title">
            <i class="fas fa-history"></i> 历史活动详情
            <span class="detail-status completed">{{ getStatusLabel(selectedHistoryCampaign?.status) }}</span>
          </div>
          <button class="modal-close" @click="showHistoryDetailModal = false"><i class="fas fa-times"></i></button>
        </div>
        <div class="modal-body" v-if="selectedHistoryCampaign">
          <!-- 基本信息 -->
          <div class="detail-section">
            <div class="section-header">
              <h4><i class="fas fa-info-circle"></i> 基本信息</h4>
            </div>
            <div class="detail-grid">
              <div class="detail-item">
                <label>活动名称</label>
                <span>{{ selectedHistoryCampaign.name }}</span>
              </div>
              <div class="detail-item">
                <label>活动周期</label>
                <span>{{ selectedHistoryCampaign.dateRange }}</span>
              </div>
              <div class="detail-item">
                <label>负责人</label>
                <span>{{ selectedHistoryCampaign.owner }}</span>
              </div>
              <div class="detail-item">
                <label>活动状态</label>
                <span class="status-badge" :class="selectedHistoryCampaign.status">{{ getStatusLabel(selectedHistoryCampaign.status) }}</span>
              </div>
            </div>
          </div>

          <!-- 核心数据统计 -->
          <div class="detail-section">
            <div class="section-header">
              <h4><i class="fas fa-chart-pie"></i> 核心数据统计</h4>
            </div>
            <div class="metrics-grid">
              <div class="metric-card">
                <div class="metric-icon blue"><i class="fas fa-paper-plane"></i></div>
                <div class="metric-content">
                  <div class="metric-value">{{ selectedHistoryCampaign.stats.sent.toLocaleString() }}</div>
                  <div class="metric-label">总发送量</div>
                </div>
              </div>
              <div class="metric-card">
                <div class="metric-icon green"><i class="fas fa-envelope-open"></i></div>
                <div class="metric-content">
                  <div class="metric-value">{{ selectedHistoryCampaign.stats.opened.toLocaleString() }}</div>
                  <div class="metric-label">打开数 ({{ selectedHistoryCampaign.stats.openRate }}%)</div>
                </div>
              </div>
              <div class="metric-card">
                <div class="metric-icon purple"><i class="fas fa-reply"></i></div>
                <div class="metric-content">
                  <div class="metric-value">{{ selectedHistoryCampaign.stats.replied.toLocaleString() }}</div>
                  <div class="metric-label">回复数 ({{ selectedHistoryCampaign.stats.replyRate }}%)</div>
                </div>
              </div>
              <div class="metric-card">
                <div class="metric-icon orange"><i class="fas fa-mouse-pointer"></i></div>
                <div class="metric-content">
                  <div class="metric-value">{{ selectedHistoryCampaign.stats.clicked.toLocaleString() }}</div>
                  <div class="metric-label">点击数</div>
                </div>
              </div>
              <div class="metric-card highlight">
                <div class="metric-icon success"><i class="fas fa-bullseye"></i></div>
                <div class="metric-content">
                  <div class="metric-value">{{ selectedHistoryCampaign.stats.opportunities }}</div>
                  <div class="metric-label">转化商机</div>
                </div>
              </div>
            </div>
          </div>

          <!-- 渠道效果分析 -->
          <div class="detail-section">
            <div class="section-header">
              <h4><i class="fas fa-chart-bar"></i> 渠道效果分析</h4>
            </div>
            <div class="channel-detail-list">
              <div v-for="ch in selectedHistoryCampaign.channels" :key="ch" class="channel-detail-item">
                <div class="channel-icon-wrapper" :style="getChannelStyleByName(ch)">
                  <i :class="getChannelIcon(ch)"></i>
                </div>
                <div class="channel-detail-info">
                  <div class="channel-detail-name">{{ ch }}</div>
                  <div class="channel-detail-stats">
                    <span>发送: {{ Math.round(selectedHistoryCampaign.stats.sent / selectedHistoryCampaign.channels.length) }}</span>
                    <span>打开率: {{ selectedHistoryCampaign.stats.openRate }}%</span>
                    <span>回复率: {{ selectedHistoryCampaign.stats.replyRate }}%</span>
                  </div>
                </div>
                <div class="channel-status">
                  <span class="status-dot completed"></span> 已完成
                </div>
              </div>
            </div>
          </div>

          <!-- 效果评估 -->
          <div class="detail-section">
            <div class="section-header">
              <h4><i class="fas fa-clipboard-check"></i> 效果评估</h4>
            </div>
            <div class="evaluation-grid">
              <div class="eval-item">
                <div class="eval-label">发送效率</div>
                <div class="eval-bar">
                  <div class="eval-fill" :style="{ width: '85%' }"></div>
                </div>
                <div class="eval-value">优秀</div>
              </div>
              <div class="eval-item">
                <div class="eval-label">打开率</div>
                <div class="eval-bar">
                  <div class="eval-fill" :style="{ width: selectedHistoryCampaign.stats.openRate + '%' }"></div>
                </div>
                <div class="eval-value">{{ selectedHistoryCampaign.stats.openRate >= 50 ? '优秀' : '良好' }}</div>
              </div>
              <div class="eval-item">
                <div class="eval-label">回复率</div>
                <div class="eval-bar">
                  <div class="eval-fill" :style="{ width: selectedHistoryCampaign.stats.replyRate * 3 + '%' }"></div>
                </div>
                <div class="eval-value">{{ selectedHistoryCampaign.stats.replyRate >= 15 ? '优秀' : '良好' }}</div>
              </div>
              <div class="eval-item">
                <div class="eval-label">转化率</div>
                <div class="eval-bar">
                  <div class="eval-fill" :style="{ width: (selectedHistoryCampaign.stats.opportunities / selectedHistoryCampaign.stats.sent * 100 * 10) + '%' }"></div>
                </div>
                <div class="eval-value">{{ selectedHistoryCampaign.stats.opportunities > 20 ? '优秀' : '良好' }}</div>
              </div>
            </div>
          </div>

          <!-- 经验总结 -->
          <div class="detail-section">
            <div class="section-header">
              <h4><i class="fas fa-lightbulb"></i> 经验总结</h4>
            </div>
            <div class="summary-content">
              <div class="summary-item">
                <i class="fas fa-check-circle success"></i>
                <span>活动时间选择恰当，目标客户响应积极</span>
              </div>
              <div class="summary-item">
                <i class="fas fa-check-circle success"></i>
                <span>邮件主题具有吸引力，打开率超过行业平均水平</span>
              </div>
              <div class="summary-item">
                <i class="fas fa-info-circle info"></i>
                <span>建议下次活动增加 WhatsApp 渠道触达</span>
              </div>
            </div>
          </div>
        </div>
        <div class="modal-footer">
          <button class="btn btn-secondary" @click="duplicateCampaign(selectedHistoryCampaign)">
            <i class="fas fa-copy"></i> 复制活动
          </button>
          <button class="btn btn-secondary" @click="exportHistoryReport(selectedHistoryCampaign)">
            <i class="fas fa-download"></i> 导出报告
          </button>
          <button class="btn btn-primary" @click="showHistoryDetailModal = false">关闭</button>
        </div>
      </div>
    </div>

    <!-- Templates Modal -->
    <div v-if="showTemplatesModal" class="modal-overlay" @click.self="showTemplatesModal = false">
      <div class="modal templates-modal">
        <div class="modal-header">
          <div class="modal-title"><i class="fas fa-file-alt"></i> 营销模板库</div>
          <button class="modal-close" @click="showTemplatesModal = false"><i class="fas fa-times"></i></button>
        </div>
        <div class="modal-body">
          <!-- 模板分类标签 -->
          <div class="template-tabs">
            <span class="template-tab" :class="{ active: templateTab === 'all' }" @click="templateTab = 'all'">
              全部模板
            </span>
            <span class="template-tab" :class="{ active: templateTab === 'email' }" @click="templateTab = 'email'">
              <i class="fas fa-envelope"></i> 邮件模板
            </span>
            <span class="template-tab" :class="{ active: templateTab === 'whatsapp' }" @click="templateTab = 'whatsapp'">
              <i class="fab fa-whatsapp"></i> WhatsApp
            </span>
            <span class="template-tab" :class="{ active: templateTab === 'linkedin' }" @click="templateTab = 'linkedin'">
              <i class="fab fa-linkedin"></i> LinkedIn
            </span>
            <span class="template-tab" :class="{ active: templateTab === 'my' }" @click="templateTab = 'my'">
              <i class="fas fa-star"></i> 我的模板
            </span>
          </div>

          <!-- 搜索和排序 -->
          <div class="templates-toolbar">
            <div class="search-box">
              <i class="fas fa-search"></i>
              <input type="text" v-model="templateSearch" placeholder="搜索模板名称或内容...">
            </div>
            <div class="sort-options">
              <select class="sort-select" v-model="templateSort">
                <option value="popular">最受欢迎</option>
                <option value="openRate">打开率最高</option>
                <option value="replyRate">回复率最高</option>
                <option value="newest">最新添加</option>
              </select>
            </div>
          </div>

          <!-- 模板统计 -->
          <div class="templates-stats">
            <span><i class="fas fa-folder"></i> 共 {{ filteredTemplates.length }} 个模板</span>
            <span class="divider">|</span>
            <span><i class="fas fa-chart-line"></i> 平均打开率: {{ avgTemplateOpenRate }}%</span>
            <span class="divider">|</span>
            <span><i class="fas fa-reply"></i> 平均回复率: {{ avgTemplateReplyRate }}%</span>
          </div>

          <!-- 模板列表 -->
          <div class="templates-grid-enhanced">
            <div v-for="tpl in filteredTemplates" :key="tpl.id" class="template-card-enhanced">
              <div class="template-card-header">
                <div class="template-type-badge" :class="tpl.channel">
                  <i :class="getTemplateChannelIcon(tpl.channel)"></i>
                  {{ tpl.type }}
                </div>
                <div class="template-lang-badge">{{ tpl.language }}</div>
                <button class="btn-favorite" :class="{ active: tpl.favorite }" @click="toggleFavorite(tpl)">
                  <i :class="tpl.favorite ? 'fas fa-star' : 'far fa-star'"></i>
                </button>
              </div>
              <div class="template-subject-enhanced">{{ tpl.subject }}</div>
              <div class="template-preview-enhanced">{{ tpl.preview }}</div>
              <div class="template-tags" v-if="tpl.tags && tpl.tags.length">
                <span v-for="tag in tpl.tags" :key="tag" class="template-tag">{{ tag }}</span>
              </div>
              <div class="template-stats-enhanced">
                <div class="template-stat">
                  <i class="fas fa-envelope-open"></i>
                  <span class="stat-value">{{ tpl.openRate }}%</span>
                  <span class="stat-label">打开率</span>
                </div>
                <div class="template-stat">
                  <i class="fas fa-reply"></i>
                  <span class="stat-value">{{ tpl.replyRate }}%</span>
                  <span class="stat-label">回复率</span>
                </div>
                <div class="template-stat">
                  <i class="fas fa-users"></i>
                  <span class="stat-value">{{ tpl.usedCount }}</span>
                  <span class="stat-label">使用次数</span>
                </div>
              </div>
              <div class="template-actions">
                <button class="btn btn-secondary btn-sm" @click="previewTemplate(tpl)">
                  <i class="fas fa-eye"></i> 预览
                </button>
                <button class="btn btn-primary btn-sm" @click="useTemplate(tpl)">
                  <i class="fas fa-check"></i> 使用
                </button>
              </div>
            </div>
          </div>

          <!-- AI推荐模板 -->
          <div class="ai-template-section">
            <div class="ai-section-header">
              <i class="fas fa-robot"></i>
              <span>AI 为您推荐</span>
              <span class="ai-badge-mini">基于您的行业和历史数据</span>
            </div>
            <div class="ai-template-list">
              <div v-for="tpl in aiRecommendedTemplates" :key="tpl.id" class="ai-template-item" @click="useTemplate(tpl)">
                <div class="ai-template-icon">
                  <i :class="getTemplateChannelIcon(tpl.channel)"></i>
                </div>
                <div class="ai-template-info">
                  <div class="ai-template-subject">{{ tpl.subject }}</div>
                  <div class="ai-template-meta">
                    <span>{{ tpl.type }}</span>
                    <span>{{ tpl.language }}</span>
                    <span class="highlight">{{ tpl.matchScore }}% 匹配</span>
                  </div>
                </div>
                <div class="ai-template-stats">
                  <span><i class="fas fa-envelope-open"></i> {{ tpl.openRate }}%</span>
                  <span><i class="fas fa-reply"></i> {{ tpl.replyRate }}%</span>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div class="modal-footer">
          <button class="btn btn-secondary" @click="showCreateTemplateModal = true">
            <i class="fas fa-plus"></i> 创建模板
          </button>
          <button class="btn btn-secondary" @click="importTemplates">
            <i class="fas fa-file-import"></i> 导入模板
          </button>
          <button class="btn btn-secondary" @click="showTemplatesModal = false">关闭</button>
        </div>
      </div>
    </div>

    <!-- Template Preview Modal -->
    <div v-if="showTemplatePreview" class="modal-overlay" @click.self="showTemplatePreview = false">
      <div class="modal template-preview-modal">
        <div class="modal-header">
          <div class="modal-title"><i class="fas fa-eye"></i> 模板预览</div>
          <button class="modal-close" @click="showTemplatePreview = false"><i class="fas fa-times"></i></button>
        </div>
        <div class="modal-body">
          <div class="preview-template-content" v-if="previewingTemplate">
            <div class="preview-row">
              <label>模板类型：</label>
              <span>{{ previewingTemplate.type }}</span>
            </div>
            <div class="preview-row">
              <label>语言：</label>
              <span>{{ previewingTemplate.language }}</span>
            </div>
            <div class="preview-row">
              <label>邮件主题：</label>
              <div class="preview-subject">{{ previewingTemplate.subject }}</div>
            </div>
            <div class="preview-row">
              <label>邮件正文：</label>
              <div class="preview-body" v-html="previewingTemplate.body || previewingTemplate.preview"></div>
            </div>
            <div class="preview-row tags-row" v-if="previewingTemplate.tags">
              <label>标签：</label>
              <div class="preview-tags">
                <span v-for="tag in previewingTemplate.tags" :key="tag" class="preview-tag">{{ tag }}</span>
              </div>
            </div>
          </div>
        </div>
        <div class="modal-footer">
          <button class="btn btn-secondary" @click="showTemplatePreview = false">关闭</button>
          <button class="btn btn-primary" @click="useTemplate(previewingTemplate)">
            <i class="fas fa-check"></i> 使用此模板
          </button>
        </div>
      </div>
    </div>

    <!-- Opened Customers Modal -->
    <div v-if="showOpenedCustomersModal" class="modal-overlay" @click.self="showOpenedCustomersModal = false">
      <div class="modal detail-modal">
        <div class="modal-header">
          <div class="modal-title">
            <i class="fas fa-envelope-open"></i> 打开邮件的客户 ({{ selectedOpenedCampaign?.openedCustomers }})
          </div>
          <button class="modal-close" @click="showOpenedCustomersModal = false"><i class="fas fa-times"></i></button>
        </div>
        <div class="modal-body">
          <div class="filter-bar">
            <button class="filter-btn active">全部</button>
            <button class="filter-btn">高价值</button>
            <button class="filter-btn">已保护</button>
            <button class="filter-btn">营销暂停</button>
          </div>
          <div class="customers-list">
            <div v-for="customer in openedCustomers" :key="customer.id" class="customer-item" :class="{ protected: customer.protected }">
              <div class="customer-header">
                <div class="customer-info">
                  <div class="customer-name">
                    {{ customer.name }}
                    <span v-if="customer.protected" class="protection-badge">
                      <i class="fas fa-shield-alt"></i> 已保护
                    </span>
                  </div>
                  <div class="customer-email">{{ customer.email }}</div>
                </div>
              </div>
              <div class="customer-details">
                <div class="detail-item">
                  <span class="label">打开时间:</span>
                  <span class="value">{{ customer.openTime }}</span>
                </div>
                <div class="detail-item">
                  <span class="label">点击次数:</span>
                  <span class="value">{{ customer.clickCount }}次</span>
                </div>
              </div>
              <div class="customer-actions">
                <button v-if="!customer.protected" class="btn btn-secondary btn-sm" @click="protectCustomer(customer)" title="添加到保护白名单">
                  <i class="fas fa-shield-alt"></i> 保护
                </button>
                <button v-else class="btn btn-secondary btn-sm" @click="unprotectCustomer(customer)" title="从保护白名单中移除">
                  <i class="fas fa-times"></i> 取消保护
                </button>
                <button class="btn btn-secondary btn-sm" @click="pauseCampaignForCustomer(customer)" v-if="customer.interventionStatus !== 'paused'" title="暂停向该客户发送邮件">
                  <i class="fas fa-pause"></i> 暂停
                </button>
                <button class="btn btn-secondary btn-sm" @click="resumeCampaignForCustomer(customer)" v-else title="恢复向该客户发送邮件">
                  <i class="fas fa-play"></i> 恢复
                </button>
              </div>
            </div>
          </div>
        </div>
        <div class="modal-footer">
          <button class="btn btn-secondary" @click="showOpenedCustomersModal = false">关闭</button>
          <button class="btn btn-primary" @click="showOpenedCustomersModal = false">
            <i class="fas fa-download"></i> 导出列表
          </button>
        </div>
      </div>
    </div>

    <!-- Reply Review Modal -->
    <div v-if="showReplyReviewModal" class="modal-overlay" @click.self="showReplyReviewModal = false">
      <div class="modal detail-modal">
        <div class="modal-header">
          <div class="modal-title">
            <i class="fas fa-reply"></i> 回复邮件的客户 ({{ repliedCustomers.length }}个)
          </div>
          <button class="modal-close" @click="showReplyReviewModal = false"><i class="fas fa-times"></i></button>
        </div>
        <div class="modal-body">
          <div class="review-stats">
            <div class="stat-box">
              <span class="stat-label">全部</span>
              <span class="stat-value">{{ repliedCustomers.filter(r => r.status === 'pending-review').length }}</span>
            </div>
            <div class="stat-box">
              <span class="stat-label">已保护</span>
              <span class="stat-value">{{ repliedCustomers.filter(r => r.requiresHumanReview).length }}</span>
            </div>
            <div class="stat-box">
              <span class="stat-label">营销暂停</span>
              <span class="stat-value">{{ repliedCustomers.filter(r => r.priority === '高').length }}</span>
            </div>
          </div>
          <div class="replies-list">
            <div v-for="reply in repliedCustomers" :key="reply.id" class="reply-item" :class="[reply.status, { 'requires-review': reply.requiresHumanReview }]">
              <div class="reply-header">
                <div class="reply-info">
                  <div class="reply-name">
                    {{ reply.name }}
                  </div>
                  <div class="reply-email">{{ reply.email }}</div>
                </div>
                <div class="reply-badges">
                  <span class="priority-badge" :class="reply.priority">
                    {{ reply.priority }}优先级
                  </span>
                  <span class="value-badge" :class="reply.value">{{ reply.value }}</span>
                </div>
              </div>
              <div class="reply-time">回复时间: {{ reply.replyTime }}</div>
              <div class="reply-content">
                <p>{{ reply.replyContent }}</p>
              </div>
              <div class="reply-review-notes" v-if="reply.reviewNotes">
                <i class="fas fa-lightbulb"></i>
                <span>{{ reply.reviewNotes }}</span>
              </div>
              <div class="reply-actions">
                <button v-if="!reply.protected" class="btn btn-secondary btn-sm" @click="protectCustomer(reply)" title="添加到保护白名单">
                  <i class="fas fa-shield-alt"></i> 保护
                </button>
                <button v-else class="btn btn-secondary btn-sm" @click="unprotectCustomer(reply)" title="从保护白名单中移除">
                  <i class="fas fa-times"></i> 取消保护
                </button>
                <button class="btn btn-secondary btn-sm" @click="pauseCampaignForCustomer(reply)" v-if="reply.interventionStatus !== 'paused'" title="暂停向该客户发送邮件">
                  <i class="fas fa-pause"></i> 暂停
                </button>
                <button class="btn btn-secondary btn-sm" @click="resumeCampaignForCustomer(reply)" v-else title="恢复向该客户发送邮件">
                  <i class="fas fa-play"></i> 恢复
                </button>
              </div>
            </div>
          </div>
        </div>
        <div class="modal-footer">
          <button class="btn btn-secondary" @click="showReplyReviewModal = false">关闭</button>
          <button class="btn btn-primary" @click="showReplyReviewModal = false">
            <i class="fas fa-download"></i> 导出回复
          </button>
        </div>
      </div>
    </div>

    <!-- Intervention Modal -->
    <div v-if="showInterventionModal" class="modal-overlay" @click.self="showInterventionModal = false">
      <div class="modal detail-modal">
        <div class="modal-header">
          <div class="modal-title">
            <i class="fas fa-hand-paper"></i> 人工干预
          </div>
          <button class="modal-close" @click="showInterventionModal = false"><i class="fas fa-times"></i></button>
        </div>
        <div class="modal-body" v-if="selectedIntervention">
          <div class="tabs-section">
            <div class="tab-item active" @click="selectedIntervention.activeTab = 'protected'">
              <i class="fas fa-shield-alt"></i> 客户保护白名单
            </div>
            <div class="tab-item" @click="selectedIntervention.activeTab = 'history'">
              <i class="fas fa-hand-paper"></i> 营销暂停
            </div>
          </div>

          <!-- Protected Customers List -->
          <div v-if="!selectedIntervention.activeTab || selectedIntervention.activeTab === 'protected'" class="detail-section">
            <div class="protected-customers">
              <div v-for="customer in protectedCustomersList" :key="customer.id" class="protected-customer-item">
                <div class="customer-header">
                  <div class="customer-info">
                    <div class="customer-name">
                      {{ customer.name }}
                      <span class="protection-level" :class="customer.protectionLevel">
                        {{ customer.protectionLevel }}保护
                      </span>
                    </div>
                    <div class="customer-email">{{ customer.email }}</div>
                  </div>
                </div>
                <div class="customer-details">
                  <span class="detail">保护原因: {{ customer.reason }}</span>
                  <span class="detail">保护时间: {{ customer.protectedSince }}</span>
                </div>
                <div class="customer-actions">
                  <button class="btn btn-secondary btn-sm" @click="unprotectCustomer(customer)">
                    <i class="fas fa-times"></i> 移除保护
                  </button>
                </div>
              </div>
            </div>
          </div>

          <!-- Intervention History -->
          <div v-if="selectedIntervention.activeTab === 'history'" class="detail-section">
            <h5>干预历史记录</h5>
            <div class="interventions-list">
              <div v-for="intervention in interventions.filter(i => i.campaignId === selectedIntervention.id)" :key="intervention.id" class="intervention-item">
                <div class="intervention-header">
                  <span class="intervention-type">{{ intervention.type }}</span>
                  <span class="intervention-status" :class="intervention.status">{{ intervention.status === 'active' ? '进行中' : '已完成' }}</span>
                </div>
                <div class="intervention-info">
                  <p class="description">{{ intervention.description }}</p>
                  <div class="meta">
                    <span>原因: {{ intervention.reason }}</span>
                    <span>影响: {{ intervention.affectedCount }}个客户</span>
                    <span>创建: {{ intervention.createdTime }}</span>
                    <span>创建人: {{ intervention.createdBy }}</span>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <!-- Current Interventions -->
          <div class="detail-section">
            <h5>现有干预</h5>
            <div class="interventions-list">
              <div v-for="intervention in interventions.filter(i => i.campaignId === selectedIntervention.id)" :key="intervention.id" class="intervention-item">
                <div class="intervention-header">
                  <span class="intervention-type">{{ intervention.type }}</span>
                  <span class="intervention-status" :class="intervention.status">{{ intervention.status === 'active' ? '进行中' : '已完成' }}</span>
                </div>
                <div class="intervention-info">
                  <p class="description">{{ intervention.description }}</p>
                  <div class="meta">
                    <span>原因: {{ intervention.reason }}</span>
                    <span>影响: {{ intervention.affectedCount }}个客户</span>
                    <span>创建: {{ intervention.createdTime }}</span>
                    <span>创建人: {{ intervention.createdBy }}</span>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div class="modal-footer">
          <button class="btn btn-secondary" @click="showInterventionModal = false">关闭</button>
          <button class="btn btn-primary" @click="showInterventionModal = false">
            <i class="fas fa-download"></i> 导出报告
          </button>
        </div>
      </div>
    </div>
    <transition name="toast">
      <div v-if="showToast" class="toast" :class="toastType">
        <i :class="toastType === 'success' ? 'fas fa-check-circle' : 'fas fa-info-circle'"></i>
        {{ toastMessage }}
      </div>
    </transition>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import AddMarketing from '../components/addMarketing.vue'
import { getMarketingList } from '../api/marketing'

const filterTab = ref('all')

const showAIModal = ref(false)
const showTemplatesModal = ref(false)
const showHistoryModal = ref(false)
const showHistoryDetailModal = ref(false)
const selectedHistoryCampaign = ref(null)
const showTemplatePreview = ref(false)
const showCreateTemplateModal = ref(false)
const showCampaignDetailModal = ref(false)
const showInteractionsModal = ref(false)
const selectedCampaignInteractions = ref([])
const selectedCampaign = ref(null)
const previewingTemplate = ref(null)
const isGenerating = ref(false)
const showToast = ref(false)
const toastMessage = ref('')
const toastType = ref('success')
const showInterventionModal = ref(false)
const showOpenedCustomersModal = ref(false)
const showReplyReviewModal = ref(false)
const selectedIntervention = ref(null)
const selectedOpenedCampaign = ref(null)
const selectedReplyReview = ref(null)

const addMarketingRef = ref()
const openCreateModal = () => {
  addMarketingRef.value.open()
}

getMarketingList({ pageIndex: 1, pageSize: 10 }).then(res => {
  console.log('res :>> ', res);
})

// History filters
const historySearch = ref('')
const historyFilter = ref({ status: '', type: '', dateRange: '' })
const templateSearch = ref('')
const templateTab = ref('all')
const templateSort = ref('popular')

const marketingStats = { totalSent: 2847, openRate: 45, clickRate: 12, replyRate: 8, protectedCustomers: 156, pendingReview: 23, activeCampaigns: 5 }
const tabs = [
  { key: 'all', label: '全部活动', count: 12 },
  { key: 'active', label: '进行中', count: 5 },
  { key: 'paused', label: '已暂停', count: 2 },
  { key: 'completed', label: '已完成', count: 5 }
]

const campaigns = ref([
  // ===== 进行中 =====
  { id: 1, name: '中东潜客开发活动', description: '针对中东地区 SSD 进口商', status: 'active', progress: 68, icon: 'fas fa-globe', iconBg: 'rgba(99, 102, 241, 0.2)', iconColor: 'var(--primary)', channels: ['邮件', 'LinkedIn'], stats: { sent: 312, openRate: 48, replyRate: 12 }, openedCustomers: 150, repliedCustomers: 37 },
  { id: 2, name: '欧洲企业级存储推广', description: '面向欧洲数据中心客户', status: 'active', progress: 45, icon: 'fas fa-server', iconBg: 'rgba(16, 185, 129, 0.2)', iconColor: 'var(--success)', channels: ['邮件', 'WhatsApp'], stats: { sent: 178, openRate: 52, replyRate: 15 }, openedCustomers: 93, repliedCustomers: 27 },
  { id: 3, name: '沉默客户唤醒计划', description: '重新激活90天未互动客户', status: 'active', progress: 32, icon: 'fas fa-moon', iconBg: 'rgba(139, 92, 246, 0.2)', iconColor: 'var(--secondary)', channels: ['邮件'], stats: { sent: 89, openRate: 35, replyRate: 8 }, openedCustomers: 31, repliedCustomers: 7 },
  { id: 5, name: '东南亚分销商招募', description: '招募东南亚电子产品分销商', status: 'active', progress: 55, icon: 'fas fa-handshake', iconBg: 'rgba(6, 182, 212, 0.2)', iconColor: 'var(--info)', channels: ['邮件', 'WhatsApp'], stats: { sent: 234, openRate: 38, replyRate: 11 }, openedCustomers: 89, repliedCustomers: 26 },
  { id: 6, name: '非洲新兴市场开拓', description: '开拓非洲电子产品进口商资源', status: 'active', progress: 22, icon: 'fas fa-map-marker-alt', iconBg: 'rgba(239, 68, 68, 0.2)', iconColor: 'var(--danger)', channels: ['邮件', 'WhatsApp'], stats: { sent: 145, openRate: 31, replyRate: 7 }, openedCustomers: 45, repliedCustomers: 10 },
  { id: 7, name: '2026春季产品推广', description: '推广最新一代企业级SSD产品线', status: 'active', progress: 60, icon: 'fas fa-box-open', iconBg: 'rgba(251, 191, 36, 0.2)', iconColor: '#FBBF24', channels: ['邮件', 'LinkedIn', 'WhatsApp'], stats: { sent: 420, openRate: 55, replyRate: 18 }, openedCustomers: 231, repliedCustomers: 76 },
  { id: 8, name: '展会客户跟进计划', description: '跟进2026广交会收集的名片客户', status: 'active', progress: 78, icon: 'fas fa-id-card', iconBg: 'rgba(16, 185, 129, 0.2)', iconColor: 'var(--success)', channels: ['邮件', 'WhatsApp'], stats: { sent: 267, openRate: 61, replyRate: 22 }, openedCustomers: 163, repliedCustomers: 59 },
  // ===== 已暂停 =====
  { id: 4, name: '北美市场拓展', description: '针对美国和加拿大市场', status: 'paused', progress: 25, icon: 'fas fa-flag-usa', iconBg: 'rgba(245, 158, 11, 0.2)', iconColor: 'var(--warning)', channels: ['邮件', 'LinkedIn'], stats: { sent: 156, openRate: 42, replyRate: 10 }, openedCustomers: 65, repliedCustomers: 16 },
  { id: 9, name: '日韩高端客户培育', description: '针对日本和韩国高端企业客户', status: 'paused', progress: 40, icon: 'fas fa-gem', iconBg: 'rgba(139, 92, 246, 0.2)', iconColor: 'var(--secondary)', channels: ['邮件', 'LinkedIn'], stats: { sent: 98, openRate: 44, replyRate: 9 }, openedCustomers: 43, repliedCustomers: 9 },
  { id: 10, name: '南美分销渠道建设', description: '在巴西、阿根廷等地寻找分销商', status: 'paused', progress: 15, icon: 'fas fa-route', iconBg: 'rgba(6, 182, 212, 0.2)', iconColor: 'var(--info)', channels: ['邮件'], stats: { sent: 72, openRate: 28, replyRate: 5 }, openedCustomers: 20, repliedCustomers: 4 },
  { id: 11, name: '印度IT采购季活动', description: '针对印度IT企业Q2采购季', status: 'paused', progress: 50, icon: 'fas fa-rupee-sign', iconBg: 'rgba(245, 158, 11, 0.2)', iconColor: 'var(--warning)', channels: ['邮件', 'WhatsApp'], stats: { sent: 189, openRate: 37, replyRate: 11 }, openedCustomers: 70, repliedCustomers: 21 },
  // ===== 已完成 =====
  { id: 12, name: '2025年终大促活动', description: '2025年Q4年终促销，清库存冲业绩', status: 'completed', progress: 100, icon: 'fas fa-trophy', iconBg: 'rgba(251, 191, 36, 0.2)', iconColor: '#FBBF24', channels: ['邮件', 'WhatsApp', 'LinkedIn'], stats: { sent: 856, openRate: 62, replyRate: 24 }, openedCustomers: 531, repliedCustomers: 205 },
  { id: 13, name: '欧洲圣诞节日营销', description: '圣诞节前针对欧洲客户的节日促销', status: 'completed', progress: 100, icon: 'fas fa-snowflake', iconBg: 'rgba(99, 102, 241, 0.2)', iconColor: 'var(--primary)', channels: ['邮件', 'LinkedIn'], stats: { sent: 412, openRate: 57, replyRate: 19 }, openedCustomers: 235, repliedCustomers: 78 },
  { id: 14, name: '中东斋月特别活动', description: '斋月期间针对中东客户的专项营销', status: 'completed', progress: 100, icon: 'fas fa-star-and-crescent', iconBg: 'rgba(16, 185, 129, 0.2)', iconColor: 'var(--success)', channels: ['邮件', 'WhatsApp'], stats: { sent: 298, openRate: 53, replyRate: 17 }, openedCustomers: 158, repliedCustomers: 51 },
  { id: 15, name: '2025广交会前期预热', description: '广交会前向目标客户发送邀请函', status: 'completed', progress: 100, icon: 'fas fa-handshake', iconBg: 'rgba(6, 182, 212, 0.2)', iconColor: 'var(--info)', channels: ['邮件', 'LinkedIn', 'WhatsApp'], stats: { sent: 634, openRate: 68, replyRate: 28 }, openedCustomers: 431, repliedCustomers: 177 }
])

const filteredCampaigns = computed(() => filterTab.value === 'all' ? campaigns.value : campaigns.value.filter(c => c.status === filterTab.value))

// 打开邮件的客户列表 - 需要人工跟进
const openedCustomers = ref([
  { id: 1, name: '阿里巴巴国际', email: 'contact@alibaba-intl.com', openTime: '2026-03-23 10:30', clickCount: 2, status: 'opened', engagement: '高', value: '高价值', annualPurchase: '¥500K+', lastOrder: '2026-02-15', protected: true, protectionReason: '高价值客户', interventionStatus: 'assigned-to-sales' },
  { id: 2, name: '沙特阿美贸易', email: 'trade@aramco-sa.com', openTime: '2026-03-23 09:15', clickCount: 1, status: 'opened', engagement: '中', value: '中价值', annualPurchase: '¥200K', lastOrder: '2026-03-01', protected: true, protectionReason: '活跃客户', interventionStatus: 'pending-review' },
  { id: 3, name: '迪拜电子商务', email: 'info@dubai-ecom.ae', openTime: '2026-03-23 08:45', clickCount: 3, status: 'opened', engagement: '高', value: '高价值', annualPurchase: '¥800K+', lastOrder: '2026-02-28', protected: true, protectionReason: '高价值客户', interventionStatus: 'assigned-to-sales' },
  { id: 4, name: '新加坡科技', email: 'sales@sg-tech.com.sg', openTime: '2026-03-22 16:20', clickCount: 0, status: 'opened', engagement: '低', value: '低价值', annualPurchase: '¥50K', lastOrder: '2025-12-10', protected: false, protectionReason: '', interventionStatus: 'auto-follow' },
  { id: 5, name: '印度IT服务', email: 'contact@india-it.in', openTime: '2026-03-22 14:50', clickCount: 2, status: 'opened', engagement: '中', value: '中价值', annualPurchase: '¥150K', lastOrder: '2026-01-20', protected: true, protectionReason: '活跃客户', interventionStatus: 'pending-review' },
  { id: 6, name: '巴西进出口', email: 'export@brasil-trade.br', openTime: '2026-03-22 11:30', clickCount: 1, status: 'opened', engagement: '低', value: '低价值', annualPurchase: '¥30K', lastOrder: '2025-11-05', protected: false, protectionReason: '', interventionStatus: 'auto-follow' },
  { id: 7, name: '德国工业集团', email: 'procurement@de-industry.de', openTime: '2026-03-21 15:45', clickCount: 4, status: 'opened', engagement: '高', value: '高价值', annualPurchase: '¥1.2M+', lastOrder: '2026-03-10', protected: true, protectionReason: '高价值客户', interventionStatus: 'assigned-to-sales' },
  { id: 8, name: '英国分销商', email: 'sales@uk-dist.co.uk', openTime: '2026-03-21 13:20', clickCount: 2, status: 'opened', engagement: '中', value: '中价值', annualPurchase: '¥300K', lastOrder: '2026-02-20', protected: true, protectionReason: '活跃客户', interventionStatus: 'pending-review' }
])

// 回复邮件的客户列表 - 需要人工审核和介入
const repliedCustomers = ref([
  { id: 1, name: '中东贸易公司', email: 'buyer@middle-east-trade.com', replyTime: '2026-03-23 11:45', replyContent: '感谢您的邮件，我们对您的产品很感兴趣，能否提供详细的产品规格和价格？', status: 'pending-review', sentiment: '正面', priority: '高', value: '高价值', annualPurchase: '¥600K+', lastOrder: '2026-02-10', requiresHumanReview: true, reviewNotes: '需要销售人员立即跟进，客户明确表示感兴趣', assignedTo: '', reviewedBy: '', reviewTime: '' },
  { id: 2, name: '欧洲数据中心', email: 'procurement@eu-datacenter.eu', replyTime: '2026-03-23 10:20', replyContent: '我们正在评估新的存储解决方案，您能否安排一次技术演示？', status: 'pending-review', sentiment: '正面', priority: '高', value: '高价值', annualPurchase: '¥1M+', lastOrder: '2026-03-05', requiresHumanReview: true, reviewNotes: '需要技术团队配合，安排产品演示', assignedTo: '', reviewedBy: '', reviewTime: '' },
  { id: 3, name: '北美分销', email: 'sales@na-dist.com', replyTime: '2026-03-22 16:30', replyContent: '价格太高了，能否提供折扣？', status: 'pending-review', sentiment: '中立', priority: '中', value: '中价值', annualPurchase: '¥250K', lastOrder: '2026-01-15', requiresHumanReview: true, reviewNotes: '需要销售经理评估折扣空间', assignedTo: '', reviewedBy: '', reviewTime: '' },
  { id: 4, name: '东南亚进口商', email: 'import@sea-import.com', replyTime: '2026-03-22 14:15', replyContent: '我们有兴趣，但需要了解更多关于技术支持的信息。', status: 'pending-review', sentiment: '正面', priority: '中', value: '中价值', annualPurchase: '¥180K', lastOrder: '2026-02-01', requiresHumanReview: true, reviewNotes: '需要技术支持团队提供详细信息', assignedTo: '', reviewedBy: '', reviewTime: '' },
  { id: 5, name: '日本电子商社', email: 'trade@japan-elec.jp', replyTime: '2026-03-21 17:00', replyContent: '暂时不需要，但会保留您的联系方式。', status: 'pending-review', sentiment: '中立', priority: '低', value: '低价值', annualPurchase: '¥80K', lastOrder: '2025-10-20', requiresHumanReview: false, reviewNotes: '可自动标记为后续跟进', assignedTo: '', reviewedBy: '', reviewTime: '' },
  { id: 6, name: '韩国科技公司', email: 'contact@korea-tech.kr', replyTime: '2026-03-21 15:30', replyContent: '这不是我们需要的产品类型。', status: 'pending-review', sentiment: '负面', priority: '低', value: '低价值', annualPurchase: '¥40K', lastOrder: '2025-09-10', requiresHumanReview: false, reviewNotes: '可自动标记为不适配，从列表中移除', assignedTo: '', reviewedBy: '', reviewTime: '' }
])

// 人工干预列表 - 保护有效客户
const interventions = ref([
  { id: 1, campaignId: 1, type: '客户保护', reason: '高价值客户，需要人工跟进', affectedCount: 12, status: 'active', createdTime: '2026-03-23 12:00', createdBy: '销售经理', description: '将高价值客户从自动营销中移除，由销售人员进行专属跟进' },
  { id: 2, campaignId: 2, type: '审核干预', reason: '回复邮件需要人工审核', affectedCount: 6, status: 'active', createdTime: '2026-03-23 11:30', createdBy: '营销主管', description: '所有回复邮件必须经过人工审核后才能进行后续跟进' },
  { id: 3, campaignId: 3, type: '内容调整', reason: '提高邮件个性化程度', affectedCount: 89, status: 'active', createdTime: '2026-03-22 10:00', createdBy: '营销主管', description: '根据客户历史数据调整邮件内容，提高相关性' },
  { id: 4, campaignId: 1, type: '发送暂停', reason: '等待销售人员反馈', affectedCount: 45, status: 'active', createdTime: '2026-03-21 14:30', createdBy: '销售经理', description: '暂停向该客户群体发送邮件，等待销售团队的跟进反馈' }
])

// 客户保护白名单 - 防止AI营销影响
const protectedCustomersList = ref([
  { id: 1, name: '阿里巴巴国际', email: 'contact@alibaba-intl.com', protectionLevel: '高', reason: '高价值客户', annualValue: '¥500K+', status: 'active', protectedSince: '2026-03-20', assignedSalesRep: '张三' },
  { id: 2, name: '迪拜电子商务', email: 'info@dubai-ecom.ae', protectionLevel: '高', reason: '高价值客户', annualValue: '¥800K+', status: 'active', protectedSince: '2026-03-18', assignedSalesRep: '李四' },
  { id: 3, name: '德国工业集团', email: 'procurement@de-industry.de', protectionLevel: '高', reason: '高价值客户', annualValue: '¥1.2M+', status: 'active', protectedSince: '2026-03-15', assignedSalesRep: '王五' },
  { id: 4, name: '沙特阿美贸易', email: 'trade@aramco-sa.com', protectionLevel: '中', reason: '活跃客户', annualValue: '¥200K', status: 'active', protectedSince: '2026-03-22', assignedSalesRep: '赵六' },
  { id: 5, name: '英国分销商', email: 'sales@uk-dist.co.uk', protectionLevel: '中', reason: '活跃客户', annualValue: '¥300K', status: 'active', protectedSince: '2026-03-21', assignedSalesRep: '孙七' }
])

const showCustomerPreview = ref(false)
const showSubjectSuggestions = ref(false)

const subjectSuggestions = ref([
  'Reliable SSD Solutions for Your Business',
  'Quality Storage Products at Competitive Prices',
  'Partnership Opportunity - Storage Solutions'
])

const confirmChecks = ref({ content: false, schedule: false, compliance: false, unsubscribe: true })

const segmentOptions = [
  { id: 'all', name: '全部潜客', count: 847, icon: 'fas fa-globe' },
  { id: 'new', name: '本周新增', count: 56, icon: 'fas fa-star' },
  { id: 'high-intent', name: '高评分客户', count: 124, icon: 'fas fa-fire' },
  { id: 'silent', name: '沉默客户', count: 89, icon: 'fas fa-moon' }
]

const sopTemplates = [
  { id: 'standard', name: '标准开发序列', icon: '📧', steps: 4, description: '适合初次触达客户', stepsDetail: [
    { title: '首封介绍邮件', day: 1, channel: '邮件', channelIcon: 'fas fa-envelope' },
    { title: '产品优势介绍', day: 3, channel: '邮件', channelIcon: 'fas fa-envelope' },
    { title: '案例分享', day: 7, channel: 'LinkedIn', channelIcon: 'fab fa-linkedin' },
    { title: '电话跟进', day: 14, channel: '电话', channelIcon: 'fas fa-phone' }
  ]},
  { id: 'aggressive', name: '快速跟进序列', icon: '⚡', steps: 3, description: '快速转化意向客户', stepsDetail: [
    { title: '个性化介绍', day: 1, channel: '邮件', channelIcon: 'fas fa-envelope' },
    { title: 'WhatsApp跟进', day: 2, channel: 'WhatsApp', channelIcon: 'fab fa-whatsapp' },
    { title: '报价发送', day: 5, channel: '邮件', channelIcon: 'fas fa-envelope' }
  ]},
  { id: 'nurture', name: '培育序列', icon: '🌱', steps: 5, description: '长期培育潜在客户', stepsDetail: [
    { title: '欢迎邮件', day: 1, channel: '邮件', channelIcon: 'fas fa-envelope' },
    { title: '行业报告', day: 7, channel: '邮件', channelIcon: 'fas fa-envelope' },
    { title: '产品更新', day: 14, channel: '邮件', channelIcon: 'fas fa-envelope' },
    { title: '案例研究', day: 21, channel: 'LinkedIn', channelIcon: 'fab fa-linkedin' },
    { title: '优惠促销', day: 30, channel: '邮件', channelIcon: 'fas fa-envelope' }
  ]},
  { id: 'reactivate', name: '唤醒序列', icon: '🔄', steps: 3, description: '重新激活沉睡客户', stepsDetail: [
    { title: '想念你邮件', day: 1, channel: '邮件', channelIcon: 'fas fa-envelope' },
    { title: '新产品推荐', day: 5, channel: '邮件', channelIcon: 'fas fa-envelope' },
    { title: '特别优惠', day: 10, channel: 'WhatsApp', channelIcon: 'fab fa-whatsapp' }
  ]}
]

const aiGenerator = ref({
  type: 'introduction', product: 'ssd', selectedPoints: ['quality', 'price'],
  tone: 'professional', language: 'en', additionalRequirements: ''
})

const sellingPoints = [
  { id: 'quality', label: '高品质' }, { id: 'price', label: '价格优势' },
  { id: 'service', label: '售后服务' }, { id: 'delivery', label: '快速交付' },
  { id: 'certification', label: '认证' }, { id: 'customization', label: '定制服务' }
]

const toneOptions = [
  { value: 'professional', label: '专业' }, { value: 'friendly', label: '友好' },
  { value: 'direct', label: '简洁' }, { value: 'persuasive', label: '说服力' }
]

const languageOptions = [
  { value: 'en', label: 'English' }, { value: 'zh', label: '中文' },
  { value: 'de', label: 'Deutsch' }, { value: 'ar', label: 'العربية' }
]

const generatedEmail = ref({ subject: '', body: '', wordCount: 0, readTime: 0, readability: 0 })

const emailTemplates = ref([
  { id: 1, type: '介绍信', language: 'EN', subject: 'Reliable SSD Solutions for Your Business', preview: 'Hi [Name], I noticed your company...', openRate: 48, replyRate: 12 },
  { id: 2, type: '跟进邮件', language: 'EN', subject: 'Following Up on Our Conversation', preview: 'Hi [Name], I wanted to follow up...', openRate: 35, replyRate: 8 },
  { id: 3, type: '产品推荐', language: 'EN', subject: 'New Enterprise SSD Line', preview: 'Hi [Name], Exciting news...', openRate: 52, replyRate: 15 },
  { id: 4, type: '介绍信', language: '中文', subject: '为您的企业提供可靠存储方案', preview: '您好，我注意到贵公司...', openRate: 45, replyRate: 10 }
])

// const predictedOpenRate = computed(() => {
//   let rate = 35
//   if (newCampaign.value.channels.includes('email')) rate += 10
//   if (newCampaign.value.channels.includes('whatsapp')) rate += 15
//   if (newCampaign.value.channels.includes('linkedin')) rate += 8
//   if (newCampaign.value.aiRecommend) rate += 5
//   return Math.min(rate, 55)
// })

// const predictedReplyRate = computed(() => {
//   let rate = 8
//   if (newCampaign.value.channels.includes('whatsapp')) rate += 5
//   if (newCampaign.value.channels.includes('linkedin')) rate += 3
//   if (newCampaign.value.rules.noReplyFollowup) rate += 4
//   return Math.min(rate, 18)
// })

const formatNumber = (n) => n >= 1000 ? (n / 1000).toFixed(1) + 'K' : n.toLocaleString()
const getStatusLabel = (s) => ({ active: '进行中', paused: '已暂停', completed: '已完成' }[s] || s)
const getChannelIcon = (c) => ({ '邮件': 'fas fa-envelope', 'WhatsApp': 'fab fa-whatsapp', 'LinkedIn': 'fab fa-linkedin' }[c] || 'fas fa-comment')

const getPriorityLabel = (priority) => ({ high: '高', medium: '中', low: '低' }[priority] || priority)
const getRegionLabel = (region) => ({ 'middle-east': '中东', 'europe': '欧洲', 'north-america': '北美', 'southeast-asia': '东南亚', 'africa': '非洲', 'south-america': '南美' }[region] || '全部地区')
const getIndustryLabel = (industry) => ({ 'datacenter': '数据中心', 'consumer': '消费电子', 'distributor': '电子分销', 'retail': '零售', 'manufacturing': '制造业' }[industry] || '全部行业')
const getChannelName = (id) => ({ email: '邮件营销', whatsapp: 'WhatsApp', linkedin: 'LinkedIn', wechat: '微信企业号' }[id] || id)

const generateSubjectAI = () => {
  showSubjectSuggestions.value = !showSubjectSuggestions.value
  if (showSubjectSuggestions.value) toast('已生成推荐主题', 'success')
}

const openAIGenerator = (campaign) => { 
  selectedCampaign.value = campaign
  showAIModal.value = true 
}

const generateEmail = () => {
  isGenerating.value = true
  setTimeout(() => {
    generatedEmail.value = {
      subject: 'Reliable SSD Solutions for Your Growing Business',
      body: `Dear [Contact Name],<br><br>I hope this email finds you well. I noticed that <strong>[Company Name]</strong> specializes in SSD distribution, and I wanted to explore potential collaboration opportunities.<br><br>Our company has been a leading SSD manufacturer for over 15 years:<br><br>• <strong>Competitive Pricing:</strong> Factory-direct pricing<br>• <strong>Quality Assurance:</strong> ISO 9001 certified, 3-year warranty<br>• <strong>Fast Delivery:</strong> 15-20 days to major ports<br><br>I'd love to schedule a quick call. Would next Tuesday work?`,
      wordCount: 95,
      readTime: 30,
      readability: 8.5
    }
    isGenerating.value = false
    toast('邮件已生成', 'success')
  }, 2000)
}

const copyEmail = () => {
  const text = generatedEmail.value.body.replace(/<br>/g, '\n').replace(/<strong>/g, '').replace(/<\/strong>/g, '')
  navigator.clipboard.writeText(`Subject: ${generatedEmail.value.subject}\n\n${text}`)
  toast('已复制到剪贴板', 'success')
}

const useEmail = () => { showAIModal.value = false; toast('邮件已应用到活动', 'success') }
const useTemplate = (tpl) => { showTemplatesModal.value = false; toast(`已应用模板: ${tpl.subject}`, 'success') }
const toggleCampaign = (c) => { c.status = c.status === 'paused' ? 'active' : 'paused'; toast(c.status === 'paused' ? '已暂停' : '已恢复', 'success') }
const showCampaignDetail = (campaign) => {
  selectedCampaign.value = campaign
  showCampaignDetailModal.value = true
}

const showAllInteractions = () => {
  // 生成完整的互动列表
  selectedCampaignInteractions.value = [
    { id: 1, name: 'Mohammed Al-Rashid', email: 'mohammed@alrashid.ae', avatar: 'M', type: 'reply', action: '回复邮件', content: '回复了您的邮件，询问价格和交期', time: '10分钟前', sentiment: '正面', priority: '高', interested: true, company: 'Al-Rashid Trading Co.', phone: '+971-50-1234567' },
    { id: 2, name: 'Ahmed Hassan', email: 'ahmed@hassan-trading.ae', avatar: 'A', type: 'open', action: '打开邮件', content: '打开了您的邮件', time: '1小时前', sentiment: '中立', priority: '中', interested: false, company: 'Hassan Trading LLC', phone: '+971-50-2345678' },
    { id: 3, name: 'Sarah Williams', email: 'sarah@techsolutions.uk', avatar: 'S', type: 'click', action: '点击链接', content: '点击了邮件中的产品链接', time: '3小时前', sentiment: '正面', priority: '中', interested: true, company: 'Tech Solutions Ltd', phone: '+44-20-12345678' },
    { id: 4, name: 'John Chen', email: 'john@datacenter.com', avatar: 'J', type: 'reply', action: '回复邮件', content: '希望了解更多关于企业级SSD的详细信息', time: '5小时前', sentiment: '正面', priority: '高', interested: true, company: 'Global Data Center', phone: '+1-555-1234567' },
    { id: 5, name: 'Maria Garcia', email: 'maria@distributor.mx', avatar: 'M', type: 'open', action: '打开邮件', content: '打开了邮件但未回复', time: '昨天', sentiment: '中立', priority: '低', interested: false, company: 'Garcia Distributors', phone: '+52-55-12345678' },
    { id: 6, name: 'David Kim', email: 'david@electronics.kr', avatar: 'D', type: 'click', action: '点击链接', content: '查看了产品规格页面', time: '昨天', sentiment: '正面', priority: '中', interested: true, company: 'Kim Electronics', phone: '+82-2-12345678' },
    { id: 7, name: 'Lisa Brown', email: 'lisa@retail.au', avatar: 'L', type: 'reply', action: '回复邮件', content: '询问批发价格和交货时间', time: '2天前', sentiment: '正面', priority: '高', interested: true, company: 'Brown Retail Group', phone: '+61-2-98765432' },
    { id: 8, name: 'Peter Mueller', email: 'peter@manufacturing.de', avatar: 'P', type: 'open', action: '打开邮件', content: '多次打开邮件查看产品信息', time: '3天前', sentiment: '中立', priority: '低', interested: false, company: 'Mueller Manufacturing', phone: '+49-30-12345678' },
    { id: 9, name: 'Ahmed Al-Sayed', email: 'ahmed@alsayed.ae', avatar: 'A', type: 'click', action: '点击链接', content: '下载了产品目录PDF', time: '4天前', sentiment: '正面', priority: '中', interested: true, company: 'Al-Sayed Group', phone: '+971-4-1234567' },
    { id: 10, name: 'Emma Wilson', email: 'emma@techstartup.us', avatar: 'E', type: 'reply', action: '回复邮件', content: '表示对样品感兴趣，请求寄送样品', time: '5天前', sentiment: '正面', priority: '高', interested: true, company: 'Wilson Tech Startup', phone: '+1-415-1234567' }
  ]
  showInteractionsModal.value = true
}

const toast = (msg, type = 'success') => {
  toastMessage.value = msg; toastType.value = type; showToast.value = true
  setTimeout(() => { showToast.value = false }, 3000)
}

// 历史活动数据
const historyCampaigns = ref([
  { id: 101, name: '2025冬季中东潜客开发', dateRange: '2025-12-01 至 2025-12-31', owner: '张经理', status: 'completed', icon: 'fas fa-snowflake', iconBg: 'rgba(99, 102, 241, 0.2)', iconColor: 'var(--primary)', channels: ['邮件', 'LinkedIn'], stats: { sent: 1256, opened: 590, openRate: 47, replied: 148, replyRate: 12, clicked: 320, opportunities: 28 } },
  { id: 102, name: '欧洲数据中心展会跟进', dateRange: '2025-11-15 至 2025-12-15', owner: '李主管', status: 'completed', icon: 'fas fa-building', iconBg: 'rgba(16, 185, 129, 0.2)', iconColor: 'var(--success)', channels: ['邮件', 'WhatsApp'], stats: { sent: 856, opened: 478, openRate: 56, replied: 126, replyRate: 15, clicked: 198, opportunities: 22 } },
  { id: 103, name: '黑色星期五促销', dateRange: '2025-11-25 至 2025-11-30', owner: '王小明', status: 'completed', icon: 'fas fa-tag', iconBg: 'rgba(245, 158, 11, 0.2)', iconColor: 'var(--warning)', channels: ['邮件'], stats: { sent: 2340, opened: 890, openRate: 38, replied: 234, replyRate: 10, clicked: 456, opportunities: 45 } },
  { id: 104, name: '北美市场调研活动', dateRange: '2025-10-01 至 2025-10-31', owner: '张经理', status: 'completed', icon: 'fas fa-flag-usa', iconBg: 'rgba(6, 182, 212, 0.2)', iconColor: 'var(--info)', channels: ['邮件', 'LinkedIn'], stats: { sent: 678, opened: 298, openRate: 44, replied: 68, replyRate: 10, clicked: 145, opportunities: 12 } },
  { id: 105, name: '春节客户关怀', dateRange: '2025-01-20 至 2025-02-10', owner: '李主管', status: 'completed', icon: 'fas fa-gift', iconBg: 'rgba(236, 72, 153, 0.2)', iconColor: '#ec4899', channels: ['邮件', 'WhatsApp'], stats: { sent: 1567, opened: 1020, openRate: 65, replied: 312, replyRate: 20, clicked: 380, opportunities: 35 } },
  { id: 106, name: '2025广交会客户回访', dateRange: '2025-10-15 至 2025-11-15', owner: '张经理', status: 'completed', icon: 'fas fa-handshake', iconBg: 'rgba(16, 185, 129, 0.2)', iconColor: 'var(--success)', channels: ['邮件', 'WhatsApp', 'LinkedIn'], stats: { sent: 1567, opened: 980, openRate: 63, replied: 298, replyRate: 19, clicked: 456, opportunities: 52 } },
  { id: 107, name: '中东斋月营销活动', dateRange: '2025-03-01 至 2025-03-31', owner: '李主管', status: 'completed', icon: 'fas fa-star-and-crescent', iconBg: 'rgba(139, 92, 246, 0.2)', iconColor: 'var(--secondary)', channels: ['邮件'], stats: { sent: 890, opened: 512, openRate: 58, replied: 145, replyRate: 16, clicked: 234, opportunities: 28 } },
  { id: 108, name: 'Q3季度产品促销', dateRange: '2025-07-01 至 2025-09-30', owner: '王小明', status: 'completed', icon: 'fas fa-percent', iconBg: 'rgba(239, 68, 68, 0.2)', iconColor: 'var(--danger)', channels: ['邮件', 'WhatsApp'], stats: { sent: 3456, opened: 1382, openRate: 40, replied: 345, replyRate: 10, clicked: 692, opportunities: 65 } },
  { id: 109, name: '东南亚市场开拓', dateRange: '2025-06-01 至 2025-08-31', owner: '张经理', status: 'completed', icon: 'fas fa-map-marker-alt', iconBg: 'rgba(6, 182, 212, 0.2)', iconColor: 'var(--info)', channels: ['邮件', 'LinkedIn'], stats: { sent: 1234, opened: 567, openRate: 46, replied: 98, replyRate: 8, clicked: 189, opportunities: 18 } },
  { id: 110, name: '年度客户答谢活动', dateRange: '2025-12-15 至 2026-01-05', owner: '李主管', status: 'completed', icon: 'fas fa-glass-cheers', iconBg: 'rgba(251, 191, 36, 0.2)', iconColor: '#FBBF24', channels: ['邮件', 'WhatsApp'], stats: { sent: 2890, opened: 2023, openRate: 70, replied: 578, replyRate: 20, clicked: 867, opportunities: 78 } }
])

const totalHistoricalSent = computed(() => historyCampaigns.value.reduce((sum, c) => sum + c.stats.sent, 0).toLocaleString())
const avgHistoricalOpenRate = computed(() => Math.round(historyCampaigns.value.reduce((sum, c) => sum + c.stats.openRate, 0) / historyCampaigns.value.length))
const avgHistoricalReplyRate = computed(() => Math.round(historyCampaigns.value.reduce((sum, c) => sum + c.stats.replyRate, 0) / historyCampaigns.value.length))
const totalHistoricalOpportunities = computed(() => historyCampaigns.value.reduce((sum, c) => sum + c.stats.opportunities, 0))

const filteredHistoryCampaigns = computed(() => {
  return historyCampaigns.value.filter(c => {
    const matchSearch = !historySearch.value || c.name.toLowerCase().includes(historySearch.value.toLowerCase())
    const matchStatus = !historyFilter.value.status || c.status === historyFilter.value.status
    return matchSearch && matchStatus
  })
})

// 模板数据
const allTemplates = ref([
  { id: 1, channel: 'email', type: '介绍信', language: 'English', subject: 'Reliable SSD Solutions for Your Business', preview: 'Hi [Name], I noticed your company specializes in SSD distribution...', openRate: 48, replyRate: 12, usedCount: 156, favorite: true, tags: ['SSD', '潜客开发'], body: '<p>Hi [Name],</p><p>I noticed your company specializes in <strong>SSD distribution</strong>...</p>' },
  { id: 2, channel: 'email', type: '跟进邮件', language: 'English', subject: 'Following Up on Our Conversation', preview: 'Hi [Name], I wanted to follow up on my previous email...', openRate: 35, replyRate: 8, usedCount: 89, favorite: false, tags: ['跟进'], body: '<p>Hi [Name],</p><p>I wanted to follow up...</p>' },
  { id: 3, channel: 'email', type: '产品推荐', language: 'English', subject: 'New Enterprise SSD Line', preview: 'Hi [Name], Exciting news! Our new enterprise SSD...', openRate: 52, replyRate: 15, usedCount: 234, favorite: true, tags: ['产品', '新品'], body: '<p>Hi [Name],</p><p>Exciting news! Our new <strong>enterprise SSD line</strong>...</p>' },
  { id: 4, channel: 'email', type: '报价邮件', language: 'English', subject: 'Competitive Quote for Your Order', preview: 'Hi [Name], As discussed, please find our quote...', openRate: 42, replyRate: 18, usedCount: 178, favorite: false, tags: ['报价'], body: '<p>Hi [Name],</p><p>As discussed, please find our quote...</p>' },
  { id: 5, channel: 'email', type: '节日祝福', language: '中文', subject: '【节日祝福】感谢您一直以来的支持', preview: '尊敬的客户，新春佳节即将来临...', openRate: 65, replyRate: 20, usedCount: 345, favorite: true, tags: ['节日', '中国'], body: '<p>尊敬的客户：</p><p>新春佳节即将来临，感谢您...</p>' },
  { id: 6, channel: 'whatsapp', type: '即时消息', language: 'English', subject: 'Quick Chat About SSD', preview: 'Hi [Name]! 👋 I came across your profile...', openRate: 78, replyRate: 35, usedCount: 456, favorite: true, tags: ['WhatsApp', '即时'], body: 'Hi [Name]! 👋 I came across your profile...' },
  { id: 7, channel: 'linkedin', type: '连接请求', language: 'English', subject: 'Connection Request - Storage Solutions', preview: 'Hi [Name], I noticed we share similar interests...', openRate: 52, replyRate: 25, usedCount: 567, favorite: true, tags: ['LinkedIn', '连接'], body: 'Hi [Name], I noticed we share similar interests...' },
  { id: 8, channel: 'linkedin', type: '私信', language: 'English', subject: 'Quick Question About Enterprise Storage', preview: 'Hi [Name], I saw your recent post about data centers...', openRate: 48, replyRate: 22, usedCount: 345, favorite: false, tags: ['LinkedIn', '私信'], body: 'Hi [Name], I saw your recent post about data centers...' }
])

const filteredTemplates = computed(() => {
  let templates = allTemplates.value
  if (templateTab.value !== 'all') {
    if (templateTab.value === 'my') {
      templates = templates.filter(t => t.favorite)
    } else {
      templates = templates.filter(t => t.channel === templateTab.value)
    }
  }
  if (templateSearch.value) {
    const search = templateSearch.value.toLowerCase()
    templates = templates.filter(t => t.subject.toLowerCase().includes(search) || t.preview.toLowerCase().includes(search))
  }
  return templates
})

const avgTemplateOpenRate = computed(() => Math.round(allTemplates.value.reduce((sum, t) => sum + t.openRate, 0) / allTemplates.value.length))
const avgTemplateReplyRate = computed(() => Math.round(allTemplates.value.reduce((sum, t) => sum + t.replyRate, 0) / allTemplates.value.length))

const aiRecommendedTemplates = computed(() => [
  { id: 1, channel: 'email', type: '介绍信', language: 'English', subject: 'Reliable SSD Solutions for Your Business', openRate: 48, replyRate: 12, matchScore: 95 },
  { id: 6, channel: 'whatsapp', type: '即时消息', language: 'English', subject: 'Quick Chat About SSD', openRate: 78, replyRate: 35, matchScore: 88 },
  { id: 7, channel: 'linkedin', type: '连接请求', language: 'English', subject: 'Connection Request', openRate: 52, replyRate: 25, matchScore: 82 }
])

// 历史活动方法
const duplicateCampaign = (campaign) => {
  addMarketingRef.value.duplicateCampaign(campaign)
}

const viewHistoryDetail = (campaign) => {
  selectedHistoryCampaign.value = campaign
  showHistoryDetailModal.value = true
}

const exportHistoryReport = (campaign) => {
  toast(`正在导出活动报告`, 'success')
}

const exportAllHistory = () => {
  toast('正在导出全部历史报告', 'success')
}

// 模板方法
const getTemplateChannelIcon = (channel) => {
  const icons = { email: 'fas fa-envelope', whatsapp: 'fab fa-whatsapp', linkedin: 'fab fa-linkedin' }
  return icons[channel] || 'fas fa-file-alt'
}

const toggleFavorite = (tpl) => {
  tpl.favorite = !tpl.favorite
  toast(tpl.favorite ? '已添加收藏' : '已取消收藏', 'success')
}

const previewTemplate = (tpl) => {
  previewingTemplate.value = tpl
  showTemplatePreview.value = true
}

const importTemplates = () => {
  toast('模板导入功能开发中', 'info')
}

const openOpenedCustomers = (campaign) => {
  selectedOpenedCampaign.value = campaign
  showOpenedCustomersModal.value = true
}

const openReplyReview = (campaign) => {
  selectedReplyReview.value = campaign
  showReplyReviewModal.value = true
}

const openInterventionModal = (campaign) => {
  selectedIntervention.value = campaign
  showInterventionModal.value = true
}

const approveReply = (reply) => {
  reply.status = 'approved'
  toast(`已批准 ${reply.name} 的回复，将由销售人员跟进`, 'success')
}

const rejectReply = (reply) => {
  reply.status = 'rejected'
  toast(`已拒绝 ${reply.name} 的回复`, 'success')
}

const assignToSales = (reply) => {
  reply.status = 'assigned'
  toast(`已分配给销售人员，等待跟进`, 'success')
}

const approveReplyWithReview = (reply, reviewer) => {
  reply.status = 'approved'
  reply.reviewedBy = reviewer
  reply.reviewTime = new Date().toLocaleString('zh-CN')
  toast(`已批准 ${reply.name} 的回复`, 'success')
}

const rejectReplyWithReason = (reply, reason) => {
  reply.status = 'rejected'
  reply.reviewedBy = '当前用户'
  reply.reviewTime = new Date().toLocaleString('zh-CN')
  toast(`已拒绝 ${reply.name} 的回复，原因: ${reason}`, 'success')
}

const assignReplyToSales = (reply, salesPerson) => {
  reply.status = 'assigned'
  reply.assignedTo = salesPerson
  reply.reviewedBy = '当前用户'
  reply.reviewTime = new Date().toLocaleString('zh-CN')
  toast(`已将 ${reply.name} 分配给 ${salesPerson}`, 'success')
}

const createIntervention = (type, reason) => {
  const newIntervention = {
    id: interventions.value.length + 1,
    campaignId: selectedIntervention.value.id,
    type: type,
    reason: reason,
    affectedCount: selectedIntervention.value.stats.sent,
    status: 'active',
    createdTime: new Date().toLocaleString('zh-CN'),
    createdBy: '当前用户'
  }
  interventions.value.push(newIntervention)
  toast(`已创建人工干预: ${type}`, 'success')
  showInterventionModal.value = false
}

const contactCustomer = (customer) => {
  toast(`正在联系 ${customer.name}...`, 'success')
}

const getSentimentColor = (sentiment) => {
  const colors = { '正面': '#10B981', '中立': '#F59E0B', '负面': '#EF4444' }
  return colors[sentiment] || '#6366F1'
}

const protectCustomer = (customer) => {
  customer.protected = true
  customer.protectionReason = '高价值客户'
  customer.interventionStatus = 'assigned-to-sales'
  protectedCustomersList.value.push({
    id: protectedCustomersList.value.length + 1,
    name: customer.name,
    email: customer.email,
    protectionLevel: customer.value === '高价值' ? '高' : '中',
    reason: customer.value === '高价值' ? '高价值客户' : '活跃客户',
    annualValue: customer.annualPurchase,
    status: 'active',
    protectedSince: new Date().toLocaleDateString('zh-CN'),
    assignedSalesRep: '待分配'
  })
  toast(`已将 ${customer.name} 添加到保护白名单`, 'success')
}

const unprotectCustomer = (customer) => {
  customer.protected = false
  customer.protectionReason = ''
  customer.interventionStatus = 'auto-follow'
  protectedCustomersList.value = protectedCustomersList.value.filter(c => c.email !== customer.email)
  toast(`已将 ${customer.name} 从保护白名单中移除`, 'success')
}

const assignToSalesRep = (customer, salesRep) => {
  customer.interventionStatus = 'assigned-to-sales'
  toast(`已分配 ${customer.name} 给销售人员 ${salesRep}`, 'success')
}

const pauseCampaignForCustomer = (customer) => {
  customer.interventionStatus = 'paused'
  toast(`已暂停向 ${customer.name} 发送营销邮件`, 'success')
}

const resumeCampaignForCustomer = (customer) => {
  customer.interventionStatus = 'auto-follow'
  toast(`已恢复向 ${customer.name} 发送营销邮件`, 'success')
}

// 活动详情方法
const openCampaignDetailModal = (campaign) => {
  selectedCampaign.value = campaign
  showCampaignDetailModal.value = true
}

const getChannelStyleByName = (ch) => {
  const styles = {
    '邮件': { background: 'rgba(99, 102, 241, 0.2)', color: 'var(--primary)' },
    'WhatsApp': { background: 'rgba(37, 211, 102, 0.2)', color: '#25D366' },
    'LinkedIn': { background: 'rgba(10, 102, 194, 0.2)', color: '#0A66C2' },
    '微信': { background: 'rgba(7, 193, 96, 0.2)', color: '#07C160' }
  }
  return styles[ch] || { background: 'rgba(99, 102, 241, 0.2)', color: 'var(--primary)' }
}

const exportCampaignReport = (campaign) => {
  toast(`正在导出"${campaign.name}"报告`, 'success')
}

const editCampaign = (campaign) => {
  showCampaignDetailModal.value = false
  toast('正在打开活动编辑...', 'info')
}
</script>

<style scoped>
 @import '../assets/styles/marketing.css';
</style>
