// 短信模板数据的会话内存储（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: 'SMS_TPL_001',
      name: '通用权益支付成功模板',
      content: '【银行】您购买的${productName}已支付成功，卡号：${exchangeNum}，卡密：${exchangePwd}，有效期至${expireDate}，详情：${qrCodeDownPaths}',
      creator: '张运营',
      createdAt: '2026-04-01 09:15:30',
      updater: '张运营',
      updatedAt: '2026-04-10 14:20:10'
    },
    {
      id: 'SMS_TPL_002',
      name: '券码类短信模板',
      content: '【银行】尊敬的客户，您的${productName}购买成功，券码为${exchangeNum}，请于${expireDate}前使用。',
      creator: '李产品',
      createdAt: '2026-04-02 10:32:18',
      updater: '李产品',
      updatedAt: '2026-04-18 09:02:45'
    },
    {
      id: 'SMS_TPL_003',
      name: '实物类短信模板',
      content: '【银行】您购买的${productName}已受理，我们将尽快安排发货，感谢您的支持。',
      creator: '王运营',
      createdAt: '2026-04-05 11:08:00',
      updater: '王运营',
      updatedAt: '2026-04-05 11:08:00'
    }
  ]
})

let seq = state.list.length

const genId = () => {
  seq += 1
  return `SMS_TPL_${String(seq).padStart(3, '0')}`
}

export default {
  state,
  query({ name = '', id = '' } = {}) {
    return state.list.filter(item => {
      if (name && !item.name.includes(name)) return false
      if (id && !item.id.includes(id)) return false
      return true
    })
  },
  getById(id) {
    return state.list.find(item => item.id === id)
  },
  create({ name, content }) {
    const item = {
      id: genId(),
      name,
      content,
      creator: '当前用户',
      createdAt: now(),
      updater: '当前用户',
      updatedAt: now()
    }
    state.list.unshift(item)
    return item
  },
  update(id, { name, content }) {
    const target = state.list.find(item => item.id === id)
    if (!target) return null
    target.name = name
    target.content = content
    target.updater = '当前用户'
    target.updatedAt = now()
    return target
  },
  remove(id) {
    const idx = state.list.findIndex(item => item.id === id)
    if (idx >= 0) state.list.splice(idx, 1)
  }
}
