<template>
  <div class="activity-edit" :class="{ 'readonly-mode': isReadonly }">
    <el-card :class="['activity-page-card', { 'basic-modular-mode': activeStep === 0 }]">
      <template #header><div class="page-header"><span>{{ pageTitle }}</span><el-button @click="goBack">返回</el-button></div></template>
      <el-form ref="formRef" :model="form" :rules="rules" label-width="150px" :disabled="isReadonly">
        <div class="steps-card">
          <el-steps :active="activeStep" simple class="activity-steps">
            <el-step v-for="item in stepItems" :key="item.title" :title="item.title">
              <template #icon><el-icon><component :is="item.icon" /></el-icon></template>
            </el-step>
          </el-steps>
        </div>

        <div v-show="activeStep === 0" class="step-pane">
          <el-card shadow="never" class="section-card">
            <template #header><div class="section-title">基础信息</div></template>
            <el-row :gutter="30" class="basic-info-form">
              <el-col :span="12"><el-form-item label="活动标题（对内）" prop="internalTitle"><el-input v-model="form.internalTitle" maxlength="50" show-word-limit placeholder="请输入对内活动标题" /></el-form-item></el-col>
              <el-col :span="12"><el-form-item label="活动名称（对客）" prop="name"><el-input v-model="form.name" maxlength="50" show-word-limit placeholder="请输入面向客户的活动名称" /></el-form-item></el-col>
              <el-col :span="12"><el-form-item label="活动类型" prop="category"><el-select v-model="form.category" placeholder="请选择活动类型" style="width:100%" @change="handleCategoryChange"><el-option label="普通活动" value="普通活动" /><el-option label="层层礼" value="层层礼" /><el-option label="MGM活动" value="MGM" /><el-option label="NTB活动" value="NTB活动" /></el-select></el-form-item></el-col>
              <el-col :span="12"><el-form-item label="活动对象"><el-input v-model="form.target" maxlength="50" show-word-limit placeholder="请输入活动对象" /></el-form-item></el-col>
              <el-col :span="12">
                <el-form-item label="活动小图" prop="thumbnail">
                  <div class="image-upload-field">
                    <el-upload
                      action="#"
                      list-type="picture-card"
                      :auto-upload="false"
                      :file-list="uploadList('thumbnail')"
                      :on-change="file => handleUpload(file, 'thumbnail')"
                      :on-preview="handlePreviewImage"
                      :on-remove="() => form.thumbnail = []"
                      :disabled="isReadonly"
                      :class="{ 'upload-hide-trigger': uploadList('thumbnail').length >= 1 }"
                    >
                      <el-icon><Plus /></el-icon>
                    </el-upload>
                    <div class="upload-size-tip">建议尺寸：780x438px<br>支持 JPG、PNG 格式</div>
                  </div>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="活动头图" prop="detailImage">
                  <div class="image-upload-field">
                    <el-upload
                      action="#"
                      list-type="picture-card"
                      :auto-upload="false"
                      :file-list="uploadList('detailImage')"
                      :on-change="file => handleUpload(file, 'detailImage')"
                      :on-preview="handlePreviewImage"
                      :on-remove="() => form.detailImage = []"
                      :disabled="isReadonly"
                      :class="{ 'upload-hide-trigger': uploadList('detailImage').length >= 1 }"
                    >
                      <el-icon><Plus /></el-icon>
                    </el-upload>
                    <div class="upload-size-tip">建议尺寸：780x438px<br>支持 JPG、PNG 格式</div>
                  </div>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <div class="offline-switch-line">
                  <div>
                    <div class="setting-title">线下活动</div>
                    <div class="setting-desc">开启后，需配置线下活动所在的城市及具体地点</div>
                  </div>
                  <el-switch v-model="form.offlineEnabled" />
                </div>
                <div v-if="form.offlineEnabled" class="offline-config-panel">
                  <el-row :gutter="30">
                    <el-col :span="12"><el-form-item label="活动城市"><el-input v-model="form.cityText" placeholder="如：上海市" /></el-form-item></el-col>
                    <el-col :span="12"><el-form-item label="活动地点"><el-input v-model="form.location" placeholder="请输入详细活动地址" /></el-form-item></el-col>
                  </el-row>
                </div>
              </el-col>
              <el-col :span="24">
                <el-form-item label="活动内容" prop="content">
                  <quill-editor v-model:content="form.content" content-type="html" :options="quillOptions" :read-only="isReadonly"></quill-editor>
                </el-form-item>
              </el-col>
              <el-col v-if="form.category === '层层礼'" :span="24">
                <div class="layer-copy-config">
                  <div class="layer-copy-header">
                    <div class="layer-copy-title"><span class="required-mark">*</span> 活动达标层级内容</div>
                    <div class="layer-copy-actions">
                      <span>已配置 <strong>{{ form.layerContents.length }}</strong> / 5 个层级</span>
                      <el-button v-if="!isReadonly" type="danger" link :icon="Plus" :disabled="form.layerContents.length >= 5" @click="addLayerCopy">添加层级</el-button>
                    </div>
                  </div>
                  <div class="layer-copy-tabs">
                    <el-tabs v-model="layerCopyActiveTab" type="card">
                      <el-tab-pane v-for="(level, index) in form.layerContents" :key="level.key" :label="level.title || layerTitle(index)" :name="String(index)">
                        <div class="layer-copy-panel">
                          <div class="layer-copy-meta">
                            <el-form-item label="Tab 标题" required>
                              <el-input v-model="level.title" class="layer-title-input" />
                            </el-form-item>
                            <el-button v-if="!isReadonly && form.layerContents.length > 1" type="info" link :icon="Delete" @click="removeLayerCopy(index)">删除此层级</el-button>
                          </div>
                          <quill-editor v-model:content="level.content" content-type="html" :options="layerQuillOptions" :read-only="isReadonly"></quill-editor>
                        </div>
                      </el-tab-pane>
                    </el-tabs>
                  </div>
                </div>
              </el-col>
            </el-row>
          </el-card>

          <el-card shadow="never" class="section-card toggle-section-card" :class="{ 'is-collapsed': !form.sharable }" :body-style="form.sharable ? undefined : { display: 'none', padding: '0' }">
            <template #header>
              <div class="section-title section-title-with-action">
                <span>分享设置</span>
                <el-checkbox v-model="form.sharable" class="share-toggle-checkbox">自定义微信分享</el-checkbox>
              </div>
            </template>
            <el-row v-if="form.sharable" :gutter="30" class="basic-info-form">
              <el-col :span="12"><el-form-item label="分享名称"><el-input v-model="form.shareTitle" maxlength="50" show-word-limit placeholder="输入分享到微信的卡片标题" /></el-form-item></el-col>
              <el-col :span="12">
                <el-form-item label="分享图片">
                  <div class="image-upload-field share-upload-field">
                    <el-upload
                      action="#"
                      list-type="picture-card"
                      :auto-upload="false"
                      :file-list="uploadList('shareImage')"
                      :on-change="file => handleUpload(file, 'shareImage')"
                      :on-preview="handlePreviewImage"
                      :on-remove="() => form.shareImage = []"
                      :disabled="isReadonly"
                      :class="{ 'upload-hide-trigger': uploadList('shareImage').length >= 1 }"
                    >
                      <el-icon><Plus /></el-icon>
                    </el-upload>
                    <div class="upload-size-tip">建议尺寸：100x100px<br>支持 JPG、PNG 格式</div>
                  </div>
                </el-form-item>
              </el-col>
            </el-row>
          </el-card>

          <el-card shadow="never" class="section-card">
            <template #header><div class="section-title">其他设置</div></template>
            <el-row :gutter="30" class="basic-info-form">
              <el-col :span="12"><el-form-item label="CD staff ID"><el-input v-model="form.ownerStaffId" placeholder="输入相关 Staff ID" /></el-form-item></el-col>
              <el-col :span="12"><el-form-item label="SCRM activity code"><el-input v-model="form.scrmActivityCode" placeholder="输入 SCRM 对应的活动编号" /></el-form-item></el-col>
              <el-col :span="12"><el-form-item label="SCRM channel code"><el-input v-model="form.scrmChannelCode" placeholder="输入渠道编号" /></el-form-item></el-col>
              <el-col :span="12"><el-form-item label="Label"><el-select v-model="form.labels" multiple allow-create filterable default-first-option placeholder="活动相关标签" style="width:100%"><el-option label="interest-新客" value="interest-新客" /><el-option label="interest-MGM" value="interest-MGM" /></el-select></el-form-item></el-col>
            </el-row>
          </el-card>
        </div>

        <div v-show="activeStep === 1" class="step-pane">
          <el-card shadow="never" class="section-card">
            <template #header><div class="section-title">时间配置</div></template>
            <el-row :gutter="30" class="module-form">
              <el-col :span="12">
                <el-form-item label="活动时间" prop="activityTime">
                  <el-date-picker v-model="form.activityTime" type="daterange" value-format="YYYY-MM-DD" class="date-range-field" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="展示时间">
                  <el-date-picker v-model="form.displayTime" type="daterange" value-format="YYYY-MM-DD" class="date-range-field" />
                </el-form-item>
              </el-col>
            </el-row>
          </el-card>
          <el-card shadow="never" class="section-card">
            <template #header><div class="section-title">展示客群</div></template>
            <el-row :gutter="30" class="module-form">
              <el-col :span="12">
                <el-form-item label="展示客群">
                  <el-select
                    v-model="form.visibleCrowdIds"
                    multiple
                    collapse-tags
                    collapse-tags-tooltip
                    clearable
                    placeholder="请选择展示客群，不选代表全部用户展示"
                    class="field-md"
                  >
                    <el-option v-for="item in crowds" :key="item.id" :label="item.name" :value="item.id" />
                  </el-select>
                  <div class="form-tip">不选代表全部用户展示（全部展示不包括潜客）</div>
                </el-form-item>
              </el-col>
            </el-row>
          </el-card>
          <el-card shadow="never" class="section-card">
            <template #header><div class="section-title">渠道配置</div></template>
            <el-row :gutter="30" class="module-form">
              <el-col :span="12">
                <el-form-item label="Campaign ID">
                  <el-select v-model="form.campaignId" clearable placeholder="请选择 Campaign ID" style="width:100%">
                    <el-option v-for="item in campaignOptions" :key="item.value" :label="item.label" :value="item.value" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="Channel ID">
                  <el-select v-model="form.channelId" clearable placeholder="请选择 Channel ID" style="width:100%">
                    <el-option v-for="item in channelOptions" :key="item.value" :label="item.label" :value="item.value" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
          </el-card>
          <el-card shadow="never" class="section-card">
            <template #header><div class="section-title">入口展示</div></template>
            <el-row :gutter="30" class="module-form">
              <el-col :span="24">
                <el-form-item label="权益首页">
                  <el-radio-group v-model="form.showOnHome">
                    <el-radio :value="true">显示</el-radio>
                    <el-radio :value="false">不显示</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="组装页">
                  <el-radio-group v-model="form.showOnAssembly">
                    <el-radio :value="true">显示</el-radio>
                    <el-radio :value="false">不显示</el-radio>
                  </el-radio-group>
                </el-form-item>
                <div v-if="form.showOnAssembly" class="assembly-select-panel">
                  <el-select
                    v-model="form.assemblyPageIds"
                    multiple
                    collapse-tags
                    collapse-tags-tooltip
                    clearable
                    placeholder="请选择组装页"
                    class="field-md"
                  >
                    <el-option v-for="item in assemblyPages" :key="item.id" :label="`${item.name}（${item.id}）`" :value="item.id" />
                  </el-select>
                </div>
              </el-col>
              <el-col :span="24">
                <el-form-item label="活动轮播图">
                  <el-radio-group v-model="form.showOnCarousel">
                    <el-radio :value="true">显示</el-radio>
                    <el-radio :value="false">不显示</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
            </el-row>
          </el-card>
        </div>

        <div v-show="activeStep === 2" class="step-pane">
          <el-card shadow="never" class="section-card toggle-section-card" :body-style="{ display: 'none', padding: '0' }">
            <template #header>
              <div class="section-title section-title-with-action">
                <span>报名设置</span>
                <el-checkbox v-model="form.needSignup" class="section-toggle-checkbox">需要报名</el-checkbox>
              </div>
            </template>
          </el-card>
          <template v-if="form.needSignup">
            <el-card shadow="never" class="section-card">
              <template #header><div class="section-title">报名客群与时间</div></template>
              <el-row :gutter="30" class="module-form signup-row">
                <el-col :span="12">
                  <el-form-item label="报名客群">
                    <el-select
                      v-model="form.signupCrowdIds"
                      multiple
                      collapse-tags
                      collapse-tags-tooltip
                      clearable
                      placeholder="请选择报名客群，数据来自人群管理"
                      class="field-md"
                    >
                      <el-option v-for="item in crowds" :key="item.id" :label="item.name" :value="item.id" />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="报名时间" required>
                    <el-date-picker v-model="form.signupTime" type="daterange" value-format="YYYY-MM-DD" class="date-range-field" />
                  </el-form-item>
                </el-col>
              </el-row>
            </el-card>
            <el-card shadow="never" class="section-card toggle-section-card" :class="{ 'is-collapsed': !form.needConfirm }">
              <template #header>
                <div class="section-title section-title-with-action">
                  <span>报名确认</span>
                  <el-checkbox v-model="form.needConfirm" class="section-toggle-checkbox">报名确认</el-checkbox>
                </div>
              </template>
              <el-row v-if="form.needConfirm" :gutter="30" class="module-form signup-row">
                <el-col :span="12">
                  <el-form-item label="报名确认文案">
                    <el-input v-model="form.confirmText" type="textarea" :rows="3" resize="vertical" placeholder="请输入报名确认文案" class="field-lg" />
                  </el-form-item>
                </el-col>
              </el-row>
            </el-card>
            <el-card shadow="never" class="section-card toggle-section-card" :class="{ 'is-collapsed': !form.needExtraInfo }">
              <template #header>
                <div class="section-title section-title-with-action">
                  <span>补充信息表单</span>
                  <el-checkbox v-model="form.needExtraInfo" class="section-toggle-checkbox" @change="handleNeedExtraInfoChange">补充信息</el-checkbox>
                </div>
              </template>
              <el-row v-if="form.needExtraInfo" :gutter="30" class="module-form signup-row">
                <el-col :span="24">
                  <div class="extra-forms-header">
                    <div>
                      <span class="extra-forms-title">补充信息配置</span>
                      <span class="extra-forms-limit">最多配置 2 项</span>
                    </div>
                    <el-button v-if="!isReadonly && form.extraForms.length < 2" type="primary" link :icon="Plus" @click="addExtraForm">添加补充信息</el-button>
                  </div>
                  <div v-for="(extra, extraIndex) in form.extraForms" :key="extraIndex" class="extra-form-panel">
                    <div class="extra-form-head">
                      <span>补充信息{{ extraIndex + 1 }}</span>
                      <el-button v-if="!isReadonly && form.extraForms.length > 1" type="danger" link :icon="Delete" @click="removeExtraForm(extraIndex)">删除补充信息</el-button>
                    </div>
                    <el-row :gutter="16">
                      <el-col :span="12"><el-form-item label="字段名称" :prop="`extraForms.${extraIndex}.name`" required><el-input v-model="extra.name" class="field-md" /></el-form-item></el-col>
                      <el-col :span="12"><el-form-item label="提示文案" :prop="`extraForms.${extraIndex}.placeholder`" required><el-input v-model="extra.placeholder" class="field-md" /></el-form-item></el-col>
                      <el-col :span="12"><el-form-item label="字段类型" :prop="`extraForms.${extraIndex}.type`" required>
                        <el-select v-model="extra.type" class="field-md"><el-option label="文本" value="text" /><el-option label="数字" value="number" /></el-select>
                      </el-form-item></el-col>
                      <el-col :span="6"><el-form-item label="是否必填" :prop="`extraForms.${extraIndex}.required`" required><el-switch v-model="extra.required" /></el-form-item></el-col>
                      <el-col :span="6"><el-form-item label="最大长度" :prop="`extraForms.${extraIndex}.maxLength`" required><el-input-number v-model="extra.maxLength" :min="1" :max="500" :controls="true" class="field-xs" /></el-form-item></el-col>
                    </el-row>
                  </div>
                  <div class="extra-link-panel">
                    <el-form-item label="第三方跳转链接" label-width="140px">
                      <el-input v-model="form.extraInfoLink" placeholder="例如：https://example.com/third-party" class="field-lg" />
                    </el-form-item>
                  </div>
                </el-col>
              </el-row>
            </el-card>
            <el-card shadow="never" class="section-card toggle-section-card" :class="{ 'is-collapsed': !form.quotaEnabled }">
              <template #header>
                <div class="section-title section-title-with-action">
                  <span>名额控制</span>
                  <el-checkbox v-model="form.quotaEnabled" class="section-toggle-checkbox">名额控制</el-checkbox>
                </div>
              </template>
              <el-row v-if="form.quotaEnabled" :gutter="30" class="module-form signup-row">
                <el-col :span="12"><el-form-item label="报名人数上限"><el-input-number v-model="form.quota" :min="0" class="field-md" /></el-form-item></el-col>
                <el-col :span="12"><el-form-item label="展示报名人数"><el-switch v-model="form.showSignupCount" /></el-form-item></el-col>
                <el-col v-if="isEdit" :span="24"><el-form-item label="已报名人数"><el-input-number v-model="form.signedCount" :min="0" disabled class="field-md" /></el-form-item></el-col>
              </el-row>
            </el-card>
            <el-card shadow="never" class="section-card toggle-section-card" :class="{ 'is-collapsed': !form.signupGuideEnabled }">
              <template #header>
                <div class="section-title section-title-with-action">
                  <span>报名成功页配置</span>
                  <el-checkbox v-model="form.signupGuideEnabled" class="section-toggle-checkbox">报名成功页配置</el-checkbox>
                </div>
              </template>
              <el-row v-if="form.signupGuideEnabled" :gutter="30" class="module-form signup-row">
                <el-col :span="12">
                  <el-form-item label="标题" required>
                    <el-input v-model="form.signupSuccessTitle" maxlength="30" show-word-limit placeholder="请输入移动端报名成功页标题" />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="描述">
                    <el-input v-model="form.signupSuccessDescription" type="textarea" :rows="3" maxlength="200" show-word-limit placeholder="请输入移动端报名成功页描述" />
                  </el-form-item>
                </el-col>
              </el-row>
            </el-card>
          </template>
        </div>

        <div v-show="activeStep === 3" class="step-pane">
          <ActivityAchievementConfig :form="form" :crowds="crowds" :grant-plans="grantPlans" :readonly="isReadonly" />
          <el-card v-if="false" shadow="never" class="section-card">
            <div v-if="false" class="progress-config">
              <div class="config-section template-section">
                <div class="section-body">
                  <el-row :gutter="20" align="middle">
                    <el-col :span="8">
                      <el-form-item label="进度与奖励" class="compact-item">
                        <el-switch v-model="form.progressEnabled" />
                      </el-form-item>
                    </el-col>
                    <el-col v-if="form.progressEnabled" :span="10">
                      <el-form-item label="活动模板" required class="compact-item">
                        <el-select v-model="form.achievementTemplate" placeholder="请选择" style="width:100%" @change="handleAchievementTemplateChange">
                          <el-option label="NTB（新客达标）" value="NTB" />
                          <el-option label="MGM（推荐有礼）" value="MGM" />
                          <el-option label="层层礼" value="LAYER" />
                        </el-select>
                      </el-form-item>
                    </el-col>
                    <el-col v-if="form.progressEnabled && form.achievementTemplate === 'LAYER'" :span="6">
                      <el-form-item label="层级数量" required class="compact-item">
                        <el-input-number v-model="form.layerCount" :min="1" :max="5" @change="syncLayerCount" />
                      </el-form-item>
                    </el-col>
                  </el-row>
                </div>
              </div>

              <el-empty v-if="!form.progressEnabled || !form.achievementTemplate" description="当前未配置达标进度与奖励" :image-size="72" />

              <template v-else>
                <div v-if="form.achievementTemplate === 'NTB'" class="config-section">
                  <div class="section-header">达标进度提示话术配置</div>
                  <div class="section-body narrow-form">
                    <el-form-item label="未达标提示"><el-input v-model="form.progressCopy.unreached" maxlength="100" show-word-limit /></el-form-item>
                    <el-form-item label="已达标提示"><el-input v-model="form.progressCopy.reached" maxlength="100" show-word-limit /></el-form-item>
                    <el-form-item label="达标进度提示"><el-input v-model="form.progressCopy.help" maxlength="100" show-word-limit placeholder="配置问号弹窗提示内容" /></el-form-item>
                  </div>
                </div>

                <div class="config-section">
                  <div class="section-header">
                    <span>{{ form.achievementTemplate === 'LAYER' ? '达标层级配置' : '达标规则标签配置' }}</span>
                    <el-button v-if="!isReadonly && form.achievementTemplate !== 'LAYER'" type="primary" :icon="Plus" @click="addAchievementRule">添加进度标签</el-button>
                  </div>
                  <div class="section-body">
                    <template v-if="form.achievementTemplate === 'MGM'">
                      <el-form-item label="已达标展示标签" required class="limit-field">
                        <el-select v-model="form.mgmAchievedTag" placeholder="请选择">
                          <el-option label="客户MSC Group" value="客户MSC Group" />
                        </el-select>
                      </el-form-item>
                    </template>

                    <template v-if="form.achievementTemplate !== 'LAYER'">
                      <div v-for="(rule, index) in form.achievementRules" :key="rule.key" class="rule-block">
                        <div class="rule-title">
                          <strong>规则标签{{ index + 1 }}</strong>
                          <el-button v-if="!isReadonly && form.achievementRules.length > 1" type="danger" link :icon="Delete" @click="removeAchievementRule(index)">删除</el-button>
                        </div>
                        <el-row :gutter="16">
                          <el-col :span="8">
                            <el-form-item label="规则标签" required>
                              <el-select v-model="rule.field" placeholder="请选择" style="width:100%">
                                <el-option v-for="item in ruleFieldOptions" :key="item" :label="item" :value="item" />
                              </el-select>
                            </el-form-item>
                          </el-col>
                          <el-col :span="6">
                            <el-form-item label="判断条件" required>
                              <el-select v-model="rule.operator" placeholder="请选择" style="width:100%">
                                <el-option v-for="item in operatorOptions" :key="item" :label="item" :value="item" />
                              </el-select>
                            </el-form-item>
                          </el-col>
                          <el-col :span="10">
                            <el-form-item label="规则值" required>
                              <el-date-picker v-if="rule.field === '开户时间' && rule.operator === '介于'" v-model="rule.dateRange" type="daterange" value-format="YYYY-MM-DD" start-placeholder="开始日期" end-placeholder="结束日期" style="width:100%" />
                              <el-input-number v-else v-model="rule.value" :min="0" :controls="false" style="width:100%" />
                            </el-form-item>
                          </el-col>
                        </el-row>
                        <el-row v-if="rule.field !== '开户时间'" :gutter="16">
                          <el-col :span="8"><el-form-item label="开户当月必须达标"><el-switch v-model="rule.openingMonthRequired" /></el-form-item></el-col>
                          <el-col :span="8"><el-form-item label="连续达标"><el-switch v-model="rule.continuous" /></el-form-item></el-col>
                          <el-col v-if="rule.continuous" :span="8"><el-form-item label="连续月份"><el-input-number v-model="rule.months" :min="1" :max="36" /></el-form-item></el-col>
                          <el-col v-if="rule.continuous" :span="8"><el-form-item label="允许断开"><el-switch v-model="rule.allowBreak" /></el-form-item></el-col>
                        </el-row>
                        <el-row :gutter="16">
                          <el-col :span="12"><el-form-item :label="form.achievementTemplate === 'MGM' ? '已达标提示话术' : '标签描述'" required><el-input v-model="rule.reachedText" /></el-form-item></el-col>
                          <el-col :span="12"><el-form-item :label="form.achievementTemplate === 'MGM' ? '待达标提示话术' : '标签未达标提示'" required><el-input v-model="rule.unreachedText" /></el-form-item></el-col>
                          <el-col v-if="form.achievementTemplate === 'MGM'" :span="12"><el-form-item label="不达标原因" required><el-input v-model="rule.failureReason" /></el-form-item></el-col>
                          <el-col v-else :span="12"><el-form-item label="标签进度提示"><el-input v-model="rule.progressText" placeholder="配置问号弹窗提示内容" /></el-form-item></el-col>
                        </el-row>
                      </div>
                    </template>

                    <template v-else>
                      <el-tabs v-model="layerActiveTab" class="layer-tabs">
                        <el-tab-pane v-for="(level, levelIndex) in form.achievementLayers" :key="level.key" :label="`层级${levelIndex + 1}`" :name="String(levelIndex)">
                          <div class="level-panel">
                            <el-row :gutter="16">
                              <el-col :span="12"><el-form-item label="可参与人群"><el-select v-model="level.crowdId" clearable style="width:100%"><el-option v-for="item in crowds" :key="item.id" :label="`${item.id}-${item.name}`" :value="item.id" /></el-select></el-form-item></el-col>
                              <el-col :span="12"><el-form-item label="层级标题"><el-input v-model="level.title" /></el-form-item></el-col>
                            </el-row>
                            <div class="subsection-actions">
                              <el-button v-if="!isReadonly" type="primary" :icon="Plus" @click="addLayerActivity(level)">添加活动</el-button>
                            </div>

                            <div v-for="(activity, activityIndex) in level.activities" :key="activity.key" class="layer-activity">
                              <div class="activity-heading">
                                <div>
                                  <strong>活动 {{ activityIndex + 1 }}</strong>
                                  <span v-if="activityIndex > 0" class="prerequisite-note">*注意：活动{{ activityIndex + 1 }}达标前提为活动{{ activityIndex }}</span>
                                </div>
                                <el-button v-if="!isReadonly && level.activities.length > 1" type="danger" link :icon="Delete" @click="removeLayerActivity(level, activityIndex)">删除活动</el-button>
                              </div>
                              <el-row :gutter="16">
                                <el-col :span="12"><el-form-item label="活动标题"><el-input v-model="activity.title" /></el-form-item></el-col>
                                <el-col :span="12"><el-form-item label="活动描述"><el-input v-model="activity.description" /></el-form-item></el-col>
                              </el-row>
                              <div v-if="!isReadonly" class="subsection-actions rule-actions"><el-button type="primary" plain :icon="Plus" @click="addLayerRule(activity)">添加进度标签</el-button></div>
                              <div v-for="(rule, ruleIndex) in activity.rules" :key="rule.key" class="rule-block inner-rule" :class="{ 'dependent-rule': activityIndex > 0 }">
                                <div class="rule-title"><strong>规则标签{{ ruleIndex + 1 }}</strong><el-button v-if="!isReadonly && activity.rules.length > 1" type="danger" link :icon="Delete" @click="activity.rules.splice(ruleIndex, 1)">删除</el-button></div>
                                <el-row :gutter="16">
                                  <el-col :span="8"><el-form-item label="规则标签" required><el-select v-model="rule.field" style="width:100%"><el-option v-for="item in ruleFieldOptions" :key="item" :label="item" :value="item" /></el-select></el-form-item></el-col>
                                  <template v-if="rule.field === '境外消费'">
                                    <el-col :span="8"><el-form-item label="消费时间" required><el-date-picker v-model="rule.consumptionEndDate" type="date" value-format="YYYY-MM-DD" placeholder="请选择日期" style="width:100%" /></el-form-item></el-col>
                                    <el-col :span="8"><el-form-item label="消费维度" required><el-select v-model="rule.consumptionDimension" style="width:100%"><el-option label="笔数" value="笔数" /></el-select></el-form-item></el-col>
                                    <el-col :span="8"><el-form-item label="判断条件" required><el-select v-model="rule.operator" style="width:100%"><el-option label="大于等于" value="大于等于" /></el-select></el-form-item></el-col>
                                    <el-col :span="8"><el-form-item label="消费笔数" required><el-input-number v-model="rule.value" :min="1" style="width:100%" /></el-form-item></el-col>
                                  </template>
                                  <template v-else>
                                    <el-col :span="6"><el-form-item label="判断条件" required><el-select v-model="rule.operator" style="width:100%"><el-option v-for="item in operatorOptions" :key="item" :label="item" :value="item" /></el-select></el-form-item></el-col>
                                    <el-col :span="10"><el-form-item label="规则值" required>
                                      <el-date-picker v-if="rule.field === '开户时间' && rule.operator === '介于'" v-model="rule.dateRange" type="daterange" value-format="YYYY-MM-DD" start-placeholder="开始日期" end-placeholder="结束日期" style="width:100%" />
                                      <el-input-number v-else v-model="rule.value" :min="0" :controls="false" style="width:100%" />
                                    </el-form-item></el-col>
                                    <el-col v-if="rule.field !== '开户时间'" :span="8"><el-form-item label="开户当月必须达标"><el-switch v-model="rule.openingMonthRequired" /></el-form-item></el-col>
                                    <el-col v-if="rule.field !== '开户时间'" :span="8"><el-form-item label="连续达标"><el-switch v-model="rule.continuous" /></el-form-item></el-col>
                                    <el-col v-if="rule.field !== '开户时间' && rule.continuous" :span="8"><el-form-item label="连续月份"><el-input-number v-model="rule.months" :min="1" :max="36" /></el-form-item></el-col>
                                    <el-col v-if="rule.field !== '开户时间' && rule.continuous" :span="8"><el-form-item label="允许断开"><el-switch v-model="rule.allowBreak" /></el-form-item></el-col>
                                  </template>
                                  <el-col :span="12"><el-form-item label="规则标题"><el-input v-model="rule.reachedText" /></el-form-item></el-col>
                                  <el-col :span="12"><el-form-item label="规则描述"><el-input v-model="rule.unreachedText" /></el-form-item></el-col>
                                  <el-col :span="12"><el-form-item label="标签进度提示"><el-input v-model="rule.progressText" placeholder="配置问号弹窗提示内容" /></el-form-item></el-col>
                                </el-row>
                              </div>
                              <div class="inline-reward">
                                <el-form-item label="达标发放计划" required>
                                  <el-select v-model="activity.grantPlanId" placeholder="请选择" style="width:100%">
                                    <el-option v-for="item in grantPlans" :key="item.id" :label="`${item.id}-${item.name}`" :value="item.id" />
                                  </el-select>
                                </el-form-item>
                              </div>
                            </div>
                          </div>
                        </el-tab-pane>
                      </el-tabs>
                    </template>
                  </div>
                </div>

                <div v-if="form.achievementTemplate === 'MGM'" class="config-section">
                  <div class="section-header">被推荐进度配置</div>
                  <div class="section-body narrow-form">
                    <el-form-item label="规则标签1描述" required><el-input v-model="form.mgmReferredProgress.labelOne" /></el-form-item>
                    <el-form-item label="规则标签2描述" required><el-input v-model="form.mgmReferredProgress.labelTwo" /></el-form-item>
                    <el-form-item label="是否有进阶奖励" required><el-switch v-model="form.mgmReferredProgress.advancedReward" /></el-form-item>
                    <el-form-item v-if="form.mgmReferredProgress.advancedReward" label="进阶奖励规则标签" required>
                      <el-select v-model="form.mgmReferredProgress.advancedRuleField" style="width:320px"><el-option label="TRB值（含家庭账户）" value="TRB值（含家庭账户）" /></el-select>
                    </el-form-item>
                    <el-form-item v-if="form.mgmReferredProgress.advancedReward" label="进阶奖励规则描述" required><el-input v-model="form.mgmReferredProgress.advancedRuleText" /></el-form-item>
                  </div>
                </div>

                <div v-if="form.achievementTemplate !== 'LAYER'" class="config-section">
                  <div class="section-header">达标奖励配置</div>
                  <div class="section-body">
                    <el-row :gutter="20">
                      <el-col :span="8"><el-form-item label="需要发放奖励"><el-switch v-model="form.rewardEnabled" /></el-form-item></el-col>
                      <el-col v-if="form.rewardEnabled" :span="8"><el-form-item label="奖励类型" required><el-select v-model="form.rewardType" style="width:100%"><el-option label="积分" value="积分" /><el-option label="权益" value="权益" /></el-select></el-form-item></el-col>
                      <el-col v-if="form.rewardEnabled" :span="8"><el-form-item label="权益发放计划" required><el-select v-model="form.grantPlanId" clearable placeholder="请选择" style="width:100%"><el-option v-for="item in filteredGrantPlans" :key="item.id" :label="`${item.id}-${item.name}`" :value="item.id" /></el-select></el-form-item></el-col>
                      <el-col v-if="form.rewardEnabled && form.rewardType === '权益'" :span="12"><el-form-item label="权益有效期" required><el-date-picker v-model="form.rewardValidity" type="daterange" value-format="YYYY-MM-DD" start-placeholder="开始日期" end-placeholder="结束日期" style="width:100%" /></el-form-item></el-col>
                      <el-col v-if="form.rewardEnabled && form.rewardType === '权益'" :span="12"><el-form-item label="赠送次数" required><el-input-number v-model="form.rewardGrantTimes" :min="1" /></el-form-item></el-col>
                    </el-row>
                  </div>
                </div>
              </template>
            </div>
          </el-card>
        </div>

        <div v-show="activeStep === 4" class="step-pane">
          <el-card shadow="never" class="section-card toggle-section-card" :class="{ 'is-collapsed': !form.mutexEnabled }">
            <template #header>
              <div class="section-title section-title-with-action">
                <span>互斥设置</span>
                <el-checkbox v-model="form.mutexEnabled" class="section-toggle-checkbox">参与互斥</el-checkbox>
              </div>
            </template>
            <el-row v-if="form.mutexEnabled" :gutter="30" class="module-form">
              <el-col :span="16"><el-form-item label="互斥组" required><el-select v-model="form.mutexGroup" clearable style="width:100%"><el-option v-for="item in mutexGroups" :key="item.id" :label="item.name" :value="item.name" /></el-select></el-form-item></el-col>
            </el-row>
          </el-card>
          <el-card shadow="never" class="section-card">
            <template #header><div class="section-title">通知设置</div></template>
            <el-row :gutter="30" class="module-form">
              <el-col :span="12"><el-form-item label="报名成功模板"><el-select v-model="form.signupNoticeTemplateId" clearable style="width:100%"><el-option v-for="item in notifications" :key="item.id" :label="item.name" :value="item.id" /></el-select></el-form-item></el-col>
              <el-col :span="12"><el-form-item label="开始前提醒模板"><el-select v-model="form.beforeStartTemplateId" clearable style="width:100%"><el-option v-for="item in notifications" :key="item.id" :label="item.name" :value="item.id" /></el-select></el-form-item></el-col>
              <el-col :span="12"><el-form-item label="达标发奖通知模板（需领取）"><el-select v-model="form.rewardTemplateId" clearable style="width:100%"><el-option v-for="item in notifications" :key="item.id" :label="item.name" :value="item.id" /></el-select></el-form-item></el-col>
              <el-col :span="12"><el-form-item label="达标发奖通知模板（无需领取）"><el-select v-model="form.rewardNoClaimTemplateId" clearable style="width:100%"><el-option v-for="item in notifications" :key="item.id" :label="item.name" :value="item.id" /></el-select></el-form-item></el-col>
            </el-row>
          </el-card>
        </div>

      </el-form>
      <div class="action-bar">
        <div class="action-left">
          <el-button v-if="activeStep > 0" @click="prevStep"><el-icon><ArrowLeft /></el-icon>上一步</el-button>
        </div>
        <div class="action-center">
          <el-button @click="goBack">{{ isReadonly ? '返回' : '取消' }}</el-button>
          <el-button v-if="isAudit" type="danger" @click="rejectActivity">{{ isOfflineAudit ? '驳回下线' : '驳回' }}</el-button>
          <el-button v-if="isAudit" type="primary" @click="approveActivity">{{ isOfflineAudit ? '审核通过并下线' : '审核通过' }}</el-button>
          <el-button v-if="!isReadonly" type="primary" plain @click="saveDraft">保存草稿</el-button>
          <el-button v-if="!isReadonly && activeStep === stepItems.length - 1" type="primary" @click="markPending">提交审核</el-button>
        </div>
        <div class="action-right">
          <el-button v-if="activeStep < stepItems.length - 1" type="primary" @click="nextStep">下一步<el-icon class="el-icon--right"><ArrowRight /></el-icon></el-button>
        </div>
      </div>
    </el-card>
    <el-dialog v-model="previewVisible" title="图片预览" width="640px" append-to-body>
      <img v-if="previewImageUrl" :src="previewImageUrl" style="display:block; max-width:100%; margin:0 auto;" />
    </el-dialog>
  </div>
