<template>
    <div v-if="showCreateModal" class="modal-overlay" @click.self="closeCreateModal">
        <div class="modal create-modal">
            <div class="modal-header">
                <div class="modal-title">
                    <i class="fas fa-plus-circle"></i> 创建营销活动
                </div>
                <button class="modal-close" @click="closeCreateModal">
                    <i class="fas fa-times"></i>
                </button>
            </div>

            <div class="modal-body">
                <!-- Step Indicator -->
                <div class="step-indicator">
                    <div class="step" :class="{ active: currentStep >= 1, completed: currentStep > 1 }">
                        <div class="step-number">1</div>
                        <div class="step-label">基本信息</div>
                    </div>
                    <div class="step-line" :class="{ active: currentStep > 1 }"></div>
                    <div class="step" :class="{ active: currentStep >= 2, completed: currentStep > 2 }">
                        <div class="step-number">2</div>
                        <div class="step-label">目标客户</div>
                    </div>
                    <div class="step-line" :class="{ active: currentStep > 2 }"></div>
                    <div class="step" :class="{ active: currentStep >= 3, completed: currentStep > 3 }">
                        <div class="step-number">3</div>
                        <div class="step-label">触达渠道</div>
                    </div>
                    <div class="step-line" :class="{ active: currentStep > 3 }"></div>
                    <div class="step" :class="{ active: currentStep >= 4, completed: currentStep > 4 }">
                        <div class="step-number">4</div>
                        <div class="step-label">自动化规则</div>
                    </div>
                    <div class="step-line" :class="{ active: currentStep > 4 }"></div>
                    <div class="step" :class="{ active: currentStep >= 5 }">
                        <div class="step-number">5</div>
                        <div class="step-label">预览确认</div>
                    </div>
                </div>

                <!-- Step 1: Basic Info -->
                <div v-if="currentStep === 1" class="step-content">
                    <h4><i class="fas fa-info-circle"></i> 活动基本信息</h4>
                    <div class="form-group">
                        <label class="form-label">活动名称 <span class="required">*</span></label>
                        <input type="text" class="form-input" v-model="newCampaign.name"
                            placeholder="例如：2026春季中东客户开发活动" />
                        <div class="form-hint" v-if="!newCampaign.name">
                            建议格式：时间+区域+目标+活动类型
                        </div>
                    </div>
                    <div class="form-row">
                        <div class="form-group">
                            <label class="form-label">活动类型</label>
                            <select class="form-select" v-model="newCampaign.type">
                                <option value="prospect">潜客开发</option>
                                <option value="nurture">客户培育</option>
                                <option value="reactivate">客户唤醒</option>
                                <option value="promote">产品推广</option>
                                <option value="seasonal">节日营销</option>
                                <option value="exhibition">展会跟进</option>
                            </select>
                        </div>
                        <div class="form-group">
                            <label class="form-label">优先级</label>
                            <select class="form-select" v-model="newCampaign.priority">
                                <option value="urgent">紧急</option>
                                <option value="high">高优先</option>
                                <option value="medium">中等</option>
                                <option value="low">低优先</option>
                            </select>
                        </div>
                    </div>
                    <div class="form-row">
                        <div class="form-group">
                            <label class="form-label">开始日期</label>
                            <input type="date" class="form-input" v-model="newCampaign.startDate" />
                        </div>
                        <div class="form-group">
                            <label class="form-label">结束日期</label>
                            <input type="date" class="form-input" v-model="newCampaign.endDate" />
                        </div>
                    </div>
                    <div class="form-row">
                        <div class="form-group">
                            <label class="form-label">负责人</label>
                            <select class="form-select" v-model="newCampaign.owner">
                                <option value="">选择负责人</option>
                                <option value="sales1">张经理</option>
                                <option value="sales2">李主管</option>
                                <option value="sales3">王小明</option>
                            </select>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="form-label">活动描述</label>
                        <textarea class="form-textarea" v-model="newCampaign.description" rows="3"
                            placeholder="描述本次营销活动的目标和策略..."></textarea>
                    </div>
                    <div class="form-group">
                        <label class="form-label">活动目标</label>
                        <div class="goal-inputs">
                            <div class="goal-item">
                                <i class="fas fa-envelope"></i>
                                <input type="number" class="goal-input" v-model="newCampaign.goals.sent"
                                    placeholder="0" />
                                <span>发送量</span>
                            </div>
                            <div class="goal-item">
                                <i class="fas fa-envelope-open"></i>
                                <input type="number" class="goal-input" v-model="newCampaign.goals.openRate"
                                    placeholder="0" />
                                <span>% 打开率</span>
                            </div>
                            <div class="goal-item">
                                <i class="fas fa-reply"></i>
                                <input type="number" class="goal-input" v-model="newCampaign.goals.replyRate"
                                    placeholder="0" />
                                <span>% 回复率</span>
                            </div>
                        </div>
                    </div>
                    <div class="ai-suggest-section" v-if="newCampaign.name">
                        <h5><i class="fas fa-lightbulb"></i> AI 建议</h5>
                        <div class="ai-suggestions">
                            <div class="ai-suggestion" @click="applySuggestion('name')">
                                <i class="fas fa-magic"></i>
                                <span>根据类型生成最佳活动名称</span>
                            </div>
                            <div class="ai-suggestion" @click="applySuggestion('desc')">
                                <i class="fas fa-file-alt"></i>
                                <span>智能生成活动描述和策略</span>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Step 2: Target Customers -->
                <div v-if="currentStep === 2" class="step-content">
                    <h4><i class="fas fa-users"></i> 目标客户群</h4>

                    <!-- AI智能推荐 -->
                    <div class="ai-recommend-section">
                        <div class="ai-recommend-header">
                            <i class="fas fa-robot"></i>
                            <span>AI 智能推荐客户</span>
                        </div>
                        <div class="ai-recommend-tags">
                            <span class="ai-tag" :class="{ active: newCampaign.aiRecommend === 'high-value' }"
                                @click="newCampaign.aiRecommend = 'high-value'">
                                <i class="fas fa-crown"></i> 高价值客户
                            </span>
                            <span class="ai-tag" :class="{ active: newCampaign.aiRecommend === 'recent' }"
                                @click="newCampaign.aiRecommend = 'recent'">
                                <i class="fas fa-clock"></i> 最近互动
                            </span>
                            <span class="ai-tag" :class="{ active: newCampaign.aiRecommend === 'similar' }"
                                @click="newCampaign.aiRecommend = 'similar'">
                                <i class="fas fa-copy"></i> 相似客户
                            </span>
                            <span class="ai-tag" :class="{ active: newCampaign.aiRecommend === 'dormant' }"
                                @click="newCampaign.aiRecommend = 'dormant'">
                                <i class="fas fa-moon"></i> 沉睡唤醒
                            </span>
                        </div>
                    </div>

                    <div class="quick-segments">
                        <div v-for="seg in segmentOptions" :key="seg.id" class="segment-option"
                            :class="{ selected: newCampaign.segment === seg.id }" @click="newCampaign.segment = seg.id">
                            <i :class="seg.icon"></i>
                            <div class="segment-info">
                                <div class="segment-name">{{ seg.name }}</div>
                                <div class="segment-count">{{ seg.count }} 位客户</div>
                            </div>
                            <div class="segment-check" v-if="newCampaign.segment === seg.id">
                                <i class="fas fa-check-circle"></i>
                            </div>
                        </div>
                    </div>

                    <div class="advanced-filters">
                        <div class="filter-header">
                            <h5><i class="fas fa-filter"></i> 高级筛选</h5>
                            <button class="btn-link" @click="clearFilters">清除筛选</button>
                        </div>
                        <div class="filter-row">
                            <div class="form-group">
                                <label class="form-label">地区</label>
                                <select class="form-select" v-model="newCampaign.filters.region">
                                    <option value="">全部地区</option>
                                    <option value="middle-east">中东</option>
                                    <option value="europe">欧洲</option>
                                    <option value="north-america">北美</option>
                                    <option value="southeast-asia">东南亚</option>
                                    <option value="africa">非洲</option>
                                    <option value="south-america">南美</option>
                                </select>
                            </div>
                            <div class="form-group">
                                <label class="form-label">行业</label>
                                <select class="form-select" v-model="newCampaign.filters.industry">
                                    <option value="">全部行业</option>
                                    <option value="datacenter">数据中心</option>
                                    <option value="consumer">消费电子</option>
                                    <option value="distributor">电子分销</option>
                                    <option value="retail">零售</option>
                                    <option value="manufacturing">制造业</option>
                                </select>
                            </div>
                        </div>
                        <div class="filter-row">
                            <div class="form-group">
                                <label class="form-label">意向分数</label>
                                <select class="form-select" v-model="newCampaign.filters.scoreRange">
                                    <option value="">不限</option>
                                    <option value="high">80-100分</option>
                                    <option value="medium">60-79分</option>
                                    <option value="low">40-59分</option>
                                </select>
                            </div>
                            <div class="form-group">
                                <label class="form-label">客户规模</label>
                                <select class="form-select" v-model="newCampaign.filters.companySize">
                                    <option value="">不限</option>
                                    <option value="large">大型企业(500+)</option>
                                    <option value="medium">中型企业(100-500)</option>
                                    <option value="small">小微企业(<100)</option>
                                </select>
                            </div>
                        </div>
                        <!-- 自定义关键词搜索 -->
                        <div class="form-group">
                            <label class="form-label">关键词搜索</label>
                            <div class="keyword-search">
                                <input type="text" class="form-input" v-model="newCampaign.filters.keyword"
                                    placeholder="搜索公司名、联系人、产品关键词..." />
                                <button class="btn btn-secondary">
                                    <i class="fas fa-search"></i>
                                </button>
                            </div>
                        </div>
                        <!-- 已选客户标签 -->
                        <div class="selected-tags" v-if="newCampaign.filters.selectedTags.length > 0">
                            <span v-for="tag in newCampaign.filters.selectedTags" :key="tag" class="selected-tag">
                                {{ tag }}
                                <i class="fas fa-times" @click="removeTag(tag)"></i>
                            </span>
                        </div>
                    </div>

                    <div class="preview-count">
                        <i class="fas fa-users"></i>
                        <div class="count-info">
                            <div class="count-value">
                                已选择 <strong>{{ selectedCustomerCount }}</strong> 位客户
                            </div>
                            <div class="count-detail">基于当前筛选条件</div>
                        </div>
                        <button class="btn btn-sm btn-outline" @click="showCustomerPreview = true">
                            <i class="fas fa-eye"></i> 预览客户
                        </button>
                    </div>

                    <!-- 客户来源分布 -->
                    <div class="customer-source">
                        <h5><i class="fas fa-chart-pie"></i> 客户来源分布</h5>
                        <div class="source-bars">
                            <div class="source-item">
                                <span class="source-label">AI推荐</span>
                                <div class="source-bar">
                                    <div class="source-fill" style="width: 45%; background: var(--primary)"></div>
                                </div>
                                <span class="source-value">45%</span>
                            </div>
                            <div class="source-item">
                                <span class="source-label">展会获取</span>
                                <div class="source-bar">
                                    <div class="source-fill" style="width: 25%; background: var(--success)"></div>
                                </div>
                                <span class="source-value">25%</span>
                            </div>
                            <div class="source-item">
                                <span class="source-label">官网注册</span>
                                <div class="source-bar">
                                    <div class="source-fill" style="width: 20%; background: var(--info)"></div>
                                </div>
                                <span class="source-value">20%</span>
                            </div>
                            <div class="source-item">
                                <span class="source-label">转介绍</span>
                                <div class="source-bar">
                                    <div class="source-fill" style="width: 10%; background: var(--warning)"></div>
                                </div>
                                <span class="source-value">10%</span>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Step 3: Channels -->
                <div v-if="currentStep === 3" class="step-content">
                    <h4><i class="fas fa-bullhorn"></i> 触达渠道配置</h4>

                    <div class="channel-grid">
                        <div v-for="ch in availableChannels" :key="ch.id" class="channel-card" :class="{
                            selected: newCampaign.channels.includes(ch.id),
                            disabled: !ch.enabled,
                        }" @click="ch.enabled && toggleChannel(ch.id)">
                            <div class="channel-icon" :style="{ background: ch.iconBg, color: ch.iconColor }">
                                <i :class="ch.icon"></i>
                            </div>
                            <div class="channel-info">
                                <div class="channel-name">{{ ch.name }}</div>
                                <div class="channel-desc">{{ ch.description }}</div>
                                <div class="channel-stats-mini">
                                    <span><i class="fas fa-chart-line"></i> {{ ch.avgOpenRate }}%
                                        打开率</span>
                                </div>
                            </div>
                            <div class="channel-check" v-if="newCampaign.channels.includes(ch.id)">
                                <i class="fas fa-check-circle"></i>
                            </div>
                        </div>
                    </div>

                    <!-- 邮件设置 -->
                    <div v-if="newCampaign.channels.includes('email')" class="channel-settings">
                        <h5><i class="fas fa-envelope"></i> 邮件设置</h5>
                        <div class="form-row">
                            <div class="form-group">
                                <label class="form-label">发件邮箱</label>
                                <select class="form-select" v-model="newCampaign.emailSender">
                                    <option>sales@company.com</option>
                                    <option>marketing@company.com</option>
                                    <option>support@company.com</option>
                                </select>
                            </div>
                            <div class="form-group">
                                <label class="form-label">发送时间</label>
                                <select class="form-select" v-model="newCampaign.emailSendTime">
                                    <option value="optimal">AI推荐最优时间</option>
                                    <option value="morning">上午 9:00-11:00</option>
                                    <option value="afternoon">下午 14:00-16:00</option>
                                    <option value="evening">晚上 19:00-21:00</option>
                                </select>
                            </div>
                        </div>
                        <div class="form-row">
                            <div class="form-group">
                                <label class="form-label">生成方式</label>
                                <select class="form-select" v-model="newCampaign.emailTemplate">
                                    <option value="default">默认模板</option>
                                    <option value="professional">专业商务</option>
                                    <option value="friendly">友好亲切</option>
                                    <option value="minimal">极简风格</option>
                                </select>
                            </div>
                            <div class="form-group">
                                <label class="form-label">每批发送量</label>
                                <select class="form-select" v-model="newCampaign.batchSize">
                                    <option value="50">50封/批</option>
                                    <option value="100">100封/批</option>
                                    <option value="200">200封/批</option>
                                    <option value="500">500封/批</option>
                                </select>
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="form-label">邮件主题 <span class="required">*</span></label>
                            <div class="subject-input-group">
                                <input type="text" class="form-input" v-model="newCampaign.emailSubject"
                                    placeholder="输入邮件主题" />
                                <button class="btn btn-primary" @click="generateSubjectAI">
                                    <i class="fas fa-magic"></i> AI优化
                                </button>
                            </div>
                            <div class="subject-suggestions" v-if="showSubjectSuggestions">
                                <div class="suggestion-header">AI 推荐主题：</div>
                                <div v-for="subj in subjectSuggestions" :key="subj" class="suggestion-item"
                                    @click="selectSubject(subj)">
                                    {{ subj }}
                                </div>
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="form-label">邮件预览文本</label>
                            <input type="text" class="form-input" v-model="newCampaign.emailPreviewText"
                                placeholder="邮件列表中显示的预览文字（可选）" />
                        </div>
                    </div>

                    <!-- WhatsApp设置 -->
                    <div v-if="newCampaign.channels.includes('whatsapp')" class="channel-settings">
                        <h5><i class="fab fa-whatsapp"></i> WhatsApp 设置</h5>
                        <div class="form-row">
                            <div class="form-group">
                                <label class="form-label">发送账号</label>
                                <select class="form-select" v-model="newCampaign.whatsappAccount">
                                    <option>业务账号1</option>
                                    <option>业务账号2</option>
                                </select>
                            </div>
                            <div class="form-group">
                                <label class="form-label">发送间隔</label>
                                <select class="form-select" v-model="newCampaign.whatsappInterval">
                                    <option value="30">30秒/条</option>
                                    <option value="60">1分钟/条</option>
                                    <option value="120">2分钟/条</option>
                                </select>
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="form-label">消息模板</label>
                            <textarea class="form-textarea" v-model="newCampaign.whatsappTemplate" rows="3"
                                placeholder="输入 WhatsApp 消息模板..."></textarea>
                        </div>
                    </div>

                    <!-- LinkedIn设置 -->
                    <div v-if="newCampaign.channels.includes('linkedin')" class="channel-settings">
                        <h5><i class="fab fa-linkedin"></i> LinkedIn 设置</h5>
                        <div class="form-row">
                            <div class="form-group">
                                <label class="form-label">操作类型</label>
                                <select class="form-select" v-model="newCampaign.linkedinAction">
                                    <option value="message">发送消息</option>
                                    <option value="connect">发送连接请求</option>
                                    <option value="inmail">InMail</option>
                                </select>
                            </div>
                            <div class="form-group">
                                <label class="form-label">每日上限</label>
                                <select class="form-select" v-model="newCampaign.linkedinLimit">
                                    <option value="20">20次/天</option>
                                    <option value="30">30次/天</option>
                                    <option value="50">50次/天</option>
                                </select>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Step 4: Automation Rules -->
                <div v-if="currentStep === 4" class="step-content">
                    <h4><i class="fas fa-robot"></i> 自动化规则</h4>

                    <!-- SOP 序列模板 -->
                    <div class="sop-section">
                        <h5><i class="fas fa-magic"></i> SOP 序列模板</h5>
                        <div class="sop-grid">
                            <div v-for="sop in sopTemplates" :key="sop.id" class="sop-card"
                                :class="{ selected: newCampaign.sopTemplate === sop.id }"
                                @click="newCampaign.sopTemplate = sop.id">
                                <div class="sop-icon">{{ sop.icon }}</div>
                                <div class="sop-info">
                                    <div class="sop-name">{{ sop.name }}</div>
                                    <div class="sop-steps">{{ sop.steps }} 步序列</div>
                                    <div class="sop-desc">{{ sop.description }}</div>
                                </div>
                                <div class="sop-check" v-if="newCampaign.sopTemplate === sop.id">
                                    <i class="fas fa-check-circle"></i>
                                </div>
                            </div>
                        </div>
                        <!-- SOP 预览 -->
                        <div class="sop-preview" v-if="selectedSopTemplate">
                            <div class="sop-preview-header">
                                <span>{{ selectedSopTemplate.name }} - 序列步骤预览</span>
                                <button class="btn-link" @click="editSopTemplate">
                                    自定义
                                </button>
                            </div>
                            <div class="sop-timeline">
                                <div v-for="(step, idx) in selectedSopTemplate.stepsDetail" :key="idx" class="sop-step">
                                    <div class="sop-step-marker">{{ idx + 1 }}</div>
                                    <div class="sop-step-content">
                                        <div class="sop-step-title">{{ step.title }}</div>
                                        <div class="sop-step-meta">
                                            <span><i class="fas fa-clock"></i> 第{{ step.day }}天</span>
                                            <span><i :class="step.channelIcon"></i>
                                                {{ step.channel }}</span>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- 自动跟进规则 -->
                    <div class="rules-section">
                        <h5><i class="fas fa-sitemap"></i> 跟进规则</h5>
                        <div class="rule-item">
                            <div class="rule-toggle" :class="{ active: newCampaign.rules.noOpenFollowup }" @click="
                                newCampaign.rules.noOpenFollowup =
                                !newCampaign.rules.noOpenFollowup
                                "></div>
                            <div class="rule-content">
                                <div class="rule-title">未打开邮件自动跟进</div>
                                <div class="rule-desc">3天后发送提醒邮件，更换主题行</div>
                            </div>
                            <div class="rule-config" v-if="newCampaign.rules.noOpenFollowup">
                                <select class="mini-select" v-model="newCampaign.rules.noOpenFollowupDays">
                                    <option value="2">2天后</option>
                                    <option value="3">3天后</option>
                                    <option value="5">5天后</option>
                                    <option value="7">7天后</option>
                                </select>
                            </div>
                        </div>
                        <div class="rule-item">
                            <div class="rule-toggle" :class="{ active: newCampaign.rules.noReplyFollowup }" @click="
                                newCampaign.rules.noReplyFollowup =
                                !newCampaign.rules.noReplyFollowup
                                "></div>
                            <div class="rule-content">
                                <div class="rule-title">未回复自动跟进</div>
                                <div class="rule-desc">7天后跟进</div>
                            </div>
                            <div class="rule-config" v-if="newCampaign.rules.noReplyFollowup">
                                <select class="mini-select" v-model="newCampaign.rules.noReplyFollowupDays">
                                    <option value="5">5天后</option>
                                    <option value="7">7天后</option>
                                    <option value="10">10天后</option>
                                </select>
                            </div>
                        </div>
                        <div class="rule-item">
                            <div class="rule-toggle" :class="{ active: newCampaign.rules.stopOnReply }" @click="
                                newCampaign.rules.stopOnReply = !newCampaign.rules.stopOnReply
                                "></div>
                            <div class="rule-content">
                                <div class="rule-title">客户回复后停止自动化</div>
                                <div class="rule-desc">
                                    检测到客户回复后不再发送，转人工跟进
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- A/B 测试 -->
                    <div class="ab-test-section">
                        <div class="ab-test-header">
                            <h5><i class="fas fa-flask"></i> A/B 测试</h5>
                            <div class="rule-toggle" :class="{ active: newCampaign.abTest.enabled }" @click="
                                newCampaign.abTest.enabled = !newCampaign.abTest.enabled
                                "></div>
                        </div>
                        <div class="ab-test-config" v-if="newCampaign.abTest.enabled">
                            <div class="form-row">
                                <div class="form-group">
                                    <label class="form-label">测试变量</label>
                                    <select class="form-select" v-model="newCampaign.abTest.variable">
                                        <option value="subject">邮件主题</option>
                                        <option value="content">邮件内容</option>
                                        <option value="sendTime">发送时间</option>
                                        <option value="fromName">发件人名称</option>
                                    </select>
                                </div>
                                <div class="form-group">
                                    <label class="form-label">测试比例</label>
                                    <select class="form-select" v-model="newCampaign.abTest.ratio">
                                        <option value="50">50% : 50%</option>
                                        <option value="30">30% : 70%</option>
                                        <option value="20">20% : 80%</option>
                                    </select>
                                </div>
                            </div>
                            <div class="form-group">
                                <label class="form-label">胜出条件</label>
                                <select class="form-select" v-model="newCampaign.abTest.winnerCriteria">
                                    <option value="openRate">打开率最高</option>
                                    <option value="clickRate">点击率最高</option>
                                    <option value="replyRate">回复率最高</option>
                                </select>
                            </div>
                            <div class="ab-test-preview">
                                <div class="ab-variant">
                                    <span class="variant-label">A 版本</span>
                                    <span class="variant-desc">{{
                                        newCampaign.emailSubject || "原主题"
                                    }}</span>
                                </div>
                                <div class="ab-variant">
                                    <span class="variant-label">B 版本</span>
                                    <input type="text" class="variant-input" v-model="newCampaign.abTest.variantB"
                                        placeholder="输入测试主题..." />
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- 智能调度 -->
                    <div class="smart-schedule-section">
                        <h5><i class="fas fa-clock"></i> 智能调度</h5>
                        <div class="schedule-options">
                            <label class="schedule-option" :class="{ active: newCampaign.scheduleMode === 'asap' }">
                                <input type="radio" v-model="newCampaign.scheduleMode" value="asap" />
                                <div class="option-content">
                                    <div class="option-title">
                                        <i class="fas fa-bolt"></i> 立即发送
                                    </div>
                                    <div class="option-desc">立即开始执行活动</div>
                                </div>
                            </label>
                            <label class="schedule-option"
                                :class="{ active: newCampaign.scheduleMode === 'scheduled' }">
                                <input type="radio" v-model="newCampaign.scheduleMode" value="scheduled" />
                                <div class="option-content">
                                    <div class="option-title">
                                        <i class="fas fa-calendar"></i> 定时发送
                                    </div>
                                    <div class="option-desc">设置具体开始时间</div>
                                </div>
                            </label>
                            <label class="schedule-option" :class="{ active: newCampaign.scheduleMode === 'optimal' }">
                                <input type="radio" v-model="newCampaign.scheduleMode" value="optimal" />
                                <div class="option-content">
                                    <div class="option-title">
                                        <i class="fas fa-robot"></i> AI最优时间
                                    </div>
                                    <div class="option-desc">根据客户行为自动选择最佳时间</div>
                                </div>
                            </label>
                        </div>
                        <div class="schedule-time-config" v-if="newCampaign.scheduleMode === 'scheduled'">
                            <div class="form-row">
                                <div class="form-group">
                                    <label class="form-label">开始日期</label>
                                    <input type="date" class="form-input" v-model="newCampaign.scheduledDate" />
                                </div>
                                <div class="form-group">
                                    <label class="form-label">开始时间</label>
                                    <input type="time" class="form-input" v-model="newCampaign.scheduledTime" />
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Step 5: Preview -->
                <div v-if="currentStep === 5" class="step-content">
                    <h4><i class="fas fa-eye"></i> 活动预览</h4>

                    <!-- 基本信息 -->
                    <div class="preview-section">
                        <div class="preview-section-header">
                            <h5><i class="fas fa-info-circle"></i> 基本信息</h5>
                            <button class="btn-link" @click="goToStep(1)">编辑</button>
                        </div>
                        <div class="preview-cards">
                            <div class="preview-card">
                                <div class="preview-icon"><i class="fas fa-tag"></i></div>
                                <div class="preview-info">
                                    <div class="preview-label">活动名称</div>
                                    <div class="preview-value">
                                        {{ newCampaign.name || "未命名活动" }}
                                    </div>
                                </div>
                            </div>
                            <div class="preview-card">
                                <div class="preview-icon">
                                    <i class="fas fa-layer-group"></i>
                                </div>
                                <div class="preview-info">
                                    <div class="preview-label">活动类型</div>
                                    <div class="preview-value">
                                        {{ getTypeLabel(newCampaign.type) }}
                                    </div>
                                </div>
                            </div>
                            <div class="preview-card">
                                <div class="preview-icon"><i class="fas fa-flag"></i></div>
                                <div class="preview-info">
                                    <div class="preview-label">优先级</div>
                                    <div class="preview-value" :class="'priority-' + newCampaign.priority">
                                        {{ getPriorityLabel(newCampaign.priority) }}
                                    </div>
                                </div>
                            </div>
                            <div class="preview-card">
                                <div class="preview-icon"><i class="fas fa-user"></i></div>
                                <div class="preview-info">
                                    <div class="preview-label">负责人</div>
                                    <div class="preview-value">
                                        {{ getOwnerName(newCampaign.owner) || "未指定" }}
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- 目标客户 -->
                    <div class="preview-section">
                        <div class="preview-section-header">
                            <h5><i class="fas fa-users"></i> 目标客户</h5>
                            <button class="btn-link" @click="goToStep(2)">编辑</button>
                        </div>
                        <div class="preview-cards">
                            <div class="preview-card">
                                <div class="preview-icon"><i class="fas fa-users"></i></div>
                                <div class="preview-info">
                                    <div class="preview-label">客户数量</div>
                                    <div class="preview-value highlight">
                                        {{ selectedCustomerCount }} 位
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- 触达渠道 -->
                    <div class="preview-section">
                        <div class="preview-section-header">
                            <h5><i class="fas fa-bullhorn"></i> 触达渠道</h5>
                            <button class="btn-link" @click="goToStep(3)">编辑</button>
                        </div>
                        <div class="preview-channels">
                            <div v-for="chId in newCampaign.channels" :key="chId" class="preview-channel-item">
                                <div class="channel-badge" :style="getChannelStyle(chId)">
                                    <i :class="getChannelIconById(chId)"></i>
                                </div>
                                <div class="channel-details">
                                    <div class="channel-name">{{ getChannelName(chId) }}</div>
                                    <div class="channel-config">{{ getChannelConfig(chId) }}</div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- 自动化规则 -->
                    <div class="preview-section">
                        <div class="preview-section-header">
                            <h5><i class="fas fa-robot"></i> 自动化规则</h5>
                            <button class="btn-link" @click="goToStep(4)">编辑</button>
                        </div>
                        <div class="preview-rules">
                            <div class="rule-summary">
                                <span class="rule-badge">SOP: {{ selectedSopTemplate?.name || "未选择" }}</span>
                                <span class="rule-badge" v-if="newCampaign.rules.noOpenFollowup">未打开跟进</span>
                                <span class="rule-badge" v-if="newCampaign.rules.noReplyFollowup">未回复跟进</span>
                                <span class="rule-badge" v-if="newCampaign.rules.stopOnReply">回复后停止</span>
                                <span class="rule-badge highlight" v-if="newCampaign.abTest.enabled">A/B测试</span>
                            </div>
                        </div>
                    </div>

                    <!-- 警告提示 -->
                    <div class="warning-section" v-if="hasWarnings">
                        <h5><i class="fas fa-exclamation-triangle"></i> 注意事项</h5>
                        <div class="warning-list">
                            <div class="warning-item" v-if="selectedCustomerCount > 500">
                                <i class="fas fa-info-circle"></i>
                                <span>目标客户数量较多，建议分批发送以避免被标记为垃圾邮件</span>
                            </div>
                            <div class="warning-item" v-if="!newCampaign.emailSubject">
                                <i class="fas fa-exclamation-circle"></i>
                                <span>邮件主题未设置，请在渠道配置中添加</span>
                            </div>
                            <div class="warning-item" v-if="newCampaign.channels.length === 0">
                                <i class="fas fa-exclamation-circle"></i>
                                <span>尚未选择任何触达渠道</span>
                            </div>
                        </div>
                    </div>

                    <!-- 确认项 -->
                    <div class="confirm-section">
                        <h5><i class="fas fa-check-double"></i> 确认事项</h5>
                        <label class="confirm-item">
                            <input type="checkbox" v-model="confirmChecks.content" />
                            <span class="checkmark"></span>
                            <span>已确认营销内容符合规范</span>
                        </label>
                        <label class="confirm-item">
                            <input type="checkbox" v-model="confirmChecks.schedule" />
                            <span class="checkmark"></span>
                            <span>已确认发送时间和频率合理</span>
                        </label>
                        <label class="confirm-item">
                            <input type="checkbox" v-model="confirmChecks.compliance" />
                            <span class="checkmark"></span>
                            <span>已确认符合反垃圾邮件法规（GDPR/CAN-SPAM）</span>
                        </label>
                    </div>
                </div>
            </div>

            <div class="modal-footer">
                <button v-if="currentStep > 1" class="btn btn-secondary" @click="currentStep--">
                    <i class="fas fa-arrow-left"></i> 上一步
                </button>
                <button v-else class="btn btn-secondary" @click="closeCreateModal">
                    取消
                </button>
                <button v-if="currentStep < 5" class="btn btn-primary" @click="currentStep++">
                    下一步 <i class="fas fa-arrow-right"></i>
                </button>
                <button v-else class="btn btn-primary" :disabled="!canCreate" @click="createCampaign">
                    <i class="fas fa-rocket"></i> 创建活动
                </button>
            </div>
        </div>
    </div>

    <!-- Custom SOP Modal -->
    <div v-if="showCustomSopModal" class="modal-overlay" @click.self="showCustomSopModal = false">
        <div class="modal custom-sop-modal">
            <div class="modal-header">
                <div class="modal-title"><i class="fas fa-cogs"></i> 自定义 SOP 序列</div>
                <button class="modal-close" @click="showCustomSopModal = false"><i class="fas fa-times"></i></button>
            </div>
            <div class="modal-body">
                <!-- SOP 名称 -->
                <div class="form-group">
                    <label class="form-label">序列名称 <span class="required">*</span></label>
                    <input type="text" class="form-input" v-model="customSopData.name" placeholder="例如：我的自定义开发序列">
                </div>

                <!-- 步骤列表 -->
                <div class="custom-steps-section">
                    <div class="section-header">
                        <h5><i class="fas fa-list-ol"></i> 序列步骤</h5>
                        <button class="btn btn-sm btn-primary" @click="addCustomSopStep">
                            <i class="fas fa-plus"></i> 添加步骤
                        </button>
                    </div>

                    <div class="custom-steps-list">
                        <div v-for="(step, index) in customSopData.steps" :key="index" class="custom-step-item">
                            <div class="step-number">{{ index + 1 }}</div>
                            <div class="step-fields">
                                <div class="step-row">
                                    <div class="form-group">
                                        <label class="form-label">步骤名称</label>
                                        <input type="text" class="form-input" v-model="step.title"
                                            placeholder="例如：发送产品介绍">
                                    </div>
                                    <div class="form-group">
                                        <label class="form-label">间隔天数</label>
                                        <input type="number" class="form-input" v-model="step.day" min="1" max="30">
                                    </div>
                                </div>
                                <div class="step-row">
                                    <div class="form-group">
                                        <label class="form-label">触达渠道</label>
                                        <select class="form-select" v-model="step.channel"
                                            @change="updateChannelIcon(index)">
                                            <option value="email">邮件</option>
                                            <option value="whatsapp">WhatsApp</option>
                                            <option value="linkedin">LinkedIn</option>
                                            <option value="phone">电话</option>
                                            <option value="wechat">微信</option>
                                        </select>
                                    </div>
                                    <div class="channel-preview">
                                        <div class="preview-badge" :class="step.channel">
                                            <i :class="step.channelIcon"></i> {{ getChannelName(step.channel) }}
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="step-actions">
                                <button class="btn-icon" @click="removeCustomSopStep(index)"
                                    :disabled="customSopData.steps.length <= 1" title="删除步骤">
                                    <i class="fas fa-trash"></i>
                                </button>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 预览效果 -->
                <div class="custom-sop-preview">
                    <h5><i class="fas fa-eye"></i> 效果预览</h5>
                    <div class="preview-timeline">
                        <div v-for="(step, index) in customSopData.steps.filter(s => s.title)" :key="index"
                            class="preview-step">
                            <div class="preview-marker">
                                <i :class="step.channelIcon"></i>
                            </div>
                            <div class="preview-content">
                                <div class="preview-title">{{ step.title }}</div>
                                <div class="preview-meta">第{{ step.day }}天 · {{ getChannelName(step.channel) }}</div>
                            </div>
                        </div>
                        <div v-if="customSopData.steps.filter(s => s.title).length === 0" class="preview-empty">
                            <i class="fas fa-info-circle"></i> 请填写步骤内容以预览效果
                        </div>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button class="btn btn-secondary" @click="showCustomSopModal = false">取消</button>
                <button class="btn btn-primary">
                    <i class="fas fa-save"></i> 保存为新序列
                </button>
                <button class="btn btn-primary" @click="saveCustomSop">
                    <i class="fas fa-save"></i> 保存自定义SOP
                </button>
            </div>
        </div>
    </div>

    <PreviewCustomerModal
      :visible="showCustomerPreview"
      :customers="previewCustomers"
      @close="showCustomerPreview = false"
    />
