// 客群名单 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())}`
}

// A 开头 + 6 位序列 + 8 位日期 = 15 位
function genId(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 `A${String(seq).padStart(6, '0')}${stamp}`
}

const state = reactive({
  list: [
    {
      id: 'A0000120251224',
      name: '名单1',
      description: '层层礼活动黑名单',
      status: 'draft',
      members: ['00001', '00002', '00003', '00004'],
      creator: '运维A',
      reviewer: '审核B',
      createdAt: '2025-12-24 12:52:30',
      updatedAt: '2025-12-31 15:31:12'
    }
  ],
  seq: 2,
  // 调整流水（demo 仅用于上传文件结果展示）
  adjustments: []
})

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

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 initialMembers = Array.isArray(payload.members)
      ? Array.from(new Set(payload.members.filter((m) => m)))
      : []
    const record = {
      id: genId(state.seq++),
      name: payload.name,
      description: payload.description || '',
      status: 'draft',
      members: initialMembers,
      creator: '当前用户',
      reviewer: '审核B',
      createdAt: now(),
      updatedAt: now()
    }
    state.list.unshift(record)
    return record
  },
  update(id, payload) {
    const target = findById(id)
    if (!target) return null
    target.name = payload.name
    target.description = payload.description || ''
    target.updatedAt = now()
    return target
  },
  activate(id) {
    const target = findById(id)
    if (!target) return
    target.status = 'active'
    target.updatedAt = now()
  },
  stop(id) {
    const target = findById(id)
    if (!target) return
    target.status = 'stopped'
    target.updatedAt = now()
  },
  // 单条人员调整
  adjustOne({ listId, customerId, direction }) {
    const target = findById(listId)
    if (!target) return { ok: false, reason: '名单不存在' }
    if (target.status === 'stopped') return { ok: false, reason: '已停止名单不可调整' }
    if (direction === 'A') {
      if (target.members.includes(customerId)) {
        return { ok: false, reason: '客户号已存在名单中' }
      }
      target.members.push(customerId)
      target.updatedAt = now()
      return { ok: true, action: 'add' }
    }
    if (direction === 'D') {
      const idx = target.members.indexOf(customerId)
      if (idx < 0) return { ok: false, reason: '客户号不在名单中' }
      target.members.splice(idx, 1)
      target.updatedAt = now()
      return { ok: true, action: 'remove' }
    }
    return { ok: false, reason: '调整方向非法' }
  },
  // 批量调整（来自上传文件）
  applyBatch(items) {
    const result = { success: 0, failed: 0, failures: [] }
    items.forEach((item, idx) => {
      const r = this.adjustOne(item)
      if (r.ok) {
        result.success++
      } else {
        result.failed++
        result.failures.push({ line: idx + 1, item, reason: r.reason })
      }
    })
    return result
  }
}
