<template>
  <div class="activity-view">
    <el-card v-if="form" class="activity-page-card">
      <template #header>
        <div class="page-header">
          <span>查看活动</span>
          <el-button @click="goBack">返回</el-button>
        </div>
      </template>

      <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="readonly-grid">
            <el-col :span="12"><ReadonlyField label="活动编号" :value="form.id" /></el-col>
            <el-col :span="12"><ReadonlyField label="状态" :value="statusText(form.status)" /></el-col>
            <el-col :span="12"><ReadonlyField label="活动标题（对内）" :value="form.internalTitle" /></el-col>
            <el-col :span="12"><ReadonlyField label="活动名称（对客）" :value="form.name" /></el-col>
            <el-col :span="12"><ReadonlyField label="活动类型" :value="form.category" /></el-col>
            <el-col :span="12"><ReadonlyField label="活动对象" :value="form.target" /></el-col>
            <el-col :span="12">
              <ReadonlyField label="活动小图">
                <ImagePreview :src="imageUrl(form.thumbnail)" />
              </ReadonlyField>
            </el-col>
            <el-col :span="12">
              <ReadonlyField label="活动头图">
                <ImagePreview :src="imageUrl(form.detailImage)" />
              </ReadonlyField>
            </el-col>
            <el-col :span="24">
              <div class="readonly-switch-line">
                <div>
                  <div class="setting-title">线下活动</div>
                  <div class="setting-desc">开启后，需配置线下活动所在的城市及具体地点</div>
                </div>
                <el-switch :model-value="!!form.offlineEnabled" disabled />
              </div>
              <div v-if="form.offlineEnabled" class="readonly-panel">
                <el-row :gutter="30">
                  <el-col :span="12"><ReadonlyField label="活动城市" :value="form.cityText || joinText(form.cities)" /></el-col>
                  <el-col :span="12"><ReadonlyField label="活动地点" :value="form.location" /></el-col>
                </el-row>
              </div>
            </el-col>
            <el-col :span="24">
              <ReadonlyField label="活动内容">
                <div class="rich-text-view" v-html="form.content || emptyHtml"></div>
              </ReadonlyField>
            </el-col>
            <el-col v-if="isLayerActivity" :span="24">
              <div class="layer-copy-config">
                <div class="layer-copy-header">
                  <div class="layer-copy-title"><span class="required-mark">*</span> 活动达标层级内容</div>
                  <span class="muted">已配置 <strong>{{ layerContents.length }}</strong> / 5 个层级</span>
                </div>
                <div class="layer-copy-tabs">
                  <el-tabs v-model="layerCopyActiveTab" type="card">
                    <el-tab-pane v-for="(level, index) in layerContents" :key="level.key || index" :label="level.title || layerTitle(index)" :name="String(index)">
                      <div class="layer-copy-panel">
                        <ReadonlyField label="Tab 标题" :value="level.title || layerTitle(index)" />
                        <ReadonlyField label="层级内容">
                          <div class="rich-text-view compact-rich-text" v-html="level.content || emptyHtml"></div>
                        </ReadonlyField>
                      </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 :model-value="!!form.sharable" disabled>自定义微信分享</el-checkbox>
            </div>
          </template>
          <el-row v-if="form.sharable" :gutter="30" class="readonly-grid">
            <el-col :span="12"><ReadonlyField label="分享名称" :value="form.shareTitle" /></el-col>
            <el-col :span="12">
              <ReadonlyField label="分享图片">
                <ImagePreview :src="imageUrl(form.shareImage)" small />
              </ReadonlyField>
            </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="readonly-grid">
            <el-col :span="12"><ReadonlyField label="CD staff ID" :value="form.ownerStaffId" /></el-col>
            <el-col :span="12"><ReadonlyField label="SCRM activity code" :value="form.scrmActivityCode" /></el-col>
            <el-col :span="12"><ReadonlyField label="SCRM channel code" :value="form.scrmChannelCode" /></el-col>
            <el-col :span="12"><ReadonlyField label="Label" :value="joinText(form.labels)" /></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="readonly-grid">
            <el-col :span="12"><ReadonlyField label="活动时间" :value="rangeText(form.activityTime)" /></el-col>
            <el-col :span="12"><ReadonlyField label="展示时间" :value="rangeText(form.displayTime)" /></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="readonly-grid">
            <el-col :span="12"><ReadonlyField label="展示客群" :value="crowdNames(form.visibleCrowdIds, form.visibleCrowdId, form.visibleCrowds)" /></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="readonly-grid">
            <el-col :span="12"><ReadonlyField label="Campaign ID" :value="campaignName(form.campaignId)" /></el-col>
            <el-col :span="12"><ReadonlyField label="Channel ID" :value="channelName(form.channelId)" /></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="readonly-grid">
            <el-col :span="24"><ReadonlyField label="权益首页" :value="displayText(form.showOnHome)" /></el-col>
            <el-col :span="24">
              <ReadonlyField label="组装页">
                <div class="display-value">{{ displayText(form.showOnAssembly) }}</div>
                <div v-if="form.showOnAssembly" class="sub-value">{{ assemblyNames(form.assemblyPageIds) }}</div>
              </ReadonlyField>
            </el-col>
            <el-col :span="24"><ReadonlyField label="活动轮播图" :value="displayText(form.showOnCarousel)" /></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 :model-value="!!form.needSignup" disabled>需要报名</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="readonly-grid">
              <el-col :span="12"><ReadonlyField label="报名客群" :value="crowdNames(form.signupCrowdIds, form.signupCrowdId, form.signupCrowds)" /></el-col>
              <el-col :span="12"><ReadonlyField label="报名时间" :value="rangeText(form.signupTime)" /></el-col>
            </el-row>
          </el-card>

          <el-card shadow="never" class="section-card toggle-section-card" :class="{ 'is-collapsed': !form.needConfirm }" :body-style="form.needConfirm ? undefined : { display: 'none', padding: '0' }">
            <template #header>
              <div class="section-title section-title-with-action">
                <span>报名确认</span>
                <el-checkbox :model-value="!!form.needConfirm" disabled>报名确认</el-checkbox>
              </div>
            </template>
            <el-row v-if="form.needConfirm" :gutter="30" class="readonly-grid">
              <el-col :span="12"><ReadonlyField label="报名确认文案" :value="form.confirmText" /></el-col>
            </el-row>
          </el-card>

          <el-card shadow="never" class="section-card toggle-section-card" :class="{ 'is-collapsed': !form.needExtraInfo }" :body-style="form.needExtraInfo ? undefined : { display: 'none', padding: '0' }">
            <template #header>
              <div class="section-title section-title-with-action">
                <span>补充信息表单</span>
                <el-checkbox :model-value="!!form.needExtraInfo" disabled>补充信息</el-checkbox>
              </div>
            </template>
            <div v-if="form.needExtraInfo" class="extra-form-list">
              <div v-for="(extra, index) in normalizedExtraForms" :key="index" class="readonly-panel extra-form-panel">
                <div class="panel-title">补充信息{{ index + 1 }}</div>
                <el-row :gutter="30">
                  <el-col :span="12"><ReadonlyField label="字段名称" :value="extra.name" /></el-col>
                  <el-col :span="12"><ReadonlyField label="提示文案" :value="extra.placeholder" /></el-col>
                  <el-col :span="12"><ReadonlyField label="字段类型" :value="fieldTypeText(extra.type)" /></el-col>
                  <el-col :span="12"><ReadonlyField label="是否必填" :value="yesNo(extra.required)" /></el-col>
                  <el-col :span="12"><ReadonlyField label="最大长度" :value="extra.maxLength" /></el-col>
                </el-row>
              </div>
              <ReadonlyField label="第三方链接" :value="form.extraInfoLink" />
            </div>
          </el-card>

          <el-card shadow="never" class="section-card toggle-section-card" :class="{ 'is-collapsed': !form.quotaEnabled }" :body-style="form.quotaEnabled ? undefined : { display: 'none', padding: '0' }">
            <template #header>
              <div class="section-title section-title-with-action">
                <span>名额控制</span>
                <el-checkbox :model-value="!!form.quotaEnabled" disabled>名额控制</el-checkbox>
              </div>
            </template>
            <el-row v-if="form.quotaEnabled" :gutter="30" class="readonly-grid">
              <el-col :span="12"><ReadonlyField label="报名名额" :value="form.quota" /></el-col>
              <el-col :span="12"><ReadonlyField label="已报名人数" :value="form.signedCount" /></el-col>
            </el-row>
          </el-card>

          <el-card shadow="never" class="section-card toggle-section-card" :class="{ 'is-collapsed': !form.signupGuideEnabled }" :body-style="form.signupGuideEnabled ? undefined : { display: 'none', padding: '0' }">
            <template #header>
              <div class="section-title section-title-with-action">
                <span>报名成功页配置</span>
                <el-checkbox :model-value="!!form.signupGuideEnabled" disabled>报名成功页配置</el-checkbox>
              </div>
            </template>
            <el-row v-if="form.signupGuideEnabled" :gutter="30" class="readonly-grid">
              <el-col :span="12"><ReadonlyField label="标题" :value="form.signupSuccessTitle" /></el-col>
              <el-col :span="12"><ReadonlyField label="描述" :value="form.signupSuccessDescription" /></el-col>
            </el-row>
          </el-card>
        </template>
      </div>

      <div v-show="activeStep === 3" class="step-pane">
        <el-card shadow="never" class="section-card">
          <template #header><div class="section-title">进度模板</div></template>
          <el-row :gutter="30" class="readonly-grid">
            <el-col :span="12"><ReadonlyField label="进度模板" :value="templateText(form.achievementTemplate)" /></el-col>
            <el-col v-if="form.achievementTemplate === 'LAYER'" :span="12"><ReadonlyField label="层级数量" :value="form.layerCount || achievementLayers.length" /></el-col>
          </el-row>
        </el-card>

        <template v-if="form.achievementTemplate === 'NTB'">
          <el-card shadow="never" class="section-card">
            <template #header><div class="section-title">达标进度提示话术配置</div></template>
            <el-row :gutter="30" class="readonly-grid">
              <el-col :span="12"><ReadonlyField label="未达标提示" :value="form.progressCopy?.unreached" /></el-col>
              <el-col :span="12"><ReadonlyField label="已达标提示" :value="form.progressCopy?.reached" /></el-col>
              <el-col :span="12"><ReadonlyField label="达标进度提示" :value="form.progressCopy?.help" /></el-col>
            </el-row>
          </el-card>
          <el-card shadow="never" class="section-card">
            <template #header><div class="section-title">达标规则标签配置</div></template>
            <RuleSummary v-for="(rule, index) in ntbRules" :key="rule.key || index" :rule="rule" :index="index" />
          </el-card>
          <RewardSummary :reward="form.templateRewards?.NTB" :grant-plans="grantPlans" />
        </template>

        <template v-else-if="form.achievementTemplate === 'MGM'">
          <RewardSummary :reward="form.templateRewards?.MGM" :grant-plans="grantPlans" />
          <el-card shadow="never" class="section-card">
            <template #header><div class="section-title">达标规则标签配置</div></template>
            <el-row :gutter="30" class="readonly-grid">
              <el-col :span="12"><ReadonlyField label="已达标展示标签" :value="form.mgmAchievedTag" /></el-col>
            </el-row>
            <RuleSummary v-for="(rule, index) in mgmRules" :key="rule.key || index" :rule="rule" :index="index" />
          </el-card>
          <el-card shadow="never" class="section-card">
            <template #header><div class="section-title">被推荐进度配置</div></template>
            <el-row :gutter="30" class="readonly-grid">
              <el-col :span="12"><ReadonlyField label="规则标签1描述" :value="form.mgmReferredProgress?.labelOne" /></el-col>
              <el-col :span="12"><ReadonlyField label="规则标签2描述" :value="form.mgmReferredProgress?.labelTwo" /></el-col>
              <el-col :span="12"><ReadonlyField label="是否有进阶奖励" :value="yesNo(form.mgmReferredProgress?.advancedReward)" /></el-col>
              <el-col v-if="form.mgmReferredProgress?.advancedReward" :span="12"><ReadonlyField label="进阶奖励规则标签" :value="advancedRuleText" /></el-col>
              <el-col v-if="form.mgmReferredProgress?.advancedReward" :span="12"><ReadonlyField label="进阶奖励规则标签描述" :value="form.mgmReferredProgress?.advancedRuleText" /></el-col>
            </el-row>
          </el-card>
        </template>

        <template v-else-if="form.achievementTemplate === 'LAYER'">
          <el-card shadow="never" class="section-card">
            <template #header><div class="section-title">达标层级配置</div></template>
            <el-tabs v-model="achievementLayerActiveTab" type="card" class="view-tabs">
              <el-tab-pane v-for="(level, levelIndex) in achievementLayers" :key="level.key || levelIndex" :label="`层级${levelIndex + 1}`" :name="String(levelIndex)">
                <el-row :gutter="30" class="readonly-grid">
                  <el-col :span="12"><ReadonlyField label="可参与人群" :value="crowdName(level.crowdId)" /></el-col>
                  <el-col :span="12"><ReadonlyField label="层级标题" :value="level.title" /></el-col>
                </el-row>
                <div v-for="(activity, activityIndex) in level.activities || []" :key="activity.key || activityIndex" class="layer-activity">
                  <div class="panel-title">活动{{ activityIndex + 1 }}</div>
                  <el-row :gutter="30" class="readonly-grid">
                    <el-col :span="12"><ReadonlyField label="活动标题" :value="activity.title" /></el-col>
                    <el-col :span="12"><ReadonlyField label="活动描述" :value="activity.description" /></el-col>
                  </el-row>
                  <RuleSummary v-for="(rule, ruleIndex) in activity.rules || []" :key="rule.key || ruleIndex" :rule="rule" :index="ruleIndex" />
                  <RewardSummary inner :reward="activity.reward" :grant-plans="grantPlans" />
                </div>
              </el-tab-pane>
            </el-tabs>
          </el-card>
        </template>
      </div>

      <div v-show="activeStep === 4" class="step-pane">
        <el-card shadow="never" class="section-card toggle-section-card" :class="{ 'is-collapsed': !form.mutexEnabled }" :body-style="form.mutexEnabled ? undefined : { display: 'none', padding: '0' }">
          <template #header>
            <div class="section-title section-title-with-action">
              <span>互斥设置</span>
              <el-checkbox :model-value="!!form.mutexEnabled" disabled>参与互斥</el-checkbox>
            </div>
          </template>
          <el-row v-if="form.mutexEnabled" :gutter="30" class="readonly-grid">
            <el-col :span="12"><ReadonlyField label="互斥组" :value="form.mutexGroup" /></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="readonly-grid">
            <el-col :span="12"><ReadonlyField label="报名成功模板" :value="notificationName(form.signupNoticeTemplateId)" /></el-col>
            <el-col :span="12"><ReadonlyField label="开始前提醒模板" :value="notificationName(form.beforeStartTemplateId)" /></el-col>
            <el-col :span="12"><ReadonlyField label="达标发奖通知模板（需领取）" :value="notificationName(form.rewardTemplateId)" /></el-col>
            <el-col :span="12"><ReadonlyField label="达标发奖通知模板（无需领取）" :value="notificationName(form.rewardNoClaimTemplateId)" /></el-col>
          </el-row>
        </el-card>
      </div>

      <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">返回</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-empty v-else description="活动不存在">
      <el-button type="primary" @click="goBack">返回活动管理</el-button>
    </el-empty>
  </div>
