// 客群任务 store（demo 用，刷新后重置为初始种子数据）
import { reactive } from 'vue'

const now = () => {
  const d = new Date()
  const pad = (n) => String(n).padStart(2, '0')
  return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`
}

// 14 位编号：6 位序列 + 8 位日期
function genTaskId(seq) {
  const d = new Date()
  const pad = (n) => String(n).padStart(2, '0')
  const stamp = `${d.getFullYear()}${pad(d.getMonth() + 1)}${pad(d.getDate())}`
  return `${String(seq).padStart(6, '0')}${stamp}`
}

// sample 数量规则
function sampleSize(count) {
  if (count < 30000) return 5
  if (count < 50000) return 8
  if (count < 150000) return 12
  return 15
}

function generateSample(count) {
  const size = Math.min(sampleSize(count), Math.max(count, 0))
  const arr = []
  const used = new Set()
  while (arr.length < size) {
    const cid = String(Math.floor(Math.random() * 99999) + 1).padStart(5, '0')
    if (!used.has(cid)) {
      used.add(cid)
      arr.push({ index: arr.length + 1, customerId: cid })
    }
  }
  return arr
}

function randomCount() {
  // 随机分布在 1000 - 200000
  return Math.floor(Math.random() * 199000) + 1000
}

const state = reactive({
  list: [
    {
      id: '00000120251224',
      name: '层层礼圈选客群1',
      description: '圈选层层礼报名客群',
      startDate: '2025-12-25',
      endDate: '2025-12-31',
      ruleGroupLogic: 'AND',
      ruleGroups: [
        { id: 'RG20260401001', name: '层层礼-借记卡新客圈选', description: '2025/9/30 前开户 + MSC 属于卓越/运筹', logic: 'AND', ruleCount: 4 },
        { id: 'RG20260410002', name: '信用卡-高净值持卡客户', description: 'MSC 属于卓越/尊尚 且 月末余额 ≥ 100 万', logic: 'AND', ruleCount: 2 }
      ],
      status: 'verifying',
      creator: '运维A',
      reviewer: '审核B',
      createdAt: '2025-12-24 12:52:30',
      updatedAt: '2025-12-31 15:31:12',
      run: {
        count: 20000,
        sample: generateSample(20000),
        fulllist: null
      }
    }
  ],
  seq: 2
})

function findById(id) {
  return state.list.find((t) => t.id === id)
}

// 模拟"行内"异步返回
function asyncRun(task, kind, delay = 2000) {
  if (kind === 'countSample') {
    task.run['count'] = 'running'
    task.run['sample'] = 'running'
    setTimeout(() => {
      const c = randomCount()
      task.run['count'] = c
      task.run['sample'] = generateSample(c)
      task.status = 'verifying'
      task.updatedAt = now()
    }, delay)
  } else if (kind === 'fulllist') {
    task.run['fulllist'] = 'running'
    setTimeout(() => {
      task.run['fulllist'] = 'completed'
      task.status = 'online'
      task.updatedAt = now()
    }, delay + 1000)
  }
}

export default {
  get list() {
    return state.list
  },
  query({ id = '', name = '' } = {}) {
    return state.list.filter((t) => {
      if (id && !t.id.includes(id)) return false
      if (name && !t.name.includes(name)) return false
      return true
    })
  },
  getById(id) {
    return findById(id)
  },
  create(payload) {
    const record = {
      id: genTaskId(state.seq++),
      name: payload.name,
      description: payload.description || '',
      startDate: payload.startDate,
      endDate: payload.endDate,
      ruleGroupLogic: payload.ruleGroupLogic || 'AND',
      ruleGroups: payload.ruleGroups || [],
      status: 'draft',
      creator: '当前用户',
      reviewer: '',
      createdAt: now(),
      updatedAt: now(),
      run: { count: null, sample: null, fulllist: null }
    }
    state.list.unshift(record)
    return record
  },
  copyFrom(sourceId) {
    const src = findById(sourceId)
    if (!src) return null
    return this.create({
      name: src.name + '-副本',
      description: src.description,
      startDate: src.startDate,
      endDate: src.endDate,
      ruleGroupLogic: src.ruleGroupLogic,
      ruleGroups: src.ruleGroups.map((r) => ({ ...r }))
    })
  },
  update(id, payload, opts = {}) {
    const target = findById(id)
    if (!target) return null
    target.name = payload.name
    target.description = payload.description || ''
    target.startDate = payload.startDate
    target.endDate = payload.endDate
    target.ruleGroupLogic = payload.ruleGroupLogic || 'AND'
    target.ruleGroups = payload.ruleGroups || []
    target.updatedAt = now()
    // 编辑校验状态的任务 → 回退到新建并重置运行信息
    if (opts.resetRun) {
      target.status = 'draft'
      target.run = { count: null, sample: null, fulllist: null }
    }
    return target
  },
  stop(id) {
    const target = findById(id)
    if (!target) return
    target.status = 'stopped'
    target.updatedAt = now()
  },
  run(id) {
    const target = findById(id)
    if (!target || target.status !== 'draft') return
    asyncRun(target, 'countSample')
  },
  rerunCountSample(id) {
    const target = findById(id)
    if (!target) return
    asyncRun(target, 'countSample')
  },
  publish(id) {
    const target = findById(id)
    if (!target || target.status !== 'verifying') return
    target.reviewer = target.reviewer || '审核B'
    asyncRun(target, 'fulllist')
  },
  // 给视图用：当前任务允许的操作列表
  allowedActions(task) {
    if (!task) return []
    if (task.status === 'draft') return ['edit', 'stop', 'detail', 'run']
    if (task.status === 'verifying') return ['edit', 'stop', 'detail', 'publish']
    if (task.status === 'online') return ['stop', 'detail']
    return ['detail']
  }
}
