import { reactive } from 'vue'

const pad = (n) => String(n).padStart(2, '0')

function nowText() {
  const d = new Date()
  return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`
}

function clone(value) {
  return JSON.parse(JSON.stringify(value))
}

function emptyActivity() {
  return {
    id: '',
    internalTitle: '',
    name: '',
    category: '普通活动',
    status: 'draft',
    auditStatus: '未提交',
    auditAction: '',
    auditor: '',
    target: '借记卡新客',
    shareTitle: '',
    shareImage: [],
    cities: [],
    cityText: '',
    description: '',
    scrmActivityCode: '',
    scrmChannelCode: '',
    campaignId: '',
    channelId: '',
    labels: [],
    thumbnail: [],
    detailImage: [],
    displayTitle: '',
    displaySubtitle: '',
    buttonText: '立即报名',
    detailButtonText: '查看活动详情',
    signupTime: [],
    activityTime: [],
    displayTime: [],
    location: '',
    offlineEnabled: false,
    content: '',
    layerContents: [
      { key: 'layer-copy-1', title: '层级一', content: '' }
    ],
    showOnHome: true,
    showOnAll: true,
    showOnAssembly: false,
    showOnCarousel: false,
    assemblyPageIds: [],
    visibleCrowds: ['全部客户'],
    signupCrowds: ['全部客户'],
    visibleCrowdId: '',
    visibleCrowdIds: [],
    signupCrowdId: '',
    signupCrowdIds: [],
    signupFormId: '',
    showSignupCount: true,
    sharable: true,
    showOnMine: true,
    achieveCrowds: ['全部客户'],
    sortNo: 1,
    visibleStartTime: '',
    visibleEndTime: '',
    needSignup: true,
    needConfirm: true,
    confirmText: '请确认您已了解活动规则，报名成功后将进入达标进度跟踪。',
    signupSuccessTitle: '',
    signupSuccessDescription: '',
    quotaEnabled: true,
    quota: 3000,
    signedCount: 628,
    needExtraInfo: true,
    signupGuideEnabled: false,
    extraForms: [
      { name: '', placeholder: '', type: 'text', required: true, maxLength: 30 }
    ],
    extraInfoLink: '',
    progressEnabled: true,
    achievementTemplate: '',
    layerCount: 2,
    progressCopy: {
      unreached: '您已报名本活动，请继续保持账户状态',
      reached: '您已达标活动规则，可点击下方按钮查看奖励',
      help: ''
    },
    ntbTimeRules: [],
    ntbRules: [],
    mgmRules: [],
    templateRewards: {
      NTB: { type: '积分', planId: 'AGP001', amount: 3200000, validity: [], grantPeriod: '整个周期', times: 1 },
      MGM: { type: '积分', planId: 'AGP001', amount: 3200000, validity: [], grantPeriod: '整个周期', times: 1 }
    },
    achievementRules: [
      {
        key: 'default-rule-1',
        field: 'TRB值（含家庭账户）',
        operator: '大于等于',
        value: 500000,
        dateRange: [],
        openingMonthRequired: true,
        continuous: true,
        months: 3,
        allowBreak: true,
        reachedText: '已满50万',
        unreachedText: '未满50万',
        progressText: '',
        failureReason: ''
      }
    ],
    mgmAchievedTag: '',
    mgmReferredProgress: {
      labelOne: '开户时间',
      labelTwo: '基础资产达标｜月内日均/家庭日月均人均余额≥50万',
      advancedReward: true,
      advancedRuleField: 'TRB值（含家庭账户）',
      advancedOperator: '大于等于',
      advancedValue: 6000000,
      advancedRuleText: '是否完成尊尚升级'
    },
    achievementLayers: [],
    rewardType: '积分',
    rewardValidity: [],
    rewardGrantTimes: 1,
    progressTemplateId: '',
    progressRuleId: '',
    progressStyle: '多层级任务',
    levels: [
      {
        name: '基础达标',
        tasks: [
          { tag: '开户', text: '完成汇丰借记卡开户', help: 'T+1 更新开户结果' },
          { tag: '资产', text: '活动期内月末 TRB 达到 50 万元', help: '按月末批量数据计算' }
        ]
      }
    ],
    continuousRule: { enabled: false, x: 3, y: 6, z: 2 },
    reward: {
      name: '达标积分奖励',
      type: '积分',
      grantMode: '达标后自动发放',
      buttonText: '查看积分奖励',
      linkTarget: '积分明细'
    },
    rewardEnabled: true,
    grantPlanId: '',
    mutexEnabled: true,
    mutexGroup: 'NTB新客互斥组',
    mutexActivities: ['酒店新客礼遇'],
    ntb: true,
    mgm: false,
    blockText: '您已参与同组新客活动，暂无法报名本活动。',
    releaseRule: '活动结束且未达标释放',
    smsEnabled: false,
    smsTemplate: '',
    signupNoticeTemplateId: '',
    beforeStartTemplateId: '',
    rewardTemplateId: '',
    rewardNoClaimTemplateId: '',
    ownerStaffId: '',
    beforeStartSmsEnabled: false,
    rewardSmsEnabled: false,
    launchChannels: ['权益首页', '活动列表'],
    launchUrl: 'https://demo.hsbc.com.cn/activity',
    creditCardEntry: false,
    creator: '当前用户',
    createdAt: nowText(),
    updatedAt: nowText()
  }
}

const state = reactive({
  activities: [
    {
      ...emptyActivity(),
      id: 'ACT202606001',
      internalTitle: '2026借记卡新客开户达标活动',
      name: '汇丰卓越理财新户达标礼',
      category: '普通活动',
      status: 'published',
      auditStatus: '已发布',
      target: '2026年新开户并完成卓越理财资产达标的借记卡客户',
      shareTitle: '报名汇丰卓越理财新户达标礼，解锁积分奖励',
      shareImage: [{ name: '轮播图1.png', url: '/demo-assets/resource-banners/轮播图1.png' }],
      cities: ['全国'],
      cityText: '全国',
      description: '面向新户的开户与资产达标活动，报名后完成开户、资产留存和指定月度达标即可获得积分奖励。',
      scrmActivityCode: 'SCRM-ACT-NTB-202607',
      scrmChannelCode: 'HSBC-RS-HOME',
      labels: ['新客', '达标奖励', '积分'],
      thumbnail: [{ name: '国际教育.png', url: '/demo-assets/privileges/国际教育.png' }],
      detailImage: [{ name: '轮播图1.png', url: '/demo-assets/resource-banners/轮播图1.png' }],
      displayTitle: '汇丰卓越理财新户达标礼',
      displaySubtitle: '开户并完成资产达标，最高可享320万积分奖励',
      buttonText: '立即报名',
      detailButtonText: '查看达标进度',
      activityTime: ['2026-07-01', '2026-09-30'],
      signupTime: ['2026-06-25', '2026-09-15'],
      displayTime: ['2026-07-01', '2026-09-30'],
      location: '线上参与',
      content: '<p>活动期间，客户完成汇丰借记卡开户，并在活动期内保持指定资产达标，即可参与积分奖励。</p><p>活动流程：报名活动 → 完成开户 → 维持月末 TRB 达标 → 系统自动发放积分。</p><p>奖励说明：基础达标可获得积分奖励，连续达标客户可获得进阶奖励。</p><p>温馨提示：达标结果以汇丰系统记录为准，数据通常于 T+1 更新。</p>',
      layerContents: [
        { key: 'ntb-layer-copy-1', title: '基础达标', content: '<p>完成借记卡开户，且活动期内任一月末 TRB 达到人民币50万元，可获得基础积分奖励。</p>' },
        { key: 'ntb-layer-copy-2', title: '进阶达标', content: '<p>在基础达标基础上，连续3个月保持 TRB 达标，可获得进阶积分奖励。</p>' }
      ],
      signedCount: 628,
      quota: 3000,
      signupSuccessTitle: '报名成功',
      signupSuccessDescription: '您已成功报名，后续可在“我的活动”中查看达标进度。',
      extraForms: [
        { name: '航空会员号', placeholder: '请输入航空会员号（如无可填“暂无”）', type: 'text', required: true, maxLength: 30 },
        { name: '常用手机号', placeholder: '请输入用于接收活动通知的手机号', type: 'text', required: true, maxLength: 11 }
      ],
      progressCopy: {
        unreached: '您已报名，请在活动期内完成开户及资产达标。',
        reached: '恭喜您已完成达标，奖励将在规则约定时间内发放。',
        help: '开户、资产和奖励状态通常于 T+1 更新。'
      },
      ntbTimeRules: [
        { key: 'ntb-open-date', field: '开户时间', operator: '介于', value: '2026-07-01 至 2026-09-30', dateRange: ['2026-07-01', '2026-09-30'], reachedText: '已完成开户', unreachedText: '未完成开户' }
      ],
      ntbRules: [
        { key: 'ntb-trb-50', field: 'TRB值（含家庭账户）', operator: '大于等于', value: 500000, dateRange: ['2026-07-01', '2026-09-30'], openingMonthRequired: true, continuous: true, months: 3, allowBreak: true, reachedText: '已达50万', unreachedText: '未达50万', progressText: '月末 TRB 达标进度', failureReason: '资产未达到活动要求' }
      ],
      visibleCrowdId: 'ACD001',
      signupCrowdId: 'ACD001',
      signupFormId: 'FORM001',
      progressTemplateId: 'TPL001',
      progressRuleId: 'PROG001',
      grantPlanId: 'AGP001',
      auditor: '王审核',
      ownerStaffId: 'U10086',
      beforeStartSmsEnabled: true,
      rewardSmsEnabled: true,
      signupNoticeTemplateId: 'NTF001',
      rewardTemplateId: 'NTF002',
      launchUrl: 'https://demo.hsbc.com.cn/activity/ACT202606001',
      launchChannels: ['权益首页', '全部活动', '渠道二维码']
    },
    {
      ...emptyActivity(),
      id: 'ACT202606002',
      internalTitle: '酒店合作方新客礼遇活动',
      name: '汇丰高端酒店新客礼遇',
      category: '普通活动',
      status: 'pending',
      auditStatus: '待审核',
      target: '潜客/新客',
      shareTitle: '报名汇丰高端酒店新客礼遇',
      shareImage: [{ name: '轮播图2.jpg', url: '/demo-assets/resource-banners/轮播图2.jpg' }],
      cities: ['北京', '上海', '广州', '深圳'],
      cityText: '北京、上海、广州、深圳',
      description: '与高端酒店合作的新客礼遇活动，客户完成报名与开户达标后可领取酒店权益券。',
      scrmActivityCode: 'SCRM-ACT-HOTEL-202607',
      scrmChannelCode: 'HSBC-RS-PARTNER',
      labels: ['酒店礼遇', '新客', '第三方权益'],
      thumbnail: [{ name: '品质生活.png', url: '/demo-assets/privileges/品质生活.png' }],
      detailImage: [{ name: '轮播图2.jpg', url: '/demo-assets/resource-banners/轮播图2.jpg' }],
      displayTitle: '汇丰高端酒店新客礼遇',
      displaySubtitle: '完成开户及资产达标，领取高端酒店权益券',
      buttonText: '立即报名',
      detailButtonText: '查看礼遇详情',
      signupTime: ['2026-07-05', '2026-08-31'],
      activityTime: ['2026-07-05', '2026-10-31'],
      displayTime: ['2026-07-05', '2026-10-31'],
      location: '线上报名，指定城市酒店权益适用',
      content: '<p>活动期间，符合条件的新客户报名后完成开户及资产达标，可领取合作酒店礼遇。</p><p>参与方式：填写酒店会员号 → 完成汇丰开户 → 达成资产要求 → 跳转领取酒店权益券。</p><p>权益数量有限，先到先得。若报名名额已满，页面将提示无法继续报名。</p>',
      layerContents: [
        { key: 'hotel-layer-copy-1', title: '报名要求', content: '<p>客户需在报名期内提交酒店会员号，并确认授权用于活动资格核验。</p>' },
        { key: 'hotel-layer-copy-2', title: '达标奖励', content: '<p>完成开户及资产达标后，可领取合作酒店权益券，具体权益以领取页展示为准。</p>' }
      ],
      signedCount: 1200,
      quota: 1200,
      signupSuccessTitle: '报名成功，待完成达标',
      signupSuccessDescription: '请在活动期内完成开户与资产达标，达标后可查看酒店权益券。',
      visibleCrowdId: 'ACD001',
      signupCrowdId: 'ACD001',
      signupFormId: 'FORM002',
      progressTemplateId: 'TPL002',
      progressRuleId: 'PROG001',
      grantPlanId: 'AGP001',
      extraForms: [
        { name: '酒店会员号', placeholder: '请输入酒店会员号', type: 'text', required: true, maxLength: 30 },
        { name: '入住偏好城市', placeholder: '请输入偏好城市，如上海', type: 'text', required: false, maxLength: 20 }
      ],
      progressCopy: {
        unreached: '您已报名，请继续完成开户、资产和酒店会员信息核验。',
        reached: '您已完成活动达标，可前往领取酒店权益券。',
        help: '酒店会员号用于合作方权益发放，请确保填写准确。'
      },
      ntbRules: [
        { key: 'hotel-open', field: '开户时间', operator: '介于', value: '2026-07-05 至 2026-10-31', dateRange: ['2026-07-05', '2026-10-31'], reachedText: '已完成开户', unreachedText: '未完成开户' },
        { key: 'hotel-trb', field: 'TRB值（含家庭账户）', operator: '大于等于', value: 500000, dateRange: ['2026-07-05', '2026-10-31'], openingMonthRequired: true, continuous: false, months: 1, allowBreak: false, reachedText: '已达资产要求', unreachedText: '未达资产要求', progressText: '资产达标进度', failureReason: '资产未达到活动要求' }
      ],
      reward: {
        name: '酒店权益券',
        type: '第三方权益',
        grantMode: '达标后跳转领取',
        buttonText: '查看奖励',
        linkTarget: '第三方权益页'
      },
      ownerStaffId: 'U10087',
      signupNoticeTemplateId: 'NTF001',
      rewardTemplateId: 'NTF002',
      launchUrl: 'https://demo.hsbc.com.cn/activity/ACT202606002',
      launchChannels: ['全部活动', '渠道二维码']
    },
    {
      ...emptyActivity(),
      id: 'ACT202606003',
      internalTitle: 'MGM亲友推荐互斥演示活动',
      name: '汇丰亲友推荐双享礼',
      category: 'MGM活动',
      status: 'offline',
      auditStatus: '已下线',
      target: '推荐人与被推荐人',
      shareTitle: '邀请亲友加入汇丰，推荐人与被推荐人均可享奖励',
      shareImage: [{ name: '轮播图3.png', url: '/demo-assets/resource-banners/轮播图3.png' }],
      cities: ['全国'],
      cityText: '全国',
      description: '用于演示 MGM 推荐活动与其他 NTB 活动的互斥关系、T+1 标签修正和推荐人侧进度展示。',
      scrmActivityCode: 'SCRM-ACT-MGM-202605',
      scrmChannelCode: 'HSBC-RS-MGM',
      labels: ['MGM', '亲友推荐', '互斥演示'],
      thumbnail: [{ name: '礼宾服务.png', url: '/demo-assets/privileges/礼宾服务.png' }],
      detailImage: [{ name: '轮播图3.png', url: '/demo-assets/resource-banners/轮播图3.png' }],
      displayTitle: '汇丰亲友推荐双享礼',
      displaySubtitle: '推荐亲友开户达标，双方均有机会获得奖励',
      buttonText: '查看推荐进度',
      detailButtonText: '查看活动规则',
      needExtraInfo: false,
      visibleCrowdId: 'ACD002',
      signupCrowdId: 'ACD002',
      progressTemplateId: 'TPL003',
      progressRuleId: 'PROG002',
      grantPlanId: 'AGP002',
      auditor: '王审核',
      mgm: true,
      ntb: true,
      mutexGroup: 'NTB新客互斥组',
      activityTime: ['2026-05-01', '2026-06-15'],
      signupTime: ['2026-05-01', '2026-06-10'],
      displayTime: ['2026-05-01', '2026-06-15'],
      location: '线上推荐',
      content: '<p>推荐人通过活动链接邀请亲友，被推荐人在活动期内完成开户及资产达标后，推荐人与被推荐人可分别获得活动奖励。</p><p>本活动与同组 NTB 新客活动互斥。若客户已报名航司、酒店等同组新客活动，将无法继续参与本活动。</p><p>系统会在次日根据 MGM 标签、开户时间和报名记录进行修正，演示 T+1 标签延迟场景。</p>',
      layerContents: [
        { key: 'mgm-layer-copy-1', title: '推荐关系', content: '<p>推荐人与被推荐人需建立有效推荐关系，被推荐人需符合新客条件。</p>' },
        { key: 'mgm-layer-copy-2', title: '开户达标', content: '<p>被推荐人在活动期内完成开户并达到基础资产要求后，双方奖励进入发放流程。</p>' }
      ],
      progressStyle: 'MGM推荐进度',
      progressCopy: {
        unreached: '被推荐人尚未完成开户或资产达标，请继续关注进度。',
        reached: '被推荐人已完成达标，推荐奖励将按规则发放。',
        help: '推荐关系、开户和资产状态通常于 T+1 更新。'
      },
      mgmRules: [
        { key: 'mgm-relation', field: '客户MSC Group', operator: '大于等于', value: 1, reachedText: '推荐关系有效', unreachedText: '推荐关系待确认', progressText: '推荐关系核验', failureReason: '未建立有效推荐关系' },
        { key: 'mgm-trb', field: 'TRB值（含家庭账户）', operator: '大于等于', value: 500000, dateRange: ['2026-05-01', '2026-06-15'], reachedText: '被推荐人已达标', unreachedText: '被推荐人未达标', progressText: '被推荐人资产进度', failureReason: '被推荐人资产未达标' }
      ],
      mgmAchievedTag: 'MGM_REACHED_202606',
      reward: {
        name: '推荐立减金',
        type: '立减金',
        grantMode: '达标后自动发放',
        buttonText: '前往领取',
        linkTarget: '立减金列表'
      },
      blockText: '您已参与同组新客活动，暂无法继续参与亲友推荐活动。',
      ownerStaffId: 'U10088',
      signupNoticeTemplateId: 'NTF001',
      rewardTemplateId: 'NTF002',
      launchUrl: 'https://demo.hsbc.com.cn/activity/ACT202606003',
      launchChannels: ['全部活动', 'MGM推荐链接']
    },
    {
      ...emptyActivity(),
      id: 'ACT202607004',
      internalTitle: '暑期借记卡客户回馈活动',
      name: '暑期客户回馈礼',
      category: '普通活动',
      status: 'draft',
      auditStatus: '未提交',
      target: '借记卡客户',
      activityTime: ['2026-07-15', '2026-08-31'],
      signupTime: ['2026-07-12', '2026-08-25'],
      visibleCrowdIds: ['ACD001'],
      signupCrowdIds: ['ACD001'],
      creator: '李产品',
      signedCount: 0,
      quota: 1000
    },
    {
      ...emptyActivity(),
      id: 'ACT202607005',
      internalTitle: '航空新客达标活动二期',
      name: '航空新客夏日礼遇',
      category: 'NTB活动',
      achievementTemplate: 'NTB',
      status: 'pending',
      auditStatus: '待审核',
      target: '航空联名卡新客',
      activityTime: ['2026-08-01', '2026-10-31'],
      signupTime: ['2026-07-20', '2026-10-15'],
      visibleCrowdIds: ['ACD001'],
      signupCrowdIds: ['ACD001'],
      creator: '张运营',
      signedCount: 86,
      quota: 2000
    },
    {
      ...emptyActivity(),
      id: 'ACT202607006',
      internalTitle: 'MGM推荐有礼活动三期',
      name: '挚友推荐礼遇',
      category: 'MGM',
      achievementTemplate: 'MGM',
      status: 'approved',
      auditStatus: '审核通过',
      target: '推荐人与被推荐人',
      activityTime: ['2026-08-01', '2026-12-31'],
      signupTime: ['2026-07-25', '2026-12-15'],
      visibleCrowdIds: ['ACD002'],
      signupCrowdIds: ['ACD002'],
      creator: '王运营',
      auditor: '陈审核',
      signedCount: 126,
      quota: 3000
    },
    {
      ...emptyActivity(),
      id: 'ACT202607007',
      internalTitle: '卓越客户层层礼活动',
      name: '卓越层层升级礼',
      category: '层层礼',
      achievementTemplate: 'LAYER',
      status: 'published',
      auditStatus: '已发布',
      target: '卓越理财客户',
      activityTime: ['2026-07-01', '2026-12-31'],
      signupTime: ['2026-06-20', '2026-11-30'],
      showOnAssembly: true,
      creator: '周产品',
      auditor: '陈审核',
      signedCount: 1680,
      quota: 5000
    },
    {
      ...emptyActivity(),
      id: 'ACT202607008',
      internalTitle: '城市客户专属礼遇活动',
      name: '上海客户专属礼遇',
      category: '普通活动',
      status: 'offline',
      auditStatus: '已下线',
      target: '上海地区客户',
      offlineEnabled: true,
      cityText: '上海市',
      location: '线下合作网点',
      activityTime: ['2026-04-01', '2026-06-30'],
      signupTime: ['2026-03-20', '2026-06-15'],
      creator: '李产品',
      auditor: '陈审核',
      signedCount: 300,
      quota: 300
    }
  ],
  forms: [
    { id: 'FORM001', name: '航空会员号表单', fields: '航空会员号', status: '启用', usedBy: 1, updatedAt: nowText() },
    { id: 'FORM002', name: '酒店会员号表单', fields: '酒店会员号', status: '启用', usedBy: 1, updatedAt: nowText() }
  ],
  progressRules: [
    { id: 'PROG001', name: '新客开户多层级规则', levels: 2, tasks: 4, status: '启用', updatedAt: nowText() },
    { id: 'PROG002', name: 'MGM推荐进度规则', levels: 1, tasks: 3, status: '启用', updatedAt: nowText() }
  ],
  progressTemplates: [
    {
      id: 'TPL001',
      name: '多条件多次发奖模板',
      templateType: '多条件多次发奖',
      statusTexts: '未达标/已达标/已发奖/无法继续参与',
      levels: '达标50万、达标100万',
      rewardMode: '每层级独立发奖',
      continuousEnabled: true,
      continuousRule: '观察12个月，连续8个月达标',
      mgmView: '否',
      status: '启用',
      updatedAt: nowText()
    },
    {
      id: 'TPL002',
      name: '多条件单次发奖模板',
      templateType: '多条件单次发奖',
      statusTexts: '未达标/已达标/已发奖',
      levels: '开户、资产、消费',
      rewardMode: '全部条件满足后发一次奖',
      continuousEnabled: false,
      continuousRule: '-',
      mgmView: '否',
      status: '启用',
      updatedAt: nowText()
    },
    {
      id: 'TPL003',
      name: 'MGM专属推荐进度模板',
      templateType: 'MGM专属',
      statusTexts: '被推荐人未达标/已达标/互斥失败',
      levels: '推荐关系、开户、达标',
      rewardMode: '推荐人与被推荐人分别展示',
      continuousEnabled: false,
      continuousRule: '-',
      mgmView: '是',
      status: '启用',
      updatedAt: nowText()
    }
  ],
  mutexGroups: [
    {
      id: 'MTX001',
      name: 'NTB新客互斥组',
      mutexType: '互斥报名',
      businessType: 'NTB/MGM',
      scopeType: '指定活动',
      activities: '新客开户达标礼、酒店新客礼遇、MGM 亲友推荐活动',
      judgeBasis: ['报名记录', 'MGM标签', '开户时间', '达标状态'],
      realtimeBlock: true,
      tPlusOneFix: true,
      releaseRule: '活动结束且未达标释放',
      listStatusText: '不符合参与条件',
      detailStatusText: '您已参与同组新客活动，暂无法报名本活动。',
      blockText: '您已参与同组新客活动，暂无法报名本活动。',
      conflictDisplayRule: '命中后其他活动展示不符合条件',
      correctionText: '次日标签更新后，如已参加 MGM 或已开户，则当前活动变为无法继续参与。',
      remark: '用于新客活动之间的实时互斥拦截和 T+1 数据修正。',
      status: '启用',
      updatedAt: nowText()
    }
  ],
  launches: [
    { id: 'LCH001', activityName: '新客开户达标礼', channel: '权益首页', material: '首页活动卡片', status: '已投放', updatedAt: nowText() },
    { id: 'LCH002', activityName: '酒店新客礼遇', channel: '渠道二维码', material: '合作方落地页', status: '待投放', updatedAt: nowText() }
  ],
  notifications: [
    {
      id: 'NTF001',
      name: '报名成功通知',
      scene: '报名成功',
      channel: '短信',
      template: '【汇丰】您已成功报名${activityName}，请在活动期内完成达标任务。',
      variables: 'activityName',
      status: '启用',
      updatedAt: nowText()
    },
    {
      id: 'NTF002',
      name: '达标发奖通知',
      scene: '达标发奖',
      channel: '短信',
      template: '【汇丰】您参与的${activityName}已达标，奖励${rewardName}已发放。',
      variables: 'activityName,rewardName',
      status: '启用',
      updatedAt: nowText()
    }
  ],
  activityCrowds: [
    {
      id: 'ACD001',
      name: '借记卡新客可见客群',
      crowdType: '可见客群',
      source: '标签规则',
      rule: '开户时间晚于2026-01-01，且未参与同组NTB活动',
      memberCount: 35800,
      usedBy: '新客开户达标礼',
      status: '启用',
      updatedAt: nowText()
    },
    {
      id: 'ACD002',
      name: 'MGM推荐报名客群',
      crowdType: '报名客群',
      source: '指定名单',
      rule: '推荐人白名单 + 被推荐人潜客标签',
      memberCount: 12600,
      usedBy: 'MGM 亲友推荐活动',
      status: '启用',
      updatedAt: nowText()
    }
  ],
  activityGrantPlans: [
    {
      id: 'AGP001',
      name: '新客开户积分发放计划',
      rewardType: '积分',
      rewardName: '达标积分奖励',
      grantMode: '达标后自动发放',
      perCustomerLimit: 1,
      stock: 5000,
      usedBy: '新客开户达标礼',
      status: '启用',
      updatedAt: nowText()
    },
    {
      id: 'AGP002',
      name: '推荐立减金发放计划',
      rewardType: '立减金',
      rewardName: '推荐立减金',
      grantMode: '达标后跳转领取',
      perCustomerLimit: 1,
      stock: 2000,
      usedBy: 'MGM 亲友推荐活动',
      status: '启用',
      updatedAt: nowText()
    }
  ],
  notificationRecords: [
    {
      id: 'ANR001',
      activityName: '新客开户达标礼',
      scene: '报名成功',
      templateName: '报名成功通知',
      receiverCount: 628,
      successCount: 626,
      failCount: 2,
      sendTime: nowText(),
      status: '发送完成'
    },
    {
      id: 'ANR002',
      activityName: 'MGM 亲友推荐活动',
      scene: '达标发奖',
      templateName: '达标发奖通知',
      receiverCount: 86,
      successCount: 86,
      failCount: 0,
      sendTime: nowText(),
      status: '发送完成'
    }
  ],
  creditCardEntry: {
    visibleCrowdIds: [],
    icon: '',
    name: '信用卡活动专区',
    tip: '温馨提示：如需查看信用卡活动进度，请点击上方“信用卡活动专区”。',
    link: 'https://demo.hsbc.com.cn/credit-card/activity',
    enableCreditCardTab: false,
    updatedAt: nowText()
  }
})

let seq = state.activities.length + 1

function genActivityId() {
  const d = new Date()
  return `ACT${d.getFullYear()}${pad(d.getMonth() + 1)}${pad(d.getDate())}${pad(seq++)}`
}

function saveSimple(listName, payload) {
  const list = state[listName]
  const idPrefix = { forms: 'FORM', progressRules: 'PROG', progressTemplates: 'TPL', mutexGroups: 'MTX', launches: 'LCH', notifications: 'NTF', activityCrowds: 'ACD', activityGrantPlans: 'AGP', notificationRecords: 'ANR' }[listName] || 'CFG'
  if (payload.id) {
    const target = list.find((item) => item.id === payload.id)
    if (target) Object.assign(target, payload, { updatedAt: nowText() })
    return target
  }
  const record = { ...payload, id: `${idPrefix}${pad(list.length + 1)}`, status: payload.status || '启用', updatedAt: nowText() }
  list.unshift(record)
  return record
}

export default {
  emptyActivity,
  get activities() {
    return state.activities
  },
  get forms() {
    return state.forms
  },
  get progressRules() {
    return state.progressRules
  },
  get progressTemplates() {
    return state.progressTemplates
  },
  get mutexGroups() {
    return state.mutexGroups
  },
  get launches() {
    return state.launches
  },
  get notifications() {
    return state.notifications
  },
  get activityCrowds() {
    return state.activityCrowds
  },
  get activityGrantPlans() {
    return state.activityGrantPlans
  },
  get notificationRecords() {
    return state.notificationRecords
  },
  get creditCardEntry() {
    return state.creditCardEntry
  },
  queryActivities(filters = {}) {
    return state.activities.filter((item) => {
      if (filters.name && !item.name.includes(filters.name)) return false
      if (filters.id && !item.id.includes(filters.id)) return false
      if (filters.status && item.status !== filters.status) return false
      if (filters.category && item.category !== filters.category) return false
      return true
    })
  },
  getActivity(id) {
    return state.activities.find((item) => item.id === id)
  },
  saveActivity(payload) {
    if (payload.id) {
      const target = state.activities.find((item) => item.id === payload.id)
      if (!target) return null
      Object.assign(target, clone(payload), { updatedAt: nowText() })
      return target
    }
    const record = { ...clone(payload), id: genActivityId(), status: payload.status || 'draft', auditStatus: payload.auditStatus || '未提交', creator: '当前用户', createdAt: nowText(), updatedAt: nowText() }
    state.activities.unshift(record)
    return record
  },
  copyActivity(id) {
    const source = this.getActivity(id)
    if (!source) return null
    const record = { ...clone(source), id: genActivityId(), name: `${source.name}-副本`, status: 'draft', auditStatus: '未提交', createdAt: nowText(), updatedAt: nowText() }
    state.activities.unshift(record)
    return record
  },
  publishActivity(id) {
    const target = this.getActivity(id)
    if (!target) return null
    target.status = 'published'
    target.auditStatus = '已发布'
    target.updatedAt = nowText()
    return target
  },
  offlineActivity(id) {
    const target = this.getActivity(id)
    if (!target) return null
    target.status = 'offline'
    target.auditStatus = '已下线'
    target.updatedAt = nowText()
    return target
  },
  removeActivity(id) {
    const idx = state.activities.findIndex((item) => item.id === id)
    if (idx >= 0) state.activities.splice(idx, 1)
  },
  saveSimple,
  updateCreditCardEntry(payload) {
    Object.assign(state.creditCardEntry, payload, { updatedAt: nowText() })
  }
}