</template>

<script>
import { h } from 'vue'
import { ArrowLeft, ArrowRight, Bell, InfoFilled, Medal, Setting, User } 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'

const emptyText = '-'

const ReadonlyField = {
  name: 'ReadonlyField',
  props: {
    label: { type: String, required: true },
    value: { type: [String, Number, Boolean], default: '' }
  },
  render() {
    const content = this.$slots.default
      ? this.$slots.default()
      : h('div', { class: 'display-value' }, this.value === '' || this.value === undefined || this.value === null ? emptyText : String(this.value))
    return h('div', { class: 'readonly-field' }, [
      h('div', { class: 'readonly-label' }, this.label),
      content
    ])
  }
}

const ImagePreview = {
  name: 'ImagePreview',
  props: {
    src: { type: String, default: '' },
    small: { type: Boolean, default: false }
  },
  render() {
    if (!this.src) return h('div', { class: ['image-empty', { small: this.small }] }, '暂无图片')
    return h('div', { class: ['image-preview', { small: this.small }] }, [
      h('img', { src: this.src, alt: '图片预览' })
    ])
  }
}

const RuleSummary = {
  name: 'RuleSummary',
  props: {
    rule: { type: Object, required: true },
    index: { type: Number, required: true }
  },
  methods: {
    valueText(value) {
      return value === '' || value === undefined || value === null ? emptyText : String(value)
    },
    yesNo(value) {
      return value ? '是' : '否'
    },
    rangeText(range) {
      return Array.isArray(range) && range.length === 2 ? `${range[0]} 至 ${range[1]}` : emptyText
    }
  },
  render() {
    const r = this.rule || {}
    const isOversea = r.field === '境外消费'
    const main = isOversea
      ? `${this.valueText(r.field)} / 消费时间 ${this.valueText(r.consumptionTimeOperator)} ${this.valueText(r.consumptionEndDate)} / ${this.valueText(r.consumptionDimension)} ${this.valueText(r.operator)} ${this.valueText(r.value)}`
      : `${this.valueText(r.field)} / ${this.valueText(r.operator)} / ${r.field === '开户时间' ? this.rangeText(r.dateRange) : this.valueText(r.value)}`
    const children = [
      h('div', { class: 'panel-title' }, `规则标签${this.index + 1}`),
      h('div', { class: 'rule-main' }, main)
    ]
    if (!isOversea && r.field !== '开户时间') {
      children.push(h('div', { class: 'rule-meta' }, [
        h('span', `开户当月必须达标：${this.yesNo(r.openingMonthRequired)}`),
        h('span', `连续达标：${this.yesNo(r.continuous)}`),
        h('span', `连续月份：${this.valueText(r.months)}`),
        h('span', `允许断开：${this.yesNo(r.allowBreak)}`)
      ]))
    }
    children.push(h('div', { class: 'rule-meta' }, [
      h('span', `规则标题：${this.valueText(r.labelDescription || r.reachedText)}`),
      h('span', `规则描述：${this.valueText(r.unreachedText)}`),
      h('span', `提示：${this.valueText(r.progressText || r.failureReason)}`)
    ]))
    return h('div', { class: 'readonly-panel rule-summary' }, children)
  }
}

