<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>
                        <el-input
                            v-model="newCampaign.name"
                            maxlength="30"
                            show-word-limit
                            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>
                            <el-select v-model="newCampaign.type" placeholder="请选择活动类型">
                                <el-option label="潜客开发" value="潜客开发" />
                                <el-option label="客户培育" value="客户培育" />
                                <el-option label="客户唤醒" value="客户唤醒" />
                                <el-option label="产品推广" value="产品推广" />
                                <el-option label="节日营销" value="节日营销" />
                                <el-option label="展会跟进" value="展会跟进" />
                            </el-select>
                        </div>
                        <div class="form-group">
                            <label class="form-label">优先级</label>
                            <el-select v-model="newCampaign.priority" placeholder="请选择优先级">
                                <el-option label="高" value="高" />
                                <el-option label="中" value="中" />
                                <el-option label="低" value="低" />
                            </el-select>
                        </div>
                    </div>
                    <div class="form-row">
                        <div class="form-group">
                            <label class="form-label">开始日期</label>
                            <el-date-picker
                                v-model="newCampaign.startDate"
                                type="datetime"
                                format="YYYY-MM-DD HH:mm"
                                value-format="YYYY-MM-DD HH:mm:ss"
                                placeholder="选择开始时间"
                            />
                        </div>
                        <div class="form-group">
                            <label class="form-label">结束日期</label>
                            <el-date-picker
                                v-model="newCampaign.endDate"
                                type="datetime"
                                format="YYYY-MM-DD HH:mm"
                                value-format="YYYY-MM-DD HH:mm:ss"
                                placeholder="选择结束时间"
                            />
                        </div>
                    </div>
                    <div class="form-row">
                        <div class="form-group">
                            <label class="form-label">负责人</label>
                            <el-select v-model="newCampaign.owner" multiple collapse-tags placeholder="选择负责人">
                                <el-option label="张经理" value="sales1" />
                                <el-option label="李主管" value="sales2" />
                                <el-option label="王小明" value="sales3" />
                            </el-select>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="form-label">活动描述</label>
                        <el-input
                            v-model="newCampaign.description"
                            type="textarea"
                            :rows="3"
                            maxlength="150"
                            show-word-limit
                            placeholder="描述本次营销活动的目标和策略..."
                        />
                    </div>
                    <div class="form-group">
                        <label class="form-label">活动目标</label>
                        <div class="goal-inputs">
                            <div class="goal-item">
                                <i class="fas fa-envelope"></i>
                                <el-input-number v-model="newCampaign.goals.sent" :controls="false" :min="0" />
                                <span>发送量</span>
                            </div>
                            <div class="goal-item">
                                <i class="fas fa-envelope-open"></i>
                                <el-input-number v-model="newCampaign.goals.openRate" :controls="false" :min="0" :max="100" />
                                <span>% 打开率</span>
                            </div>
                            <div class="goal-item">
                                <i class="fas fa-reply"></i>
                                <el-input-number v-model="newCampaign.goals.replyRate" :controls="false" :min="0" :max="100" />
                                <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>
                                <el-select v-model="newCampaign.filters.region" clearable placeholder="全部地区">
                                    <el-option label="中东" value="middle-east" />
                                    <el-option label="欧洲" value="europe" />
                                    <el-option label="北美" value="north-america" />
                                    <el-option label="东南亚" value="southeast-asia" />
                                    <el-option label="非洲" value="africa" />
                                    <el-option label="南美" value="south-america" />
                                </el-select>
                            </div>
                            <div class="form-group">
                                <label class="form-label">行业</label>
                                <el-select v-model="newCampaign.filters.industry" clearable placeholder="全部行业">
                                    <el-option label="数据中心" value="datacenter" />
                                    <el-option label="消费电子" value="consumer" />
                                    <el-option label="电子分销" value="distributor" />
                                    <el-option label="零售" value="retail" />
                                    <el-option label="制造业" value="manufacturing" />
                                </el-select>
                            </div>
                        </div>
                        <div class="filter-row">
                            <div class="form-group">
                                <label class="form-label">意向分数</label>
                                <el-select v-model="newCampaign.filters.scoreRange" clearable placeholder="不限">
                                    <el-option label="80-100分" value="high" />
                                    <el-option label="60-79分" value="medium" />
                                    <el-option label="40-59分" value="low" />
                                </el-select>
                            </div>
                            <div class="form-group">
                                <label class="form-label">客户规模</label>
                                <el-select v-model="newCampaign.filters.companySize" clearable placeholder="不限">
                                    <el-option label="大型企业(500+)" value="large" />
                                    <el-option label="中型企业(100-500)" value="medium" />
                                    <el-option label="小微企业(<100)" value="small" />
                                </el-select>
                            </div>
                        </div>
                        <!-- 自定义关键词搜索 -->
                        <div class="form-group">
                            <label class="form-label">关键词搜索</label>
                            <div class="keyword-search">
                                <el-input v-model="newCampaign.filters.keyword" placeholder="搜索公司名、联系人、产品关键词..." clearable />
                                <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>
                                <el-select v-model="newCampaign.emailSender" placeholder="请选择发件邮箱">
                                    <el-option label="sales@company.com" value="sales@company.com" />
                                    <el-option label="marketing@company.com" value="marketing@company.com" />
                                    <el-option label="support@company.com" value="support@company.com" />
                                </el-select>
                            </div>
                            <div class="form-group">
                                <label class="form-label">发送时间</label>
                                <el-select v-model="newCampaign.emailSendTime" placeholder="请选择发送时间">
                                    <el-option label="AI推荐最优时间" value="optimal" />
                                    <el-option label="上午 9:00-11:00" value="morning" />
                                    <el-option label="下午 14:00-16:00" value="afternoon" />
                                    <el-option label="晚上 19:00-21:00" value="evening" />
                                </el-select>
                            </div>
                        </div>
                        <div class="form-row">
                            <div class="form-group">
                                <label class="form-label">生成方式</label>
                                <el-select v-model="newCampaign.emailTemplate" placeholder="请选择生成方式">
                                    <el-option label="AI自主" value="AI自主" />
                                    <el-option label="人工协同" value="人工协同" />
                                </el-select>
                            </div>
                            <div class="form-group">
                                <label class="form-label">每批发送量</label>
                                <el-select v-model="newCampaign.batchSize" placeholder="请选择每批发送量">
                                    <el-option label="50封/批" value="50" />
                                    <el-option label="100封/批" value="100" />
                                    <el-option label="200封/批" value="200" />
                                    <el-option label="500封/批" value="500" />
                                </el-select>
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="form-label">邮件主题 <span class="required">*</span></label>
                            <div class="subject-input-group">
                                <el-input style="flex: 1" 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>
                            <el-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>
                                <el-select v-model="newCampaign.whatsappAccount" placeholder="请选择发送账号">
                                    <el-option label="业务账号1" value="业务账号1" />
                                    <el-option label="业务账号2" value="业务账号2" />
                                </el-select>
                            </div>
                            <div class="form-group">
                                <label class="form-label">发送间隔</label>
                                <el-select v-model="newCampaign.whatsappInterval" placeholder="请选择发送间隔">
                                    <el-option label="30秒/条" value="30" />
                                    <el-option label="1分钟/条" value="60" />
                                    <el-option label="2分钟/条" value="120" />
                                </el-select>
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="form-label">消息模板</label>
                            <el-input v-model="newCampaign.whatsappTemplate" type="textarea" :rows="3" placeholder="输入 WhatsApp 消息模板..." />
                        </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>
                                <el-select v-model="newCampaign.linkedinAction" placeholder="请选择操作类型">
                                    <el-option label="发送消息" value="message" />
                                    <el-option label="发送连接请求" value="connect" />
                                    <el-option label="InMail" value="inmail" />
                                </el-select>
                            </div>
                            <div class="form-group">
                                <label class="form-label">每日上限</label>
                                <el-select v-model="newCampaign.linkedinLimit" placeholder="请选择每日上限">
                                    <el-option label="20次/天" value="20" />
                                    <el-option label="30次/天" value="30" />
                                    <el-option label="50次/天" value="50" />
                                </el-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">
                                <el-select class="mini-select" v-model="newCampaign.rules.noOpenFollowupDays" placeholder="请选择">
                                    <el-option label="2天后" value="2" />
                                    <el-option label="3天后" value="3" />
                                    <el-option label="5天后" value="5" />
                                    <el-option label="7天后" value="7" />
                                </el-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">
                                <el-select class="mini-select" v-model="newCampaign.rules.noReplyFollowupDays" placeholder="请选择">
                                    <el-option label="5天后" value="5" />
                                    <el-option label="7天后" value="7" />
                                    <el-option label="10天后" value="10" />
                                </el-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>
                                    <el-select v-model="newCampaign.abTest.variable" placeholder="请选择测试变量">
                                        <el-option label="邮件主题" value="subject" />
                                        <el-option label="邮件内容" value="content" />
                                        <el-option label="发送时间" value="sendTime" />
                                        <el-option label="发件人名称" value="fromName" />
                                    </el-select>
                                </div>
                                <div class="form-group">
                                    <label class="form-label">测试比例</label>
                                    <el-select v-model="newCampaign.abTest.ratio" placeholder="请选择测试比例">
                                        <el-option label="50% : 50%" value="50" />
                                        <el-option label="30% : 70%" value="30" />
                                        <el-option label="20% : 80%" value="20" />
                                    </el-select>
                                </div>
                            </div>
                            <div class="form-group">
                                <label class="form-label">胜出条件</label>
                                <el-select v-model="newCampaign.abTest.winnerCriteria" placeholder="请选择胜出条件">
                                    <el-option label="打开率最高" value="openRate" />
                                    <el-option label="点击率最高" value="clickRate" />
                                    <el-option label="回复率最高" value="replyRate" />
                                </el-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>
                                    <el-input v-model="newCampaign.abTest.variantB" class="variant-input" 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>
                                    <el-date-picker v-model="newCampaign.scheduledDate" type="date" format="YYYY-MM-DD" value-format="YYYY-MM-DD" placeholder="选择日期" />
                                </div>
                                <div class="form-group">
                                    <label class="form-label">开始时间</label>
                                    <el-time-picker v-model="newCampaign.scheduledTime" format="HH:mm" value-format="HH:mm" placeholder="选择时间" />
                                </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 || isSubmitting" @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>
                    <el-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>
                                        <el-input v-model="step.title" placeholder="例如：发送产品介绍" />
                                    </div>
                                    <div class="form-group">
                                        <label class="form-label">间隔天数</label>
                                        <el-input-number v-model="step.day" :controls="false" :min="1" :max="30" />
                                    </div>
                                </div>
                                <div class="step-row">
                                    <div class="form-group">
                                        <label class="form-label">触达渠道</label>
                                        <el-select v-model="step.channel" placeholder="请选择渠道" @change="updateChannelIcon(index)">
                                            <el-option label="邮件" value="email" />
                                            <el-option label="WhatsApp" value="whatsapp" />
                                            <el-option label="LinkedIn" value="linkedin" />
                                            <el-option label="电话" value="phone" />
                                            <el-option label="微信" value="wechat" />
                                        </el-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'
    import { getSopList, addMarketing } from '@/api/marketing'

    const showCreateModal = ref(false)
    const currentStep = ref(1)
    const toast = (message, type = 'success') => {
        if (typeof window !== 'undefined' && typeof window.toast === 'function') {
            window.toast(message, type)
            return
        }
        console[type === 'success' ? 'log' : 'warn'](`[toast] ${message}`)
    }
    const newCampaign = ref({
        name: '', type: '潜客开发', priority: '中', 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: 'AI自主', 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 isSubmitting = ref(false)
    const canCreate = computed(() => confirmChecks.value.content && confirmChecks.value.schedule && confirmChecks.value.compliance)

    const goToStep = (step) => { currentStep.value = step }

    const createCampaign = async () => {
        if (!newCampaign.value.name) {
            currentStep.value = 1
            toast('请填写活动名称', 'error')
            return
        }
        if (newCampaign.value.channels.includes('email') && !newCampaign.value.emailSubject) {
            currentStep.value = 3
            toast('请设置邮件主题', 'error')
            return
        }
        if (!canCreate.value) {
            toast('请完成确认事项后创建活动', 'error')
            return
        }
        isSubmitting.value = true
        try {
            const typeMap = { prospect: 1, nurture: 2, reactivate: 3, promote: 4, seasonal: 5, exhibition: 6 }
            const priorityMap = { urgent: 1, high: 2, medium: 3, low: 4 }
            const ownerMap = { sales1: 1, sales2: 2, sales3: 3 }
            const selectedOwners = Array.isArray(newCampaign.value.owner)
                ? newCampaign.value.owner.filter(Boolean)
                : [newCampaign.value.owner].filter(Boolean)
            const sopIdMap = { standard: 1, aggressive: 2, nurture: 3, reactivate: 4, custom: 0 }
            const channelConfig = newCampaign.value.channels.reduce((acc, channel) => {
                if (channel === 'email') return acc + 1
                if (channel === 'whatsapp') return acc + 2
                if (channel === 'linkedin') return acc + 4
                return acc
            }, 0)
            const payload = {
                name: newCampaign.value.name,
                type: typeMap[newCampaign.value.type] || 1,
                priority: priorityMap[newCampaign.value.priority] || 3,
                description: newCampaign.value.description,
                beginData: newCampaign.value.startDate || null,
                endDate: newCampaign.value.endDate || null,
                supervisor: selectedOwners.length ? ownerMap[selectedOwners[0]] || null : null,
                linkToOpportunity: newCampaign.value.relatedOpportunity || null,
                sendVolume: Number(newCampaign.value.goals.sent) || null,
                openRate: Number(newCampaign.value.goals.openRate) || null,
                replyRate: Number(newCampaign.value.goals.replyRate) || null,
                opportunityCount: Number(newCampaign.value.goals.opportunities) || null,
                channelConfiguration: channelConfig,
                emailAddress: newCampaign.value.emailSender,
                emailSentTime: newCampaign.value.emailSendTime,
                emailTemplate: newCampaign.value.emailTemplate,
                emailBatchSize: Number(newCampaign.value.batchSize) || null,
                emailSubject: newCampaign.value.emailSubject,
                trackConfigOpen: newCampaign.value.trackOpen ? 1 : 0,
                trackConfigClick: newCampaign.value.trackClick ? 1 : 0,
                trackConfigReply: newCampaign.value.trackReply ? 1 : 0,
                sopId: sopIdMap[newCampaign.value.sopTemplate] || 0,
                followUpRulesNotOpened: newCampaign.value.rules.noOpenFollowup ? 1 : 0,
                followUpRulesNotOpenedDays: newCampaign.value.rules.noOpenFollowupDays,
                followUpRulesNotReplied: newCampaign.value.rules.noReplyFollowup ? 1 : 0,
                followUpRulesNotRepliedDays: newCampaign.value.rules.noReplyFollowupDays,
                followUpRulesLinkNotClicked: newCampaign.value.rules.noClickFollowup ? 1 : 0,
                followUpRulesLinkNotClickedDays: newCampaign.value.rules.noClickFollowupDays || null,
                followUpRulesReplied: newCampaign.value.rules.stopOnReply ? 1 : 0,
                followUpRulesAppointmentBooked: newCampaign.value.rules.stopOnBooking ? 1 : 0,
                aBTesting: newCampaign.value.abTest.enabled ? 1 : 0,
                smartSchedulingType: newCampaign.value.scheduleMode,
                smartSchedulingStartDate: newCampaign.value.scheduledDate || null,
                smartSchedulingStartTime: newCampaign.value.scheduledTime || null,
                hasContentCompliant: confirmChecks.value.content ? 1 : 0,
                hasScheduleApproved: confirmChecks.value.schedule ? 1 : 0,
                hasGdprCompliant: confirmChecks.value.compliance ? 1 : 0,
                hasUnsubscribeLink: confirmChecks.value.unsubscribe ? 1 : 0
            }
            console.log(payload)
            await addMarketing(payload)
            toast('营销活动已创建', 'success')
            closeCreateModal()
        } catch (error) {
            toast(error?.message || '创建营销活动失败', 'error')
        } finally {
            isSubmitting.value = false
        }
    }

    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 getSop = () => {
        getSopList({ pageIndex: 1, pageSize: 100 }).then(res => {
            console.log('res :>> ', res);
        })
    }

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

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

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

.create-modal :deep(.el-input__wrapper),
.create-modal :deep(.el-textarea__inner),
.create-modal :deep(.el-select .el-select__wrapper),
.create-modal :deep(.el-input-number__wrapper),
.create-modal :deep(.el-date-editor.el-input__wrapper) {
    background: var(--bg-dark);
    border: 1px solid var(--border);
    box-shadow: none;
    border-radius: 8px;
    color: var(--text-primary);
    width: 100%;
    box-sizing: border-box;
    min-width: 0;
}

.create-modal :deep(.el-date-editor) {
    width: 100%;
    min-width: 0;
}

.create-modal :deep(.el-input__wrapper.is-focus),
.create-modal :deep(.el-select .el-select__wrapper.is-focus),
.create-modal :deep(.el-input-number__wrapper.is-focus),
.create-modal :deep(.el-date-editor.el-input__wrapper.is-focus) {
    background: var(--bg-card);
    border-color: var(--primary);
    box-shadow: 0 0 0 1px var(--primary) inset;
}

.create-modal :deep(.el-input__inner),
.create-modal :deep(.el-textarea__inner),
.create-modal :deep(.el-input-number__inner),
.create-modal :deep(.el-date-editor .el-input__inner) {
    background: transparent;
    color: var(--text-primary);
}

.create-modal :deep(.el-input__inner::placeholder),
.create-modal :deep(.el-textarea__inner::placeholder),
.create-modal :deep(.el-date-editor .el-input__inner::placeholder) {
    color: var(--text-muted);
}

.create-modal :deep(.el-select-dropdown),
.create-modal :deep(.el-picker-panel) {
    background: var(--bg-card);
    border: 1px solid var(--border);
    color: var(--text-primary);
}

.create-modal :deep(.el-select-dropdown__item.hover),
.create-modal :deep(.el-select-dropdown__item:hover) {
    background: rgba(99, 102, 241, 0.12);
    color: var(--primary);
}

.create-modal :deep(.el-select-dropdown__item.is-selected) {
    background: rgba(99, 102, 241, 0.2);
    color: var(--primary);
    font-weight: 600;
}

.create-modal :deep(.el-date-table td.current:not(.disabled) .el-date-table-cell__text),
.create-modal :deep(.el-date-table td.today .el-date-table-cell__text) {
    background: var(--primary);
    color: white;
}

.create-modal :deep(.el-input__count),
.create-modal :deep(.el-input__count-inner) {
    background: transparent;
    color: var(--text-muted);
}

.create-modal :deep(.el-input-number) {
    width: 130px;
}

.create-modal :deep(.el-input-number__increase),
.create-modal :deep(.el-input-number__decrease) {
    background: var(--bg-hover);
    color: var(--text-primary);
    border-color: var(--border);
}

.create-modal :deep(.el-input-number__increase:hover),
.create-modal :deep(.el-input-number__decrease:hover) {
    background: rgba(99, 102, 241, 0.12);
    color: var(--primary);
}

.create-modal :deep(.el-select__selection .el-select__placeholder:not(.is-transparent)) {
    color: var(--text-primary);
}
</style>