/**
 * 业务员录入本地草稿（uni.setStorageSync）
 */

export const MAX_DRAFTS = 20

const STORAGE_VERSION = 'v1'

function readJson(key) {
  try {
    const raw = uni.getStorageSync(key)
    if (!raw) return []
    return typeof raw === 'string' ? JSON.parse(raw) : raw
  } catch (e) {
    return []
  }
}

function writeJson(key, data) {
  try {
    uni.setStorageSync(key, JSON.stringify(data))
    return true
  } catch (e) {
    return false
  }
}

function storageUserSuffix() {
  const user = uni.getStorageSync('salesperson_user') || {}
  if (user.id != null && user.id !== '') return String(user.id)
  const token = uni.getStorageSync('salesperson_token') || ''
  if (!token) return 'anon'
  let hash = 0
  for (let i = 0; i < token.length; i += 1) {
    hash = (hash * 31 + token.charCodeAt(i)) | 0
  }
  return 't' + Math.abs(hash)
}

function storageKey(type) {
  return `salesperson.inputDraft.${STORAGE_VERSION}.${storageUserSuffix()}.${type}`
}

function newDraftId() {
  return `draft_${Date.now()}_${Math.floor(Math.random() * 10000)}`
}

export function listDrafts(type) {
  const list = readJson(storageKey(type))
  if (!Array.isArray(list)) return []
  return list.sort((a, b) => (b.updatedAt || 0) - (a.updatedAt || 0))
}

export function getDraft(type, draftId) {
  if (!draftId) return null
  return listDrafts(type).find((d) => d.id === draftId) || null
}

export function removeDraft(type, draftId) {
  const key = storageKey(type)
  const list = listDrafts(type).filter((d) => d.id !== draftId)
  writeJson(key, list)
}

export function saveDraft(type, { name, form, ui, draftId }) {
  const trimmed = String(name || '').trim()
  if (!trimmed) {
    throw new Error('请输入草稿名称')
  }
  const key = storageKey(type)
  let list = listDrafts(type)
  const now = Math.floor(Date.now() / 1000)
  const payload = {
    id: draftId || newDraftId(),
    name: trimmed,
    updatedAt: now,
    form: JSON.parse(JSON.stringify(form || {})),
    ui: JSON.parse(JSON.stringify(ui || {})),
  }
  const idx = list.findIndex((d) => d.id === payload.id)
  if (idx >= 0) {
    list[idx] = payload
  } else {
    if (list.length >= MAX_DRAFTS) {
      throw new Error(`最多保存 ${MAX_DRAFTS} 个草稿，请先删除旧草稿`)
    }
    list.push(payload)
  }
  const ok = writeJson(key, list)
  if (!ok) {
    throw new Error('保存失败，存储空间可能不足，请删除部分草稿或图片后再试')
  }
  return payload
}

export function formatDraftTime(ts) {
  if (!ts) return ''
  const d = new Date(Number(ts) * 1000)
  const pad = (n) => String(n).padStart(2, '0')
  return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}`
}

export function draftSummary(type, form) {
  if (!form) return ''
  if (type === 'store') {
    return form.name || form.contact || form.mobile || '未填写名称'
  }
  return form.name || form.mobile || '未填写姓名'
}