const RewardSummary = {
  name: 'RewardSummary',
  props: {
    reward: { type: Object, default: () => ({}) },
    grantPlans: { type: Array, default: () => [] },
    inner: { type: Boolean, default: false }
  },
  computed: {
    planName() {
      const planId = this.reward?.planId || this.reward?.grantPlanId
      const target = this.grantPlans.find((item) => item.id === planId)
      return target ? `${target.id}-${target.name}` : (planId || emptyText)
    },
    validityText() {
      const range = this.reward?.validity || this.reward?.rewardValidity
      return Array.isArray(range) && range.length === 2 ? `${range[0]} 至 ${range[1]}` : emptyText
    }
  },
  render() {
    const card = h('div', { class: ['reward-summary', { inner: this.inner }] }, [
      h('div', { class: 'section-title reward-title' }, '达标奖励配置'),
      h('div', { class: 'reward-grid' }, [
        h(ReadonlyField, { label: '达标发放', value: this.reward?.type || emptyText }),
        h(ReadonlyField, { label: '选择权益', value: this.planName }),
        h(ReadonlyField, { label: '权益有效期', value: this.validityText }),
        h(ReadonlyField, { label: '权益赠送次数', value: `${this.reward?.grantPeriod || emptyText} / ${this.reward?.times || 1} 次` })
      ])
    ])
    if (this.inner) return card
    return h('div', { class: 'section-card reward-summary-card' }, [card])
  }
}

