// 标签数据的会话内存储（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())}`
}

const state = reactive({
  list: [
    {
      id: 'TAG20260401001',
      name: '近 6 个月尊尚客户',
      description: '近 6 个月符合尊尚资格的客户，用于尊尚专享权益投放',
      status: 'enabled',
      creator: '张运营',
      createdAt: '2026-04-01 09:15:30',
      updater: '张运营',
      updatedAt: '2026-04-10 14:20:10',
      referenceCount: 3,
      groups: [
        {
          id: 'g1',
          logic: 'AND',
          rules: [
            {
              id: 'r1',
              paramKey: 'isQualifiedLast6Months',
              timeWindow: { mode: 'current', month: '', n: 3, m: 1, aggregator: 'any' },
              operator: 'eq',
              value: true,
              value2: '',
              unit: 'day'
            }
          ]
        }
      ]
    },
    {
      id: 'TAG20260402002',
      name: '高净值活跃客户',
      description: 'TRB ≥ 100万 且 近 3 个月登录过手机银行',
      status: 'enabled',
      creator: '李产品',
      createdAt: '2026-04-02 10:32:18',
      updater: '王审核',
      updatedAt: '2026-04-18 09:02:45',
      referenceCount: 1,
      groups: [
        {
          id: 'g1',
          logic: 'AND',
          rules: [
            {
              id: 'r1',
              paramKey: 'avgTrbIncludingHousehold',
              timeWindow: { mode: 'current', month: '', n: 3, m: 1, aggregator: 'any' },
              operator: 'gte',
              value: 1000000,
              value2: '',
              unit: 'day'
            },
            {
              id: 'r2',
              paramKey: 'isPrevTwoMonthsActive',
              timeWindow: { mode: 'current', month: '', n: 3, m: 1, aggregator: 'any' },
              operator: 'eq',
              value: true,
              value2: '',
              unit: 'day'
            }
          ]
        }
      ]
    },
    {
      id: 'TAG20260410003',
      name: '跨境 1+1 CN-HK 新客',
      description: '2026 年新晋 1+1 CN-HK qualifier',
      status: 'disabled',
      creator: '赵市场',
      createdAt: '2026-04-10 16:55:02',
      updater: '赵市场',
      updatedAt: '2026-04-20 11:48:33',
      referenceCount: 0,
      groups: [
        {
          id: 'g1',
          logic: 'AND',
          rules: [
            {
              id: 'r1',
              paramKey: 'isHKQualifier',
              timeWindow: { mode: 'current', month: '', n: 3, m: 1, aggregator: 'any' },
              operator: 'eq',
              value: true,
              value2: '',
              unit: 'day'
            },
            {
              id: 'r2',
              paramKey: 'cnHkQualifierDate',
              timeWindow: { mode: 'current', month: '', n: 3, m: 1, aggregator: 'any' },
              operator: 'gte',
              value: '2026-01',
              value2: '',
              unit: 'day'
            }
          ]
        }
      ]
    }
  ]
})

let seq = state.list.length + 1

function genId() {
  const d = new Date()
  const pad = (n) => String(n).padStart(2, '0')
  const stamp = `${d.getFullYear()}${pad(d.getMonth() + 1)}${pad(d.getDate())}`
  return `TAG${stamp}${String(seq++).padStart(3, '0')}`
}

export default {
  get list() {
    return state.list
  },
  query({ name = '', id = '', status = '', creator = '', createdRange = [] } = {}) {
    return state.list.filter((t) => {
      if (name && !t.name.includes(name)) return false
      if (id && t.id !== id) return false
      if (status && t.status !== status) return false
      if (creator && !t.creator.includes(creator)) return false
      if (createdRange && createdRange.length === 2 && createdRange[0] && createdRange[1]) {
        const c = t.createdAt.slice(0, 10)
        if (c < createdRange[0] || c > createdRange[1]) return false
      }
      return true
    })
  },
  getById(id) {
    return state.list.find((t) => t.id === id)
  },
  create(payload) {
    const record = {
      id: genId(),
      name: payload.name,
      description: payload.description || '',
      status: payload.status ? 'enabled' : 'disabled',
      creator: '当前用户',
      createdAt: now(),
      updater: '当前用户',
      updatedAt: now(),
      referenceCount: 0,
      groups: payload.groups || []
    }
    state.list.unshift(record)
    return record
  },
  update(id, payload) {
    const target = state.list.find((t) => t.id === id)
    if (!target) return null
    target.name = payload.name
    target.description = payload.description || ''
    target.status = payload.status ? 'enabled' : 'disabled'
    target.groups = payload.groups || []
    target.updater = '当前用户'
    target.updatedAt = now()
    return target
  },
  remove(id) {
    const idx = state.list.findIndex((t) => t.id === id)
    if (idx >= 0) state.list.splice(idx, 1)
  },
  toggleStatus(id) {
    const target = state.list.find((t) => t.id === id)
    if (!target) return
    target.status = target.status === 'enabled' ? 'disabled' : 'enabled'
    target.updater = '当前用户'
    target.updatedAt = now()
  }
}
