<template>
  <div class="achievement-config">
    <div class="template-row">
      <el-form-item label="进度模板">
        <el-select v-model="form.achievementTemplate" clearable placeholder="可选" style="width:200px" @change="handleTemplateChange">
          <el-option label="NTB（新客达标）" value="NTB" />
          <el-option label="MGM（推荐有礼）" value="MGM" />
          <el-option label="层层礼" value="LAYER" />
        </el-select>
      </el-form-item>
      <el-form-item v-if="form.achievementTemplate === 'LAYER'" label="层级数量" required>
        <el-input-number v-model="form.layerCount" :min="1" :max="5" @change="syncLayerCount" />
      </el-form-item>
    </div>

    <template v-if="form.achievementTemplate === 'NTB'">
      <section class="config-block">
        <h3>达标进度提示话术配置</h3>
        <div class="field-panel compact-copy-panel">
          <el-form-item label="未达标提示" label-width="140px">
            <el-input v-model="form.progressCopy.unreached" class="compact-copy-input" />
          </el-form-item>
          <el-form-item label="已达标提示" label-width="140px">
            <el-input v-model="form.progressCopy.reached" class="compact-copy-input" />
          </el-form-item>
          <el-form-item label="达标进度提示" label-width="140px">
            <el-input v-model="form.progressCopy.help" class="compact-copy-input" placeholder="配置问号弹窗提示内容" />
          </el-form-item>
        </div>
      </section>

      <section class="config-block">
        <h3>达标规则标签配置</h3>
        <el-button v-if="!readonly" :disabled="form.ntbTimeRules.length >= 1" :icon="Plus" @click="addTimeRule">添加时间标签</el-button>
        <div v-for="(rule, index) in form.ntbTimeRules" :key="rule.key" class="time-rule">
          <el-form-item label="规则标签" label-width="120px" required>
            <div class="time-rule-controls">
              <el-select v-model="rule.field" class="compact-field-select">
                <el-option label="开户时间" value="开户时间" />
              </el-select>
              <el-select v-model="rule.operator" class="compact-operator-select">
                <el-option label="介于" value="介于" />
              </el-select>
              <el-date-picker
                v-model="rule.dateRange"
                class="compact-date-range"
                type="daterange"
                value-format="YYYY-MM-DD"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
              />
            </div>
          </el-form-item>
          <el-button v-if="!readonly" class="time-rule-delete" type="danger" link :icon="Delete" title="删除时间标签" @click="form.ntbTimeRules.splice(index, 1)" />
        </div>
        <el-button v-if="!readonly" type="primary" :icon="Plus" @click="addRule(form.ntbRules)">添加进度标签</el-button>
        <ActivityRuleEditor v-for="(rule, index) in form.ntbRules" :key="rule.key" :rule="rule" :index="index" mode="ntb" :removable="!readonly" @remove="form.ntbRules.splice(index, 1)" />
      </section>

      <section class="config-block reward-section">
        <ActivityRewardEditor :reward="form.templateRewards.NTB" :grant-plans="grantPlans" />
      </section>
    </template>

    <template v-else-if="form.achievementTemplate === 'MGM'">
      <section class="config-block reward-section">
        <ActivityRewardEditor :reward="form.templateRewards.MGM" :grant-plans="grantPlans" />
      </section>
      <section class="config-block">
        <h3>达标规则标签配置</h3>
        <div class="field-panel">
          <el-form-item label="已达标展示标签" required><el-select v-model="form.mgmAchievedTag" style="width:260px"><el-option label="客户MSC Group" value="客户MSC Group" /></el-select></el-form-item>
        </div>
        <el-button v-if="!readonly" type="primary" :icon="Plus" @click="addMgmRule">添加进度标签</el-button>
        <ActivityRuleEditor v-for="(rule, index) in form.mgmRules" :key="rule.key" :rule="rule" :index="index" mode="mgm" :removable="!readonly && form.mgmRules.length > 1" @remove="form.mgmRules.splice(index, 1)" />
      </section>
      <section class="config-block">
        <h3>被推荐进度配置</h3>
        <div class="field-panel mgm-referred-panel">
          <el-form-item label="规则标签1描述" label-width="180px" required>
            <el-input v-model="form.mgmReferredProgress.labelOne" class="mgm-referred-copy-input" />
          </el-form-item>
          <el-form-item label="规则标签2描述" label-width="180px" required>
            <el-input v-model="form.mgmReferredProgress.labelTwo" class="mgm-referred-copy-input" />
          </el-form-item>
          <el-form-item label="是否有进阶奖励" label-width="180px" required>
            <el-select v-model="form.mgmReferredProgress.advancedReward" class="boolean-select">
              <el-option label="是" :value="true" />
              <el-option label="否" :value="false" />
            </el-select>
          </el-form-item>
          <template v-if="form.mgmReferredProgress.advancedReward">
            <el-form-item label="进阶奖励规则标签" label-width="180px" required>
              <div class="mgm-referred-rule-controls">
                <el-select v-model="form.mgmReferredProgress.advancedRuleField" class="mgm-referred-field-select">
                  <el-option label="TRB值（含家庭账户）" value="TRB值（含家庭账户）" />
                </el-select>
                <el-select v-model="form.mgmReferredProgress.advancedOperator" class="mgm-referred-operator-select">
                  <el-option label="大于等于" value="大于等于" />
                </el-select>
                <el-input-number v-model="form.mgmReferredProgress.advancedValue" :min="0" :controls="false" class="mgm-referred-value-input" />
              </div>
            </el-form-item>
            <el-form-item label="进阶奖励规则标签描述" label-width="180px" required>
              <el-input v-model="form.mgmReferredProgress.advancedRuleText" class="mgm-referred-copy-input" />
            </el-form-item>
          </template>
        </div>
      </section>
    </template>

    <template v-else-if="form.achievementTemplate === 'LAYER'">
      <section class="config-block">
        <h3>达标层级配置</h3>
        <el-tabs v-model="activeLayer" class="layer-tabs">
          <el-tab-pane v-for="(level, levelIndex) in form.achievementLayers" :key="level.key" :label="`层级${levelIndex + 1}`" :name="String(levelIndex)">
            <div class="layer-meta-fields">
              <el-form-item label="可参与人群" label-width="120px">
                <el-select v-model="level.crowdId" class="compact-copy-input">
                  <el-option v-for="item in crowds" :key="item.id" :label="`${item.id}-${item.name}`" :value="item.id" />
                </el-select>
              </el-form-item>
              <el-form-item label="层级标题" label-width="120px">
                <el-input v-model="level.title" class="compact-copy-input" />
              </el-form-item>
            </div>
            <el-button v-if="!readonly" type="primary" :icon="Plus" @click="addActivity(level)">添加活动</el-button>

            <div v-for="(activity, activityIndex) in level.activities" :key="activity.key" class="layer-activity">
              <div class="activity-head">
                <div><strong>活动{{ activityIndex + 1 }}</strong><span v-if="activityIndex > 0" class="notice">*注意：活动{{ activityIndex + 1 }}达标前提为活动{{ activityIndex }}</span></div>
                <el-button v-if="!readonly && level.activities.length > 1" type="danger" link :icon="Delete" @click="level.activities.splice(activityIndex, 1)">删除活动</el-button>
              </div>
              <div class="layer-activity-fields">
                <el-form-item label="活动标题" label-width="120px">
                  <el-input v-model="activity.title" class="compact-copy-input" />
                </el-form-item>
                <el-form-item label="活动描述" label-width="120px">
                  <el-input v-model="activity.description" class="compact-copy-input" />
                </el-form-item>
              </div>
              <el-button v-if="!readonly" type="primary" :icon="Plus" @click="addRule(activity.rules)">添加进度标签</el-button>
              <ActivityRuleEditor v-for="(rule, ruleIndex) in activity.rules" :key="rule.key" :rule="rule" :index="ruleIndex" mode="layer" :dependent="activityIndex > 0" :removable="!readonly && activity.rules.length > 1" @remove="activity.rules.splice(ruleIndex, 1)" />
              <div class="activity-reward"><ActivityRewardEditor :reward="activity.reward" :grant-plans="grantPlans" /></div>
            </div>
          </el-tab-pane>
        </el-tabs>
      </section>
    </template>
  </div>