</template>

<script setup>
    import { ref, computed } from 'vue'
    import PreviewCustomerModal from './PreviewCustomerModal.vue'

    const showCreateModal = ref(false)
    const currentStep = ref(1)
    const newCampaign = ref({
        name: '', type: 'prospect', priority: 'medium', description: '',
        startDate: '', endDate: '', owner: '', relatedOpportunity: '',
        segment: 'all', aiRecommend: 'high-value',
        filters: {
            region: '', industry: '', scoreRange: '', stage: '', companySize: '', purchaseCycle: '',
            keyword: '', selectedTags: []
        },
        goals: { sent: 500, openRate: 40, replyRate: 10, opportunities: 15 },
        channels: ['email'],
        emailSender: 'sales@company.com', emailSendTime: 'optimal',
        emailTemplate: 'default', batchSize: '100',
        emailSubject: '', emailPreviewText: '',
        trackOpen: true, trackClick: true, trackReply: true,
        whatsappAccount: '业务账号1', whatsappInterval: '60', whatsappTemplate: '',
        linkedinAction: 'message', linkedinLimit: '30',
        sopTemplate: 'standard',
        rules: {
            noOpenFollowup: true, noReplyFollowup: true, noClickFollowup: false,
            stopOnReply: true, stopOnBooking: true,
            noOpenFollowupDays: '3', noReplyFollowupDays: '7'
        },
        abTest: { enabled: false, variable: 'subject', ratio: '50', winnerCriteria: 'openRate', variantB: '' },
        scheduleMode: 'optimal', scheduledDate: '', scheduledTime: ''
    })
    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 availableChannels = [
        { id: 'email', name: '邮件营销', icon: 'fas fa-envelope', iconBg: 'rgba(99, 102, 241, 0.2)', iconColor: 'var(--primary)', description: '专业邮件营销', enabled: true, avgOpenRate: 45 },
    ]
    const selectedCustomerCount = computed(() => {
        const counts = { all: 847, new: 56, 'high-intent': 124, silent: 89 }
        return counts[newCampaign.value.segment] || 847
    })
    const showCustomerPreview = ref(false)
    const previewCustomers = ref([
        { id: 1, name: 'Riyadh Tech Distribution', company: 'Riyadh Tech Distribution', role: '采购总监', location: '沙特 · 利雅得', annualPurchase: '年采购约$1.5M', score: 92, tag: '潜客', logoText: 'RT' },
        { id: 2, name: 'Riyadh Tech Distribution', company: 'Riyadh Tech Distribution', role: '采购总监', location: '沙特 · 利雅得', annualPurchase: '年采购约$1.5M', score: 92, tag: '潜客', logoText: 'RT' },
        { id: 3, name: 'Riyadh Tech Distribution', company: 'Riyadh Tech Distribution', role: '采购总监', location: '沙特 · 利雅得', annualPurchase: '年采购约$1.5M', score: 92, tag: '潜客', logoText: 'RT' },
        { id: 4, name: 'Riyadh Tech Distribution', company: 'Riyadh Tech Distribution', role: '采购总监', location: '沙特 · 利雅得', annualPurchase: '年采购约$1.5M', score: 92, tag: '潜客', logoText: 'RT' }
    ])
    const showSubjectSuggestions = ref(false)
    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 getTypeLabel = (type) => ({ prospect: '潜客开发', nurture: '客户培育', reactivate: '客户唤醒', promote: '产品推广', seasonal: '节日营销', exhibition: '展会跟进' }[type] || type)
    const getPriorityLabel = (priority) => ({ urgent: '紧急', high: '高优先', medium: '中等', low: '低优先' }[priority] || priority)
    const getOwnerName = (owner) => ({ sales1: '张经理', sales2: '李主管', sales3: '王小明' }[owner] || '')
    const getChannelStyle = (id) => {
        const styles = {
            email: { 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' },
            wechat: { background: 'rgba(7, 193, 96, 0.2)', color: '#07C160' }
        }
        return styles[id] || {}
    }
    const getChannelName = (id) => ({ email: '邮件营销', whatsapp: 'WhatsApp', linkedin: 'LinkedIn', wechat: '微信企业号' }[id] || id)
    const getChannelConfig = (id) => {
        if (id === 'email') return newCampaign.value.emailSender + ' · ' + (newCampaign.value.emailSendTime === 'optimal' ? 'AI推荐时间' : newCampaign.value.emailSendTime)
        if (id === 'whatsapp') return newCampaign.value.whatsappAccount + ' · ' + newCampaign.value.whatsappInterval + '秒/条'
        if (id === 'linkedin') return newCampaign.value.linkedinAction === 'message' ? '发送消息' : '连接请求' + ' · ' + newCampaign.value.linkedinLimit + '次/天'
        return ''
    }
    const getChannelIconById = (id) => ({ email: 'fas fa-envelope', whatsapp: 'fab fa-whatsapp', linkedin: 'fab fa-linkedin', wechat: 'fab fa-weixin' }[id] || 'fas fa-comment')
    const hasWarnings = computed(() => selectedCustomerCount.value > 500 || !newCampaign.value.emailSubject || newCampaign.value.channels.length === 0)
    const confirmChecks = ref({ content: false, schedule: false, compliance: false, unsubscribe: true })
    const canCreate = computed(() => confirmChecks.value.content && confirmChecks.value.schedule && confirmChecks.value.compliance)

    const createCampaign = () => { closeCreateModal(); toast('营销活动已创建', 'success') }

    const selectSubject = (subj) => { newCampaign.value.emailSubject = subj; showSubjectSuggestions.value = false }
    const toggleChannel = (id) => {
        const i = newCampaign.value.channels.indexOf(id)
        i > -1 ? newCampaign.value.channels.splice(i, 1) : newCampaign.value.channels.push(id)
    }
    const clearFilters = () => {
        newCampaign.value.filters = {
            region: '', industry: '', scoreRange: '', stage: '', companySize: '', purchaseCycle: '',
            keyword: '', selectedTags: []
        }
    }
    const removeTag = (tag) => {
        const idx = newCampaign.value.filters.selectedTags.indexOf(tag)
        if (idx > -1) newCampaign.value.filters.selectedTags.splice(idx, 1)
    }
    const applySuggestion = (type) => {
        if (type === 'name') {
            const typeNames = { prospect: '潜客开发', nurture: '客户培育', reactivate: '客户唤醒', promote: '产品推广', seasonal: '节日营销', exhibition: '展会跟进' }
            const regions = ['中东', '欧洲', '北美', '东南亚']
            const region = regions[Math.floor(Math.random() * regions.length)]
            newCampaign.value.name = `2026春季${region}${typeNames[newCampaign.value.type] || '营销'}活动`
            toast('活动名称已生成', 'success')
        } else if (type === 'desc') {
            newCampaign.value.description = `本次活动旨在通过多渠道触达目标客户群体，提升品牌知名度并获取高质量商机。主要策略包括：
            1. 针对目标客户发送个性化邮件内容
            2. 结合WhatsApp/LinkedIn进行多渠道跟进
            3. 设置自动化SOP序列持续培育客户
            预期目标：打开率45%+，回复率10%+，转化商机15+`
            toast('活动描述已生成', 'success')
        }
    }

    const duplicateCampaign = (campaign) => {
        toast(`已复制活动"${campaign.name}"`, 'success')
        showHistoryModal.value = false
        setTimeout(() => {
            openCreateModal()
            newCampaign.value.name = campaign.name + ' (副本)'
        }, 300)
    }

    const showCustomSopModal = ref(false)
    const selectedSopTemplate = computed(() => sopTemplates.find(s => s.id === newCampaign.value.sopTemplate))
    const customSopData = ref({
        name: '',
        steps: [
            { title: '', day: 1, channel: 'email', channelIcon: 'fas fa-envelope' },
            { title: '', day: 3, channel: 'email', channelIcon: 'fas fa-envelope' },
            { title: '', day: 7, channel: 'linkedin', channelIcon: 'fab fa-linkedin' },
            { title: '', day: 14, channel: 'phone', channelIcon: 'fas fa-phone' }
        ]
    })
    const editSopTemplate = () => {
        customSopData.value = {
            name: selectedSopTemplate.value?.name || '',
            steps: selectedSopTemplate.value?.stepsDetail?.map(s => ({
                title: s.title,
                day: s.day,
                channel: s.channel.toLowerCase().replace('邮件', 'email').replace('linkedin', 'linkedin').replace('电话', 'phone').replace('whatsapp', 'whatsapp'),
                channelIcon: s.channelIcon
            })) || [
                    { title: '', day: 1, channel: 'email', channelIcon: 'fas fa-envelope' },
                    { title: '', day: 3, channel: 'email', channelIcon: 'fas fa-envelope' },
                    { title: '', day: 7, channel: 'linkedin', channelIcon: 'fab fa-linkedin' },
                    { title: '', day: 14, channel: 'phone', channelIcon: 'fas fa-phone' }
                ]
        }
        showCustomSopModal.value = true
    }

    const addCustomSopStep = () => {
        const lastDay = customSopData.value.steps[customSopData.value.steps.length - 1]?.day || 0
        customSopData.value.steps.push({
            title: '',
            day: lastDay + 3,
            channel: 'email',
            channelIcon: 'fas fa-envelope'
        })
    }

    const removeCustomSopStep = (index) => {
        if (customSopData.value.steps.length > 1) {
            customSopData.value.steps.splice(index, 1)
        }
    }

    const updateChannelIcon = (index) => {
        const channel = customSopData.value.steps[index].channel
        const icons = {
            email: 'fas fa-envelope',
            whatsapp: 'fab fa-whatsapp',
            linkedin: 'fab fa-linkedin',
            phone: 'fas fa-phone',
            wechat: 'fab fa-weixin'
        }
        customSopData.value.steps[index].channelIcon = icons[channel] || 'fas fa-envelope'
    }

    const saveCustomSop = () => {
        if (!customSopData.value.name) {
            toast('请输入SOP名称', 'error')
            return
        }
        const validSteps = customSopData.value.steps.filter(s => s.title)
        if (validSteps.length === 0) {
            toast('请至少填写一个步骤', 'error')
            return
        }
        // 将自定义SOP应用到活动
        newCampaign.value.sopTemplate = 'custom'
        newCampaign.value.customSOP = { ...customSopData.value }
        showCustomSopModal.value = false
        toast('自定义SOP已保存', 'success')
    }

    const open = () => { currentStep.value = 1; showCreateModal.value = true }
    const closeCreateModal = () => { showCreateModal.value = false; currentStep.value = 1 }

    defineExpose({
        open,
        duplicateCampaign
    })
</script>

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