export default {
  name: 'ActivityView',
  components: { ImagePreview, ReadonlyField, RewardSummary, RuleSummary },
  data() {
    return {
      ArrowLeft,
      ArrowRight,
      activeStep: 0,
      layerCopyActiveTab: '0',
      achievementLayerActiveTab: '0',
      assemblyPages: [],
      campaignOptions: [],
      channelOptions: [],
      stepItems: [
        { title: '基础信息', icon: InfoFilled },
        { title: '展示规则', icon: Setting },
        { title: '客群与报名', icon: User },
        { title: '进度与奖励', icon: Medal },
        { title: '互斥与通知', icon: Bell }
      ],
      emptyHtml: '<span class="empty-rich-text">暂无内容</span>'
    }
  },
  computed: {
    form() {
      const row = activityStore.getActivity(this.$route.params.id)
      if (!row) return null
      return { ...activityStore.emptyActivity(), ...row }
    },
    crowds() { return activityStore.activityCrowds },
    grantPlans() { return activityStore.activityGrantPlans },
    notifications() { return smsTemplateStore.state.list },
    isLayerActivity() {
      return this.form?.category === '层层礼' || this.form?.achievementTemplate === 'LAYER'
    },
    layerContents() {
      const list = Array.isArray(this.form?.layerContents) ? this.form.layerContents : []
      return list.length ? list : [{ key: 'layer-copy-1', title: '层级一', content: '' }]
    },
    achievementLayers() {
      return Array.isArray(this.form?.achievementLayers) ? this.form.achievementLayers : []
    },
    normalizedExtraForms() {
      const list = Array.isArray(this.form?.extraForms) ? this.form.extraForms : []
      return list.flatMap((item) => Array.isArray(item?.fields) ? item.fields : [item]).filter(Boolean).slice(0, 2)
    },
    ntbRules() {
      const timeRules = Array.isArray(this.form?.ntbTimeRules) ? this.form.ntbTimeRules : []
      const rules = Array.isArray(this.form?.ntbRules) ? this.form.ntbRules : []
      return [...timeRules, ...rules]
    },
    mgmRules() {
      return Array.isArray(this.form?.mgmRules) ? this.form.mgmRules : []
    },
    advancedRuleText() {
      const cfg = this.form?.mgmReferredProgress || {}
      return `${cfg.advancedRuleField || emptyText} / ${cfg.advancedOperator || emptyText} / ${cfg.advancedValue ?? emptyText}`
    }
  },
  created() {
    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 = []
      }
    },
    async fetchChannelOptions() {
      try {
        const { campaignOptions, channelOptions } = await fetchLinkOptions()
        this.campaignOptions = campaignOptions
        this.channelOptions = channelOptions
      } catch (e) {
        this.campaignOptions = []
        this.channelOptions = []
      }
    },
    valueText(value) {
      return value === '' || value === undefined || value === null ? emptyText : String(value)
    },
    yesNo(value) {
      return value ? '是' : '否'
    },
    displayText(value) {
      return value ? '显示' : '不显示'
    },
    rangeText(range) {
      return Array.isArray(range) && range.length === 2 ? `${range[0]} 至 ${range[1]}` : emptyText
    },
    joinText(list) {
      return Array.isArray(list) && list.length ? list.join('、') : emptyText
    },
    imageUrl(value) {
      if (Array.isArray(value) && value.length) return value[0]?.url || value[0]
      return typeof value === 'string' ? value : ''
    },
    layerTitle(index) {
      const names = ['一', '二', '三', '四', '五']
      return `层级${names[index] || index + 1}`
    },
    crowdName(id) {
      if (!id) return emptyText
      const target = this.crowds.find((item) => item.id === id)
      return target ? `${target.id}-${target.name}` : id
    },
    crowdNames(ids, singleId, fallback) {
      if (Array.isArray(ids) && ids.length) return ids.map((id) => this.crowdName(id)).join('、')
      if (singleId) return this.crowdName(singleId)
      return this.joinText(fallback)
    },
    assemblyNames(ids) {
      if (!Array.isArray(ids) || !ids.length) return emptyText
      return ids.map((id) => {
        const target = this.assemblyPages.find((item) => item.id === id)
        return target ? `${target.name}（${target.id}）` : id
      }).join('、')
    },
    campaignName(id) {
      if (!id) return emptyText
      return this.campaignOptions.find((item) => item.value === id)?.label || id
    },
    channelName(id) {
      if (!id) return emptyText
      return this.channelOptions.find((item) => item.value === id)?.label || id
    },
    notificationName(id) {
      if (!id) return emptyText
      const target = this.notifications.find((item) => item.id === id)
      return target ? `${target.id}-${target.name}` : id
    },
    fieldTypeText(type) {
      return { text: '文本', number: '数字' }[type] || this.valueText(type)
    },
    templateText(type) {
      return { NTB: 'NTB（新客达标）', MGM: 'MGM（推荐有礼）', LAYER: '层层礼' }[type] || this.valueText(type)
    },
    statusText(status) {
      return { draft: '草稿', pending: '待审核', approved: '审核通过', published: '已发布', offline: '已下线' }[status] || this.valueText(status)
    },
    nextStep() {
      if (this.activeStep < this.stepItems.length - 1) this.activeStep += 1
    },
    prevStep() {
      if (this.activeStep > 0) this.activeStep -= 1
    },
    goBack() {
      this.$router.push('/customization/hsbc/activities')
    }
  }
}
</script>