</template>

<script>
import { Delete, Plus } from '@element-plus/icons-vue'
import ActivityRewardEditor from './ActivityRewardEditor.vue'
import ActivityRuleEditor from './ActivityRuleEditor.vue'

const key = (prefix) => `${prefix}-${Date.now()}-${Math.random()}`

export default {
  name: 'ActivityAchievementConfig',
  components: { ActivityRewardEditor, ActivityRuleEditor },
  props: {
    form: { type: Object, required: true },
    crowds: { type: Array, default: () => [] },
    grantPlans: { type: Array, default: () => [] },
    readonly: { type: Boolean, default: false }
  },
  data() { return { Delete, Plus, activeLayer: '0' } },
  created() { this.normalize() },
  methods: {
    reward(type) { return { type, planId: '', amount: 3200000, validity: [], grantPeriod: '整个周期', times: 1 } },
    rule(field = 'TRB值（含家庭账户）') {
      return {
        key: key('rule'), field, operator: field === '开户时间' ? '介于' : '大于等于', value: field === '境外消费' ? 1 : 500000,
        dateRange: [], openingMonthRequired: false, continuous: field === 'TRB值（含家庭账户）', months: 3, allowBreak: true,
        labelDescription: '', reachedText: '', unreachedText: '', progressText: '', failureReason: '', afterOpeningMonths: 3, requiredMonths: 1,
        consumptionTimeOperator: '小于等于', consumptionEndDate: '', consumptionDimension: '笔数',
        compareRequired: true, baseMonth: '', newCategoryCount: 1, limitFirstRuleMonth: true
      }
    },
    activity(index) {
      const field = index === 1 ? '境外消费' : 'TRB值（含家庭账户）'
      return { key: key('activity'), title: '', description: '', rules: [this.rule(field)], reward: this.reward('权益') }
    },
    level(index) { return { key: key('level'), crowdId: '', title: `层级${index + 1}`, activities: [this.activity(0), this.activity(1)] } },
    normalize() {
      if (!this.form.progressCopy) this.form.progressCopy = { unreached: '', reached: '', help: '' }
      if (!Array.isArray(this.form.ntbTimeRules) || !this.form.ntbTimeRules.length) this.form.ntbTimeRules = [{ key: key('time'), field: '开户时间', operator: '介于', dateRange: ['2026-07-01', '2026-09-30'] }]
      if (!Array.isArray(this.form.ntbRules) || !this.form.ntbRules.length) {
        const ntbRule = this.rule()
        ntbRule.openingMonthRequired = true
        ntbRule.labelDescription = '资产'
        ntbRule.reachedText = '已满50万'
        ntbRule.unreachedText = '未满50万'
        this.form.ntbRules = [ntbRule]
      }
      if (!Array.isArray(this.form.mgmRules) || !this.form.mgmRules.length) {
        const opening = this.rule('开户时间')
        opening.dateRange = ['2026-07-01', '2026-09-30']
        opening.reachedText = '已开户'
        opening.unreachedText = '未开户'
        opening.failureReason = '未在指定时间内开户'
        const trb = this.rule()
        trb.continuous = false
        trb.reachedText = '已升级为卓越理财客户'
        trb.unreachedText = '未升级为卓越理财客户'
        trb.failureReason = '未在活动期间升级为卓越理财客户'
        this.form.mgmRules = [opening, trb]
      }
      if (!this.form.templateRewards) this.form.templateRewards = { NTB: this.reward('权益'), MGM: this.reward('积分') }
      if (!this.form.templateRewards.NTB) this.form.templateRewards.NTB = this.reward('权益')
      if (!this.form.templateRewards.MGM) this.form.templateRewards.MGM = this.reward('积分')
      if (!this.form.mgmAchievedTag) this.form.mgmAchievedTag = '客户MSC Group'
      if (!this.form.mgmReferredProgress) this.form.mgmReferredProgress = {}
      if (!this.form.mgmReferredProgress.labelOne) this.form.mgmReferredProgress.labelOne = '开户时间'
      if (!this.form.mgmReferredProgress.labelTwo) this.form.mgmReferredProgress.labelTwo = '基础资产达标｜月内日均/家庭日月均人均余额≥50万'
      if (this.form.mgmReferredProgress.advancedReward === undefined) this.form.mgmReferredProgress.advancedReward = true
      if (!this.form.mgmReferredProgress.advancedRuleField) this.form.mgmReferredProgress.advancedRuleField = 'TRB值（含家庭账户）'
      if (!this.form.mgmReferredProgress.advancedRuleText) this.form.mgmReferredProgress.advancedRuleText = '是否完成尊尚升级'
      Object.assign(this.form.mgmReferredProgress, {
        advancedOperator: this.form.mgmReferredProgress.advancedOperator || '大于等于',
        advancedValue: this.form.mgmReferredProgress.advancedValue || 6000000
      })
      if (!Array.isArray(this.form.achievementLayers) || !this.form.achievementLayers.length) this.form.achievementLayers = [this.level(0), this.level(1)]
      this.form.achievementLayers.forEach((level, index) => {
        if (!Array.isArray(level.activities) || !level.activities.length) level.activities = [this.activity(0), this.activity(1)]
        level.activities.forEach((activity, activityIndex) => {
          if (!Array.isArray(activity.rules) || !activity.rules.length) activity.rules = [this.rule(activityIndex === 1 ? '境外消费' : 'TRB值（含家庭账户）')]
          activity.rules.forEach((rule) => {
            if (rule.field !== '境外消费') return
            if (!rule.consumptionTimeOperator) rule.consumptionTimeOperator = '小于等于'
            if (!rule.consumptionDimension) rule.consumptionDimension = '笔数'
            if (!rule.operator) rule.operator = '大于等于'
          })
          if (activityIndex === 0) {
            if (!activity.title) activity.title = '活动一：资产达标'
            if (!activity.description) activity.description = '完成以下任务获取320,000汇友荟积分'
            const firstRule = activity.rules[0]
            if (!firstRule.field) Object.assign(firstRule, this.rule('TRB值（含家庭账户）'))
            if (!firstRule.reachedText) firstRule.reachedText = '连续3个月资产达标'
          } else {
            if (!activity.title) activity.title = '活动二：信用卡加码礼赠500元微信立减金'
            if (!activity.description) activity.description = '完成以下任务赠500元微信立减金'
            const firstRule = activity.rules[0]
            if (!firstRule.field || firstRule.field !== '境外消费') Object.assign(firstRule, this.rule('境外消费'))
            if (!firstRule.reachedText) firstRule.reachedText = '需完成境外任意美元有效消费'
            if (!firstRule.consumptionTimeOperator) firstRule.consumptionTimeOperator = '小于等于'
            if (!firstRule.consumptionDimension) firstRule.consumptionDimension = '笔数'
            if (!firstRule.operator) firstRule.operator = '大于等于'
            if (!firstRule.consumptionEndDate) firstRule.consumptionEndDate = '2026-12-31'
          }
          if (!activity.reward) activity.reward = this.reward('权益')
          if (activity.reward.type === '积分') {
            activity.reward.type = '权益'
            activity.reward.planId = ''
          }
          if (!activity.reward.planId) activity.reward.planId = 'AGP002'
        })
        if (!level.crowdId) level.crowdId = 'ACD001'
        if (!level.title || level.title === `层级${index + 1}`) level.title = `卓越层级礼·层级${index + 1}（月日均≥50万）`
      })
      this.form.layerCount = this.form.layerCount || this.form.achievementLayers.length || 2
      this.syncLayerCount(this.form.layerCount)
    },
    handleTemplateChange() {
      if (this.readonly) return
      this.normalize()
    },
    addRule(list) {
      if (this.readonly) return
      if (list.length >= 5) return this.$message.warning('最多添加 5 个进度标签')
      list.push(this.rule())
    },
    addTimeRule() {
      if (this.readonly) return
      if (this.form.ntbTimeRules.length >= 1) return
      this.form.ntbTimeRules.push({ key: key('time'), field: '开户时间', operator: '介于', dateRange: [] })
    },
    addMgmRule() {
      if (this.readonly) return
      if (this.form.mgmRules.length >= 5) return this.$message.warning('最多添加 5 个进度标签')
      this.form.mgmRules.push(this.rule('开户时间'))
    },
    addActivity(level) {
      if (this.readonly) return
      if (level.activities.length >= 5) return this.$message.warning('每个层级最多添加 5 个活动')
      level.activities.push(this.activity(level.activities.length))
    },
    syncLayerCount(value) {
      const count = Number(value || 1)
      while (this.form.achievementLayers.length < count) this.form.achievementLayers.push(this.level(this.form.achievementLayers.length))
      if (this.form.achievementLayers.length > count) this.form.achievementLayers.splice(count)
      if (Number(this.activeLayer) >= count) this.activeLayer = String(count - 1)
    }
  }
}
</script>