</template>

<script>
import { ElMessage, ElMessageBox } from 'element-plus'
import { ArrowLeft, ArrowRight, Bell, InfoFilled, Medal, Plus, Setting, User, Delete } from '@element-plus/icons-vue'
import request from '@/utils/request'
import { fetchLinkOptions } from '@/utils/linkOptions'
import activityStore from '@/store/activityStore'
import smsTemplateStore from '@/store/smsTemplateStore'
import ActivityAchievementConfig from '@/components/activity/ActivityAchievementConfig.vue'

export default {
  name: 'ActivityEdit',
  components: { ActivityAchievementConfig },
  data() {
    return {
      Delete,
      Plus,
      ArrowLeft,
      ArrowRight,
      activeStep: 0,
      previewVisible: false,
      previewImageUrl: '',
      layerCopyActiveTab: '0',
      stepItems: [
        { title: '基础信息', icon: InfoFilled },
        { title: '展示规则', icon: Setting },
        { title: '客群与报名', icon: User },
        { title: '进度与奖励', icon: Medal },
        { title: '互斥与通知', icon: Bell }
      ],
      layerActiveTab: '0',
      assemblyPages: [],
      campaignOptions: [],
      channelOptions: [],
      ruleFieldOptions: ['开户时间', 'TRB值（含家庭账户）', '客户MSC Group', '境外消费'],
      operatorOptions: ['介于', '大于等于', '小于等于'],
      quillOptions: {
        placeholder: '请输入活动详情介绍、流程、注意事项等...',
        modules: {
          toolbar: [
            ['bold', 'italic', 'underline', 'strike'],
            [{ list: 'ordered' }, { list: 'bullet' }],
            ['link', 'image'],
            ['clean']
          ]
        }
      },
      layerQuillOptions: {
        placeholder: '请输入该层级的达标要求、奖励内容等...',
        modules: {
          toolbar: [
            ['bold', 'italic', 'underline', 'strike'],
            [{ list: 'ordered' }, { list: 'bullet' }],
            ['link', 'clean']
          ]
        }
      },
      form: activityStore.emptyActivity(),
      rules: {
        internalTitle: [{ required: true, message: '请输入活动标题（对内）', trigger: 'blur' }],
        name: [{ required: true, message: '请输入活动名称（对客）', trigger: 'blur' }],
        category: [{ required: true, message: '请选择活动类型', trigger: 'change' }],
        thumbnail: [{ required: true, message: '请输入活动小图', trigger: 'blur' }],
        detailImage: [{ required: true, message: '请输入活动头图', trigger: 'blur' }],
        content: [{ required: true, message: '请输入活动详情', trigger: 'blur' }],
        activityTime: [{ type: 'array', required: true, message: '请选择活动时间', trigger: 'change' }]
      }
    }
  },
  computed: {
    isEdit() { return this.$route.name === 'ActivityEdit' },
    isAudit() { return this.$route.name === 'ActivityAudit' },
    isOfflineAudit() { return this.isAudit && this.form.auditAction === 'offline' },
    isReadonly() { return this.$route.name === 'ActivityView' || this.isAudit },
    pageTitle() {
      if (this.isOfflineAudit) return '活动下线审核'
      if (this.isAudit) return '活动审核'
      if (this.isReadonly) return '查看活动'
      return this.isEdit ? '编辑活动' : '新建活动'
    },
    crowds() { return activityStore.activityCrowds },
    forms() { return activityStore.forms },
    progressTemplates() { return activityStore.progressTemplates },
    progressRules() { return activityStore.progressRules },
    grantPlans() { return activityStore.activityGrantPlans },
    filteredGrantPlans() {
      if (!this.form.rewardType) return this.grantPlans
      if (this.form.rewardType === '积分') return this.grantPlans.filter((item) => item.rewardType === '积分')
      return this.grantPlans.filter((item) => item.rewardType !== '积分')
    },
    mutexGroups() { return activityStore.mutexGroups },
    notifications() { return smsTemplateStore.state.list }
  },
  created() {
    if (this.isEdit || this.isReadonly) {
      const row = activityStore.getActivity(this.$route.params.id)
      if (!row) {
        ElMessage.error('活动不存在')
        return this.goBack()
      }
      this.form = { ...activityStore.emptyActivity(), ...JSON.parse(JSON.stringify(row)) }
    }
    this.normalizeProgressConfig()
    this.normalizeExtraForms()
    this.normalizeActivityImages()
    this.normalizeLayerContents()
    this.fetchAssemblyPages()
    this.fetchChannelOptions()
  },
  methods: {
    async fetchAssemblyPages() {
      try {
        const res = await request.get('/api/assembly/list', { params: { name: '' } })
        this.assemblyPages = Array.isArray(res?.data) ? res.data : []
      } catch (e) {
        this.assemblyPages = []
      }
    },
    newAchievementRule() {
      return {
        key: `${Date.now()}-${Math.random()}`,
        field: '',
        operator: '',
        value: 0,
        dateRange: [],
        openingMonthRequired: false,
        continuous: false,
        months: 1,
        allowBreak: false,
        reachedText: '',
        unreachedText: '',
        progressText: '',
        failureReason: '',
        consumptionEndDate: '',
        consumptionDimension: '笔数'
      }
    },
    newLayerActivity(index) {
      const rule = this.newAchievementRule()
      if (index === 1) {
        rule.field = '境外消费'
        rule.operator = '大于等于'
        rule.value = 1
      }
      return {
        key: `${Date.now()}-activity-${index}-${Math.random()}`,
        title: '',
        description: '',
        rules: [rule],
        grantPlanId: ''
      }
    },
    newAchievementLayer(index) {
      return {
        key: `${Date.now()}-${index}-${Math.random()}`,
        crowdId: '',
        title: `层级${index + 1}`,
        content: '',
        activities: [this.newLayerActivity(0), this.newLayerActivity(1)]
      }
    },
    layerTitle(index) {
      const names = ['一', '二', '三', '四', '五']
      return `层级${names[index] || index + 1}`
    },
    newLayerContent(index) {
      return {
        key: `${Date.now()}-layer-copy-${index}-${Math.random()}`,
        title: this.layerTitle(index),
        content: ''
      }
    },
    normalizeLayerContents() {
      if (!Array.isArray(this.form.layerContents) || !this.form.layerContents.length) {
        this.form.layerContents = [this.newLayerContent(0)]
      }
      this.form.layerContents = this.form.layerContents.slice(0, 5).map((item, index) => ({
        key: item.key || `${Date.now()}-layer-copy-${index}-${Math.random()}`,
        title: item.title || this.layerTitle(index),
        content: item.content || ''
      }))
      if (Number(this.layerCopyActiveTab) >= this.form.layerContents.length) this.layerCopyActiveTab = String(this.form.layerContents.length - 1)
    },
    normalizeProgressConfig() {
      if (!this.form.progressCopy) this.form.progressCopy = { unreached: '', reached: '', help: '' }
      if (!Array.isArray(this.form.achievementRules) || !this.form.achievementRules.length) this.form.achievementRules = [this.newAchievementRule()]
      if (!this.form.mgmReferredProgress) this.form.mgmReferredProgress = { labelOne: '', labelTwo: '', advancedReward: false, advancedRuleField: '', advancedRuleText: '' }
      if (!Array.isArray(this.form.achievementLayers) || !this.form.achievementLayers.length) this.form.achievementLayers = [this.newAchievementLayer(0)]
      this.form.achievementLayers.forEach((level, index) => {
        if (!level.key) level.key = `${Date.now()}-${index}-${Math.random()}`
        if (!level.title) level.title = `层级${index + 1}`
        if (level.content === undefined) level.content = ''
        if (!Array.isArray(level.activities) || !level.activities.length) {
          const firstActivity = this.newLayerActivity(0)
          firstActivity.title = level.activityTitle || ''
          firstActivity.description = level.description || ''
          firstActivity.rules = Array.isArray(level.rules) && level.rules.length ? level.rules : [this.newAchievementRule()]
          firstActivity.grantPlanId = level.grantPlanId || ''
          level.activities = [firstActivity, this.newLayerActivity(1)]
        }
      })
      this.syncLayerCount(this.form.layerCount || 1)
    },
    handleAchievementTemplateChange() {
      if (this.form.achievementTemplate === 'LAYER') this.syncLayerCount(this.form.layerCount || 1)
    },
    async fetchChannelOptions() {
      try {
        const { campaignOptions, channelOptions } = await fetchLinkOptions()
        this.campaignOptions = campaignOptions
        this.channelOptions = channelOptions
      } catch (e) {
        this.campaignOptions = []
        this.channelOptions = []
      }
    },
    handleCategoryChange(category) {
      const templateMap = {
        '层层礼': 'LAYER',
        MGM: 'MGM',
        'MGM活动': 'MGM',
        'NTB活动': 'NTB',
        '航空NTB活动': 'NTB',
        '酒店NTB活动': 'NTB'
      }
      this.form.achievementTemplate = templateMap[category] || ''
      this.handleAchievementTemplateChange()
    },
    newExtraForm() {
      return { name: '', placeholder: '', type: 'text', required: true, maxLength: 30 }
    },
    normalizeExtraForms() {
      const legacyForms = Array.isArray(this.form.extraForms) ? this.form.extraForms : []
      if (this.form.extraInfoLink === undefined) {
        this.form.extraInfoLink = legacyForms.find((item) => item?.link)?.link || ''
      }
      const normalized = legacyForms.flatMap((item) => {
        if (Array.isArray(item?.fields)) return item.fields
        return item ? [item] : []
      }).map((item) => ({
        name: item.name || '',
        placeholder: item.placeholder || '',
        type: item.type || 'text',
        required: item.required !== false,
        maxLength: Number(item.maxLength || 30)
      })).slice(0, 2)
      this.form.extraForms = normalized.length ? normalized : [this.newExtraForm()]
    },
    addExtraForm() {
      if (this.isReadonly) return
      if (this.form.extraForms.length >= 2) return ElMessage.warning('最多配置 2 项补充信息')
      this.form.extraForms.push(this.newExtraForm())
    },
    removeExtraForm(index) {
      if (this.isReadonly) return
      if (this.form.extraForms.length <= 1) return
      this.form.extraForms.splice(index, 1)
    },
    handleNeedExtraInfoChange(value) {
      if (this.isReadonly) return
      if (value && (!Array.isArray(this.form.extraForms) || !this.form.extraForms.length)) this.normalizeExtraForms()
    },
    normalizeUploadField(field) {
      const value = this.form[field]
      if (Array.isArray(value)) return value
      if (!value) return []
      this.form[field] = [{ name: `${field}.png`, url: value }]
      return this.form[field]
    },
    normalizeActivityImages() {
      this.normalizeUploadField('thumbnail')
      this.normalizeUploadField('detailImage')
      this.normalizeUploadField('shareImage')
      if (this.form.offlineEnabled === undefined) this.form.offlineEnabled = false
      if (this.form.cityText === undefined) this.form.cityText = Array.isArray(this.form.cities) ? this.form.cities.join('、') : ''
    },
    uploadList(field) {
      return this.normalizeUploadField(field)
    },
    handleUpload(file, field) {
      if (this.isReadonly) return
      if (!file || !file.raw) return
      const reader = new FileReader()
      reader.onload = (e) => {
        this.form[field] = [{ name: file.name, url: e.target.result, uid: file.uid }]
      }
      reader.readAsDataURL(file.raw)
    },
    handlePreviewImage(file) {
      this.previewImageUrl = file.url || ''
      this.previewVisible = !!this.previewImageUrl
    },
    addLayerCopy() {
      if (this.isReadonly) return
      if (!Array.isArray(this.form.layerContents)) this.form.layerContents = []
      if (this.form.layerContents.length >= 5) return ElMessage.warning('最多配置 5 个层级')
      this.form.layerContents.push(this.newLayerContent(this.form.layerContents.length))
      this.layerCopyActiveTab = String(this.form.layerContents.length - 1)
    },
    removeLayerCopy(index) {
      if (this.isReadonly) return
      if (this.form.layerContents.length <= 1) return
      this.form.layerContents.splice(index, 1)
      if (Number(this.layerCopyActiveTab) >= this.form.layerContents.length) this.layerCopyActiveTab = String(this.form.layerContents.length - 1)
      this.form.layerContents.forEach((level, levelIndex) => {
        if (!level.title) level.title = this.layerTitle(levelIndex)
      })
    },
    addAchievementRule() {
      if (this.isReadonly) return
      if (this.form.achievementRules.length >= 5) return ElMessage.warning('最多添加 5 个进度标签')
      this.form.achievementRules.push(this.newAchievementRule())
    },
    removeAchievementRule(index) {
      if (this.isReadonly) return
      this.form.achievementRules.splice(index, 1)
    },
    addLayerActivity(level) {
      if (this.isReadonly) return
      if (level.activities.length >= 5) return ElMessage.warning('每个层级最多添加 5 个活动')
      level.activities.push(this.newLayerActivity(level.activities.length))
    },
    removeLayerActivity(level, index) {
      if (this.isReadonly) return
      level.activities.splice(index, 1)
    },
    addLayerRule(activity) {
      if (this.isReadonly) return
      if (activity.rules.length >= 5) return ElMessage.warning('每个活动最多添加 5 个进度标签')
      activity.rules.push(this.newAchievementRule())
    },
    syncLayerCount(value) {
      const count = Number(value || 1)
      if (!Array.isArray(this.form.achievementLayers)) this.form.achievementLayers = []
      while (this.form.achievementLayers.length < count) this.form.achievementLayers.push(this.newAchievementLayer(this.form.achievementLayers.length))
      if (this.form.achievementLayers.length > count) this.form.achievementLayers.splice(count)
      if (Number(this.layerActiveTab) >= count) this.layerActiveTab = String(count - 1)
    },
    nextStep() {
      if (this.activeStep < this.stepItems.length - 1) this.activeStep += 1
    },
    prevStep() {
      if (this.activeStep > 0) this.activeStep -= 1
    },
    async saveDraft() { await this.submit(false) },
    async markPending() {
      await ElMessageBox.confirm('提交后将进入审核流程，期间不可再编辑。确定提交审核吗？', '提交审核', { type: 'warning' })
      await this.submit(true)
    },
    async approveActivity() {
      if (!this.isAudit) return
      await ElMessageBox.confirm(`确定${this.isOfflineAudit ? '审核通过并下线' : '审核通过'}活动「${this.form.name}」吗？`, '审核通过', { type: 'warning' })
      const target = activityStore.getActivity(this.form.id)
      if (target) {
        target.status = this.isOfflineAudit ? 'offline' : 'approved'
        target.auditStatus = this.isOfflineAudit ? '已下线' : '审核通过'
        target.auditAction = ''
        target.auditor = '当前审核人'
        target.updatedAt = this.nowText()
      }
      ElMessage.success(this.isOfflineAudit ? '审核通过，活动已下线' : '审核通过')
      this.goBack()
    },
    async rejectActivity() {
      if (!this.isAudit) return
      await ElMessageBox.confirm(`确定${this.isOfflineAudit ? '驳回下线申请' : '驳回活动'}「${this.form.name}」吗？`, '驳回活动', {
        type: 'warning',
        confirmButtonText: '驳回',
        confirmButtonClass: 'el-button--danger'
      })
      const target = activityStore.getActivity(this.form.id)
      if (target) {
        target.status = this.isOfflineAudit ? 'published' : 'rejected'
        target.auditStatus = this.isOfflineAudit ? '下线审核驳回' : '审核驳回'
        target.auditAction = ''
        target.auditor = '当前审核人'
        target.updatedAt = this.nowText()
      }
      ElMessage.success('已驳回')
      this.goBack()
    },
    async submit(toAudit) {
      if (this.isReadonly) return false
      const valid = await this.$refs.formRef.validate().catch(() => false)
      if (!valid) {
        ElMessage.warning('请先补全必填信息')
        return false
      }
      const error = this.validateBusiness()
      if (error) {
        ElMessage.warning(error)
        return false
      }
      if (toAudit) {
        this.form.status = 'pending'
        this.form.auditStatus = '待审核'
        this.form.auditAction = ''
      }
      activityStore.saveActivity(this.form)
      ElMessage.success(toAudit ? '已保存并提交审核' : '保存成功')
      this.$router.replace('/customization/hsbc/activities')
      return true
    },
    validateBusiness() {
      if (this.form.activityTime?.length === 2 && this.form.activityTime[0] > this.form.activityTime[1]) return '活动结束时间必须晚于开始时间'
      if (this.form.needSignup && (!this.form.signupTime || this.form.signupTime.length !== 2)) return '需要报名时，报名时间必填'
      if (this.form.signupGuideEnabled && !this.form.signupSuccessTitle) return '开启报名成功引导语时标题必填'
      if (this.form.signupTime?.length === 2 && this.form.signupTime[0] > this.form.signupTime[1]) return '报名结束时间必须晚于开始时间'
      if (this.form.needExtraInfo) {
        if (!this.form.extraForms?.length) return '开启补充信息时必须至少配置一个表单'
        if (this.form.extraForms.length > 2) return '补充信息最多配置 2 项'
        for (let i = 0; i < this.form.extraForms.length; i++) {
          const ef = this.form.extraForms[i]
          if (!ef.name) return `请填写补充信息${i + 1}的字段名称`
          if (!ef.placeholder) return `请填写补充信息${i + 1}的提示文案`
          if (!ef.type) return `请选择补充信息${i + 1}的字段类型`
          if (!ef.maxLength || ef.maxLength < 1) return `请填写补充信息${i + 1}的最大长度`
        }
      }
      if (this.form.quotaEnabled && Number(this.form.quota) < Number(this.form.signedCount || 0)) return '报名人数上限不能小于已报名人数'
      if (this.form.progressEnabled && this.form.achievementTemplate === 'NTB' && (!this.form.ntbRules?.length || this.form.ntbRules.some((rule) => !rule.field || !rule.operator))) return '请完整配置 NTB 达标规则标签'
      if (this.form.progressEnabled && this.form.achievementTemplate === 'MGM' && this.form.mgmRules?.some((rule) => !rule.field || !rule.operator)) return '请完整配置 MGM 达标规则标签'
      if (this.form.progressEnabled && this.form.achievementTemplate === 'LAYER') {
        const invalidLayerConfig = this.form.achievementLayers.some((level) => level.activities.some((activity) => {
          const invalidRule = activity.rules.some((rule) => !rule.field || (
            rule.field === '境外消费' &&
            (!rule.consumptionTimeOperator || !rule.consumptionEndDate || !rule.consumptionDimension || !rule.operator || Number(rule.value) < 1)
          ))
          return invalidRule || !activity.reward?.planId
        }))
        if (invalidLayerConfig) return '请完整配置每个层级活动的规则和达标奖励'
      }
      if (this.form.progressEnabled && this.form.achievementTemplate !== 'LAYER' && this.form.rewardEnabled && !this.form.grantPlanId) return '请选择达标奖励'
      if (this.form.mutexEnabled && !this.form.mutexGroup) return '参与互斥时必须选择互斥组'
      return ''
    },
    preview() { ElMessage.success('已生成移动端预览效果') },
    nowText() {
      const pad = (n) => String(n).padStart(2, '0')
      const d = new Date()
      return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`
    },
    statusText(status) { return { draft: '草稿', pending: '待审核', approved: '审核通过', published: '已发布', offline: '已下线' }[status] || status },
    goBack() { this.$router.push('/customization/hsbc/activities') }
  }
}
</script>

<style scoped>
.activity-edit { padding:20px; }
.readonly-mode :deep(.ql-toolbar),
.readonly-mode :deep(.ql-container) { background:#f5f7fa; }
.readonly-mode :deep(.ql-toolbar) { pointer-events:none; opacity:.7; }
.readonly-mode :deep(.el-input.is-disabled .el-input__wrapper),
.readonly-mode :deep(.el-textarea.is-disabled .el-textarea__inner),
.readonly-mode :deep(.el-select .el-input.is-disabled .el-input__wrapper),
.readonly-mode :deep(.el-date-editor.is-disabled),
.readonly-mode :deep(.el-input-number.is-disabled .el-input__wrapper) {
  background:#f7f8fa;
  box-shadow:0 0 0 1px #dcdfe6 inset;
}
.readonly-mode :deep(.el-input.is-disabled .el-input__inner),
.readonly-mode :deep(.el-textarea.is-disabled .el-textarea__inner),
.readonly-mode :deep(.el-select .el-input.is-disabled .el-input__inner),
.readonly-mode :deep(.el-select.is-disabled .el-select__selected-item),
.readonly-mode :deep(.el-select.is-disabled .el-select__placeholder),
.readonly-mode :deep(.el-select.is-disabled .el-select__tags-text),
.readonly-mode :deep(.el-select.is-disabled .el-tag__content),
.readonly-mode :deep(.el-date-editor.is-disabled .el-range-input),
.readonly-mode :deep(.el-date-editor.is-disabled .el-range-separator),
.readonly-mode :deep(.el-input-number.is-disabled .el-input__inner),
.readonly-mode :deep(.el-tag),
.readonly-mode :deep(.ql-editor) {
  color:#303133;
  -webkit-text-fill-color:#303133;
}
.readonly-mode :deep(.el-select.is-disabled .el-tag) {
  background:#eef0f3;
  border-color:#d4d7de;
}
.readonly-mode :deep(.el-input.is-disabled .el-input__inner::placeholder),
.readonly-mode :deep(.el-textarea.is-disabled .el-textarea__inner::placeholder),
.readonly-mode :deep(.el-date-editor.is-disabled .el-range-input::placeholder) {
  color:#a8abb2;
  -webkit-text-fill-color:#a8abb2;
}
.page-header { display:flex; justify-content:space-between; align-items:center; font-weight:600; }
.activity-page-card { background:transparent; border:none; box-shadow:none; }
.activity-page-card :deep(> .el-card__header) { margin-bottom:18px; background:#fff; border:1px solid #ebeef5; border-radius:4px; box-shadow:0 1px 4px rgba(0,0,0,.04); }
.activity-page-card :deep(> .el-card__body) { padding:0; }
.steps-card { margin-bottom:20px; padding:12px 16px; background:#fff; border:1px solid #ebeef5; border-radius:4px; box-shadow:0 1px 4px rgba(0,0,0,.04); }
.activity-steps { margin-bottom:0; }
.step-pane { min-height:360px; }
.section-card { margin-bottom:16px; border:none; border-radius:4px; }
.section-card { margin-bottom:20px; border:1px solid #ebeef5; box-shadow:0 1px 4px rgba(0,0,0,.04); }
.section-card :deep(.el-card__header) { padding:12px 20px; background:#fafafa; border-bottom:1px solid #ebeef5; }
.toggle-section-card.is-collapsed :deep(.el-card__header) { border-bottom:none; }
.toggle-section-card.is-collapsed :deep(.el-card__body) { display:none; }
.section-title { color:#303133; font-size:16px; font-weight:600; }
.section-title-with-action { display:flex; align-items:center; justify-content:space-between; gap:16px; }
.share-toggle-checkbox,
.section-toggle-checkbox { font-weight:400; }
.basic-info-form :deep(.el-form-item),
.module-form :deep(.el-form-item) { display:block; margin-bottom:24px; }
.basic-info-form :deep(.el-form-item__label),
.module-form :deep(.el-form-item__label) { width:auto !important; height:auto; margin-bottom:8px; justify-content:flex-start; color:#303133; font-weight:600; line-height:22px; white-space:nowrap; }
.basic-info-form :deep(.el-form-item__content),
.module-form :deep(.el-form-item__content) { margin-left:0 !important; display:block; line-height:normal; }
.basic-info-form :deep(.el-input),
.basic-info-form :deep(.el-select),
.module-form :deep(.el-input),
.module-form :deep(.el-select) { width:100%; }
.image-upload-field { display:flex; align-items:center; gap:18px; min-height:104px; }
.share-upload-field { min-height:92px; }
.upload-hide-trigger :deep(.el-upload--picture-card) { display:none; }
.upload-size-tip { color:#909399; font-size:13px; line-height:1.7; }
.offline-switch-line { display:flex; align-items:center; justify-content:space-between; gap:24px; margin:4px 0 24px; padding:20px 0; border-top:1px solid #ebeef5; border-bottom:1px solid #ebeef5; }
.offline-switch-line:has(+ .offline-config-panel) { margin-bottom:0; }
.setting-title { margin-bottom:8px; color:#303133; font-size:15px; font-weight:600; }
.setting-desc { color:#606266; font-size:13px; line-height:1.5; }
.offline-config-panel { margin-bottom:24px; padding:18px 18px 0; border:1px solid #ebeef5; border-radius:4px; background:#fafafa; }
.basic-modular-mode :deep(.ql-container) { min-height:220px; }
.basic-modular-mode :deep(.ql-editor) { min-height:220px; }
.layer-copy-config { margin-top:8px; padding-top:24px; border-top:1px solid #ebeef5; }
.layer-copy-header { display:flex; align-items:center; justify-content:space-between; gap:16px; margin-bottom:16px; }
.layer-copy-title { color:#303133; font-size:15px; font-weight:600; }
.required-mark { color:#f56c6c; }
.layer-copy-actions { display:flex; align-items:center; gap:14px; color:#606266; font-size:14px; }
.layer-copy-actions strong { color:#f56c6c; }
.layer-copy-tabs { border:1px solid #dcdfe6; border-radius:4px; overflow:hidden; background:#fff; }
.layer-copy-tabs :deep(.el-tabs__header) { margin:0; background:#f5f7fa; }
.layer-copy-tabs :deep(.el-tabs__nav) { border-top:none; border-left:none; border-radius:0; }
.layer-copy-tabs :deep(.el-tabs__item) { min-width:128px; text-align:center; font-weight:500; }
.layer-copy-panel { padding:20px; }
.layer-copy-meta { display:flex; align-items:flex-start; justify-content:space-between; gap:24px; margin-bottom:18px; padding:16px 16px 0; background:#fafafa; border:1px solid #ebeef5; border-radius:4px; }
.layer-copy-meta :deep(.el-form-item) { display:block; margin-bottom:16px; }
.layer-copy-meta :deep(.el-form-item__label) { width:auto !important; height:auto; margin-bottom:8px; justify-content:flex-start; color:#303133; font-weight:600; line-height:22px; white-space:nowrap; }
.layer-copy-meta :deep(.el-form-item__content) { margin-left:0 !important; display:block; line-height:normal; }
.layer-title-input { width:360px; max-width:100%; }
.layer-copy-panel :deep(.ql-container) { min-height:180px; }
.layer-copy-panel :deep(.ql-editor) { min-height:180px; }
.form-tip { margin-top:4px; color:#909399; font-size:12px; line-height:1.4; }
.signup-row :deep(.el-form-item) { margin-bottom:16px; }
.signup-row :deep(.el-form-item__content) { display:block; }
.field-md { width:240px; max-width:100%; }
.field-lg { width:320px; max-width:100%; }
.field-xs { width:140px; max-width:100%; }
.date-range-field { width:300px; max-width:100%; }
.activity-edit :deep(.compact-date-range),
.activity-edit :deep(.mgm-date-range) { width:300px; max-width:100%; }
.activity-edit :deep(.reward-validity-picker) { width:320px; max-width:100%; flex:0 1 320px; }
.assembly-select-panel { padding:12px 14px; margin-bottom:16px; background:#fafafa; border:1px solid #ebeef5; border-radius:4px; }
.action-bar { display:flex; align-items:center; justify-content:space-between; margin-top:20px; padding:16px 20px; background:#fff; border:1px solid #ebeef5; border-radius:4px; box-shadow:0 1px 4px rgba(0,0,0,.04); }
.action-left, .action-right { width:120px; }
.action-center { display:flex; justify-content:center; gap:12px; }
.action-center .el-button { min-width:100px; }
.audit-actions { margin-top:16px; text-align:center; }
.progress-config { display:flex; flex-direction:column; gap:16px; }
.config-section { border:1px solid #ebeef5; border-radius:4px; background:#fff; overflow:hidden; }
.template-section { background:#fafafa; }
.section-header { min-height:48px; padding:0 20px; display:flex; align-items:center; justify-content:space-between; gap:16px; border-bottom:1px solid #ebeef5; background:#f5f7fa; color:#303133; font-size:15px; font-weight:600; }
.section-body { padding:20px; }
.compact-item { margin-bottom:0; }
.narrow-form :deep(.el-form-item__content) { max-width:720px; }
.limit-field { max-width:540px; }
.rule-block { position:relative; margin-top:16px; padding:16px 16px 0; border:1px solid #dcdfe6; border-radius:4px; background:#fafafa; }
.rule-block:first-child { margin-top:0; }
.rule-title { margin-bottom:16px; display:flex; justify-content:space-between; align-items:center; color:#606266; }
.layer-tabs :deep(.el-tabs__header) { margin:-20px -20px 20px; padding:0 20px; background:#fafafa; }
.layer-tabs :deep(.el-tabs__nav-wrap::after) { height:1px; }
.layer-tabs :deep(.el-tabs__item) { min-width:96px; padding:0 24px; text-align:center; }
.level-panel { padding-top:4px; }
.layer-activity { margin-top:18px; padding:18px; border:1px solid #dcdfe6; border-radius:4px; background:#fafafa; }
.activity-heading { margin-bottom:18px; display:flex; align-items:center; justify-content:space-between; gap:16px; color:#303133; }
.prerequisite-note { margin-left:12px; color:#f56c6c; font-size:12px; font-weight:400; }
.rule-actions { padding-top:14px; border-top:1px solid #ebeef5; }
.dependent-rule { border-color:#fbc4c4; background:#fef0f0; }
.inner-rule { background:#f5f7fa; }
.subsection-actions { margin:4px 0 12px; }
.inline-reward { margin-top:16px; padding:16px 16px 0; border-top:1px solid #ebeef5; }
.extra-forms-header { margin-bottom:12px; display:flex; align-items:center; justify-content:space-between; gap:12px; }
.extra-forms-title { font-size:15px; font-weight:600; color:#303133; }
.extra-forms-limit { margin-left:12px; color:#909399; font-size:12px; }
.extra-form-panel { margin-bottom:16px; padding:16px 18px; border:1px solid #dcdfe6; border-radius:4px; background:#fafafa; }
.extra-form-head { margin-bottom:14px; display:flex; align-items:center; justify-content:space-between; color:#303133; font-size:14px; font-weight:600; }
.extra-link-panel { padding:16px 18px 0; border:1px solid #dcdfe6; border-radius:4px; background:#fafafa; }
@media (max-width: 1200px) {
  .section-body :deep(.el-col) { max-width:100%; flex:0 0 100%; }
}
</style>
