import hud from '#/utils/hud'

// 判断题
const judge_options = [
  { label: 'A', value: '正确', correct: true },
  { label: 'B', value: '错误', correct: false },
]

const other_options = [
  { label: 'A', value: '', correct: false },
  { label: 'B', value: '', correct: false },
  { label: 'C', value: '', correct: false },
  { label: 'D', value: '', correct: false },
]

export function useOptionType() {
  const { formData, editQuestion, isJudgeType } = inject('sharedData') as any

  // 选择题选项管理
  const addOption = () => {
    const nextLabel = String.fromCodePoint(65 + formData.value.options.length)
    formData.value.options.push({ label: nextLabel, value: '' })
  }

  const removeOption = (index: number) => {
    if (formData.value.options.length > 2) {
      formData.value.options.splice(index, 1)
      // 重新分配标签
      formData.value.options.forEach((option: any, idx: any) => {
        option.label = String.fromCodePoint(65 + idx)
      })
    }
  }

  const onTypeChange = () => {
    let defaultOptions = other_options
    if (isJudgeType.value) {
      defaultOptions = judge_options
    }
    if (!editQuestion.value.id) {
      formData.value.options = defaultOptions
      formData.value.answer = ''
      return
    }
    if (isJudgeType.value) {
      formData.value.options = judge_options
      // 答案
      formData.value.answer = ''
      return
    }
    // 选项
    const options = editQuestion.value.options || defaultOptions
    // 先不考虑多选题
    if (editQuestion.value.answer?.length) {
      for (const option of options) {
        option.correct = option.label === editQuestion.value.answer[0]
      }
    }

    formData.value.options = options
  }

  const submit = () => {
    if (!formData.value.options?.length) {
      hud.error('请添加选项')
      return
    }
    for (const option of formData.value.options) {
      if (!option.value) {
        hud.error('请填写选项内容')
        return
      }
    }

    // 看是否有勾选
    let answer = undefined as any
    for (const item of formData.value.options) {
      if (item.correct) {
        answer = item.label
        break
      }
    }
    if (!answer) {
      hud.error('请设置答案')
      return
    }
    // 只留下option的label和value
    const options = formData.value.options.map((item: any) => ({
      label: item.label,
      value: item.value,
    }))
    return {
      options: JSON.stringify(options),
      answer: JSON.stringify([answer]),
    }
  }

  return {
    addOption,
    removeOption,
    submit,
    onTypeChange,
  }
}