<style scoped>
.activity-view { padding:20px; }
.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:20px; border:1px solid #ebeef5; border-radius:4px; box-shadow:0 1px 4px rgba(0,0,0,.04); background:#fff; overflow:hidden; }
.section-card :deep(.el-card__header) { padding:12px 20px; background:#fafafa; border-bottom:1px solid #ebeef5; }
.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; }
.toggle-section-card.is-collapsed :deep(.el-card__header) { border-bottom:none; }
.toggle-section-card.is-collapsed :deep(.el-card__body) { display:none; }
.readonly-grid { padding:2px 0 0; }
.readonly-field { display:block; margin-bottom:24px; }
.readonly-label { margin-bottom:8px; color:#303133; font-size:14px; font-weight:600; line-height:22px; white-space:nowrap; }
.display-value {
  min-height:32px;
  padding:5px 11px;
  color:#606266;
  font-size:14px;
  line-height:20px;
  word-break:break-word;
  background:#f5f7fa;
  border:1px solid #e4e7ed;
  border-radius:4px;
  cursor:not-allowed;
  box-sizing:border-box;
}
.sub-value { margin-top:4px; color:#606266; font-size:13px; line-height:20px; }
.muted { color:#606266; font-size:14px; }
.muted strong { color:#f56c6c; }
.image-preview { width:180px; height:104px; border:1px solid #dcdfe6; border-radius:4px; overflow:hidden; background:#f7f8fa; }
.image-preview.small { width:88px; height:88px; }
.image-preview img { width:100%; height:100%; object-fit:cover; display:block; }
.image-empty { width:180px; height:104px; display:flex; align-items:center; justify-content:center; color:#909399; border:1px dashed #cfd6df; border-radius:4px; background:#fafafa; }
.image-empty.small { width:88px; height:88px; }
.readonly-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; }
.setting-title { margin-bottom:8px; color:#303133; font-size:15px; font-weight:600; }
.setting-desc { color:#606266; font-size:13px; line-height:1.5; }
.readonly-panel { margin-bottom:20px; padding:16px 18px 0; border:1px solid #ebeef5; border-radius:4px; background:#fafafa; }
.panel-title { margin-bottom:14px; color:#303133; font-size:15px; font-weight:600; }
.rich-text-view { min-height:160px; padding:12px 14px; color:#606266; line-height:1.7; border:1px solid #e4e7ed; border-radius:4px; background:#f5f7fa; cursor:not-allowed; }
.compact-rich-text { min-height:120px; }
.empty-rich-text { color:#909399; }
.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-tabs,
.view-tabs { border:1px solid #dcdfe6; border-radius:4px; overflow:hidden; background:#fff; }
.layer-copy-tabs :deep(.el-tabs__header),
.view-tabs :deep(.el-tabs__header) { margin:0; background:#f5f7fa; }
.layer-copy-tabs :deep(.el-tabs__nav),
.view-tabs :deep(.el-tabs__nav) { border-top:none; border-left:none; border-radius:0; }
.layer-copy-tabs :deep(.el-tabs__item),
.view-tabs :deep(.el-tabs__item) { min-width:120px; text-align:center; font-weight:500; }
.layer-copy-panel,
.view-tabs :deep(.el-tabs__content) { padding:20px; }
.extra-form-list { display:flex; flex-direction:column; gap:16px; }
.extra-form-panel { margin-bottom:0; }
.rule-summary { margin-bottom:16px; padding-bottom:16px; }
.rule-main { margin-bottom:12px; color:#303133; line-height:22px; }
.rule-meta { display:flex; flex-wrap:wrap; gap:10px 22px; color:#606266; font-size:13px; line-height:22px; }
.reward-summary-card { padding:0; }
.reward-summary { padding:0 20px 20px; background:#fff; }
.reward-summary.inner { margin-top:18px; padding:16px 18px 0; border:1px solid #ebeef5; border-radius:4px; background:#fff; }
.reward-title { margin:0 -20px 18px; padding:12px 20px; background:#fafafa; border-bottom:1px solid #ebeef5; }
.reward-summary.inner .reward-title { margin:-16px -18px 18px; padding:12px 18px; }
.reward-grid { display:grid; grid-template-columns:repeat(2, minmax(0, 1fr)); column-gap:30px; }
.layer-activity { margin-top:20px; padding:18px 18px 2px; border:1px solid #ebeef5; border-radius:4px; background:#fafafa; }
.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; }
@media (max-width:1200px) {
  .reward-grid { grid-template-columns:1fr; }
  .activity-view :deep(.el-col) { max-width:100%; flex:0 0 100%; }
}
</style>
