export const MAX_QK_TARGETS = 10
export const MAX_QK_REMARK_LENGTH = 50

export function splitQkLines(value) {
  return String(value || '').split(/[\n,，]/).map(item => item.trim()).filter(Boolean)
}

export function countQkTargets(courses = [], courseGroups = []) {
  return courses.length + courseGroups.length
}

export function getMinQkInterval(totalCount) {
  return totalCount >= 5 ? 500 : 200
}

export function validateQkTaskTargets(coursesText, courseGroupsText, intervalMs) {
  const courses = splitQkLines(coursesText)
  const courseGroups = splitQkLines(courseGroupsText)
  const total = countQkTargets(courses, courseGroups)
  if (total <= 0) {
    return { ok: false, message: '至少需要填写一门课程或一个课程分组' }
  }
  if (total > MAX_QK_TARGETS) {
    return { ok: false, message: `每个任务最多选择 ${MAX_QK_TARGETS} 个课程或分组` }
  }
  const minInterval = getMinQkInterval(total)
  const safeInterval = Number(intervalMs)
  if (!Number.isFinite(safeInterval) || safeInterval < minInterval || safeInterval > 10000) {
    return {
      ok: false,
      message: `当前共 ${total} 个抢课目标，间隔需在 ${minInterval}-10000ms 之间`
    }
  }
  return {
    ok: true,
    courses,
    courseGroups,
    total,
    minInterval
  }
}

export function validateQkTaskForm(form) {
  const name = form?.name === undefined || form?.name === null ? '' : String(form.name)
  if (name.length > MAX_QK_REMARK_LENGTH) {
    return { ok: false, message: `备注不能超过 ${MAX_QK_REMARK_LENGTH} 个字符` }
  }
  if (!form?.batch_id) {
    return { ok: false, message: '请选择选课批次' }
  }
  if (!form?.jw_account_id) {
    return { ok: false, message: '请选择统一身份认证账号' }
  }
  const targetValidation = validateQkTaskTargets(
    form.coursesText,
    form.courseGroupsText,
    form.interval_ms
  )
  if (!targetValidation.ok) {
    return targetValidation
  }
  return {
    ok: true,
    name,
    batch_id: form.batch_id,
    jw_account_id: form.jw_account_id,
    courses: targetValidation.courses,
    courseGroups: targetValidation.courseGroups,
    intervalMs: Number(form.interval_ms),
    total: targetValidation.total,
    minInterval: targetValidation.minInterval
  }
}

export function getQkTargetHint(coursesText, courseGroupsText) {
  const total = countQkTargets(splitQkLines(coursesText), splitQkLines(courseGroupsText))
  if (total <= 0) {
    return `最多 ${MAX_QK_TARGETS} 个目标；少于 5 个最低 200ms，5 个及以上最低 500ms`
  }
  const minInterval = getMinQkInterval(total)
  return `已选 ${total}/${MAX_QK_TARGETS} 个目标，当前最低间隔 ${minInterval}ms`
}