<style scoped>
.achievement-config { display:flex; flex-direction:column; gap:20px; padding:0 0 12px; }
.template-row {
  display:flex;
  align-items:center;
  gap:72px;
  padding:20px 24px 2px;
  background:#fff;
  border:1px solid #f0f2f5;
  border-radius:4px;
  box-shadow:0 1px 3px rgba(0,0,0,.05);
}
.config-block {
  padding:0 24px 24px;
  background:#fff;
  border:1px solid #f0f2f5;
  border-radius:4px;
  box-shadow:0 1px 3px rgba(0,0,0,.05);
  overflow:hidden;
}
.config-block h3 {
  margin:0 -24px 24px;
  padding:15px 24px;
  color:#303133;
  background:#fafafa;
  border-bottom:1px solid #ebeef5;
  font-size:16px;
  font-weight:600;
}
.field-panel { margin-bottom:24px; padding:20px 20px 2px; background:#f7f8fa; border:1px solid #f0f2f5; border-radius:4px; }
.copy-panel :deep(.el-form-item__content) { max-width:640px; }
.template-row :deep(.el-form-item),
.field-panel :deep(.el-form-item),
.layer-meta-fields :deep(.el-form-item),
.layer-activity-fields :deep(.el-form-item),
.reward-section :deep(.reward-type-row .el-form-item) { display:block; margin-bottom:18px; }
.template-row :deep(.el-form-item__label),
.field-panel :deep(.el-form-item__label),
.layer-meta-fields :deep(.el-form-item__label),
.layer-activity-fields :deep(.el-form-item__label),
.reward-section :deep(.reward-type-row .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;
}
.template-row :deep(.el-form-item__content),
.field-panel :deep(.el-form-item__content),
.layer-meta-fields :deep(.el-form-item__content),
.layer-activity-fields :deep(.el-form-item__content),
.reward-section :deep(.reward-type-row .el-form-item__content) { margin-left:0 !important; display:block; line-height:normal; }
.compact-copy-input { width:480px; max-width:100%; }
.boolean-select { width:100px; }
.mgm-referred-panel :deep(.el-form-item__label) { white-space:nowrap; }
.mgm-referred-copy-input { width:480px; max-width:100%; }
.mgm-referred-rule-controls { display:flex; align-items:center; gap:8px; flex-wrap:wrap; }
.mgm-referred-field-select { width:280px; }
.mgm-referred-operator-select { width:160px; }
.mgm-referred-value-input { width:180px; }
.time-rule {
  position:relative;
  margin:16px 0 24px;
  padding:18px 18px 0;
  background:#f7f8fa;
  border:1px solid #ebeef5;
  border-radius:4px;
}
.time-rule :deep(.el-form-item) { display:block; }
.time-rule :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; }
.time-rule :deep(.el-form-item__content) { margin-left:0 !important; display:block; line-height:normal; }
.time-rule-controls { display:flex; align-items:center; gap:8px; flex-wrap:wrap; }
.time-rule-delete { position:absolute; top:16px; right:18px; }
.compact-field-select { width:280px; }
.compact-operator-select { width:160px; }
.compact-date-range { width:300px; }
.reward-section { padding-bottom:24px; }
.layer-tabs :deep(.el-tabs__header) { margin:0 -24px 24px; padding:0 24px; background:#fff; }
.layer-tabs :deep(.el-tabs__nav) { width:auto; }
.layer-tabs :deep(.el-tabs__item) { min-width:120px; height:44px; padding:0 28px; text-align:center; font-weight:500; }
.layer-activity {
  margin-top:24px;
  padding:20px;
  background:#f7f8fa;
  border:1px solid #e4e7ed;
  border-radius:8px;
}
.activity-head { margin-bottom:20px; display:flex; justify-content:space-between; align-items:center; }
.notice { margin-left:14px; color:#f56c6c; font-size:12px; font-weight:400; }
.activity-reward { margin-top:24px; padding:0 24px 24px; background:#fff; border:1px solid #e4e7ed; border-radius:4px; overflow:hidden; }
.achievement-config :deep(.el-button--primary) { box-shadow:0 1px 2px rgba(64,158,255,.2); }
@media (max-width:1200px) {
  .template-row { gap:20px; flex-wrap:wrap; }
  .compact-field-select { width:240px; }
  .compact-date-range { width:300px; }
  .achievement-config :deep(.el-col) { max-width:100%; flex:0 0 100%; }
}
</style>
