<!-- eslint-disable unicorn/prefer-ternary -->
<script setup lang="ts">
import hud from '#/utils/hud'

import { useOptionType } from '../../hooks/option-type'

defineOptions({ name: 'StemData' })

// 表单数据
const {
  formData,
  formDisabled,
  editQuestion,
  isOptionType,
  isJudgeType,
  isSingleOptionType,
} = inject('sharedData') as any
// 组件
const stemRef = ref()

// 单选题
const optionType = useOptionType()

watch(
  () => editQuestion.value,
  async () => {
    // 初始化
    if (editQuestion.value?.id) {
      formData.value.stem = editQuestion.value.stem
    } else {
      formData.value.stem = undefined
    }
  },
)

function handleCorrectChange(val: any, item: any) {
  if (!val) return
  // 控制单选
  if (isJudgeType.value || isSingleOptionType.value) {
    formData.value.options.forEach((i: any) => {
      i.correct = false
    })
    item.correct = true
  }
}

defineExpose({
  submit() {
    if (stemRef.value.isBlank()) {
      hud.error('请输入题干')
      return
    }
    return {
      stem: formData.value.stem || undefined,
    }
  },
})
</script>

<template>
  <el-card shadow="never" class="form-section">
    <template #header>
      <span class="section-title">题干</span>
    </template>

    <el-form-item label="题干" prop="stem">
      <mj-editor
        v-model="formData.stem"
        :disabled="formDisabled"
        ref="stemRef"
      />
    </el-form-item>

    <!-- 选择题选项 -->
    <el-form-item v-if="isOptionType" label="选项">
      <div class="options-container" :class="{ 'judge-option': isJudgeType }">
        <div
          v-for="(option, index) in formData.options"
          :key="index"
          class="option-item"
        >
          <el-button
            v-if="!isJudgeType && formData.options.length > 2"
            type="danger"
            size="small"
            @click="optionType.removeOption(index)"
          >
            删除
          </el-button>
          <el-checkbox
            v-model="option.correct"
            @change="handleCorrectChange($event, option)"
            :label="option.label"
          />
          <el-input
            v-if="isJudgeType"
            v-model="option.value"
            placeholder="请输入选项内容"
            :disabled="isJudgeType"
          />
          <mj-editor
            v-else
            v-model="option.value"
            :disabled="formDisabled"
            :ref="(e) => (option.ref = e)"
            content-height="100px"
          />
        </div>
        <el-button
          v-if="!isJudgeType"
          type="primary"
          size="small"
          @click="optionType.addOption"
        >
          添加选项
        </el-button>
      </div>
    </el-form-item>
  </el-card>
</template>

<style lang="scss" scoped>
.options-container:not(.judge-option) {
  display: flex;
  flex-direction: column;
  gap: 10px;

  .mj-editor {
    width: 700px;
  }
}

.options-container {
  .option-item {
    display: flex;
    gap: 20px;
  }
}
</style>
