<template>
  <div class="question-options-editor">
    <el-card>
      <!-- 心理评估题的选项渲染 -->
      <div v-if="questionForm === 4">
        <div class="option-header">
          <span style="flex: 1;">选项内容</span>
          <span style="width: 120px; text-align: center;">分值</span>
        </div>
        <div 
          v-for="(option, index) in options" 
          :key="index" 
          class="option-item"
        >
          <el-input 
            v-model="option.option_text" 
            placeholder="请输入选项内容" 
            style="flex: 1; margin-right: 10px;"
          />
          <el-input-number
            v-model="option.score"
            :min="0"
            :max="10"
            style="width: 120px;"
            placeholder="分值"
          />
        </div>
      </div>

      <!-- 单选题和多选题的选项渲染 -->
      <div v-else>
        <div class="option-header">
          <span style="flex: 1;">选项内容</span>
          <span style="width: 80px; text-align: center;">是否正确</span>
        </div>
        <div 
          v-for="(option, index) in options" 
          :key="index" 
          class="option-item"
        >
          <el-input 
            v-model="option.option_text" 
            placeholder="请输入选项内容" 
            style="flex: 1; margin-right: 10px;"
          />
          <el-tooltip 
            content="设置为正确答案" 
            placement="top" 
            effect="light"
          >
            <div style="width: 80px; text-align: center;">
              <el-radio 
                v-if="questionForm === 1 || questionForm === 3"

                :model-value="option.is_correct"
                :label="true"
                @change="handleSingleChoice(index)"
              />
              <el-checkbox 
                v-else
                v-model="option.is_correct"
              />
            </div>
          </el-tooltip>
        </div>
      </div>

      <!-- 操作按钮 -->
      <div class="option-actions">
        <el-button 
          type="primary" 
          @click="addOption"
        >
          添加选项
        </el-button>
        
        <el-button 
          v-if="options.length > 2"
          type="danger" 
          @click="removeLastOption"
        >
          删除最后一项
        </el-button>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, watch, nextTick } from 'vue';

interface Option {
  option_text: string;
  is_correct?: boolean;
  score?: number;
  sort: number;
}

interface Props {
  modelValue: Option[];
  questionForm: number;
}

interface Emits {
  (e: 'update:modelValue', value: Option[]): void;
}

const props = defineProps<Props>();
const emit = defineEmits<Emits>();

const options = ref<Option[]>([...props.modelValue]);

// 使用更精确的对比函数
const isArrayEqual = (arr1: Option[], arr2: Option[]): boolean => {
  if (arr1.length !== arr2.length) return false;
  
  return arr1.every((item, index) => {
    const item2 = arr2[index];
    return item.option_text === item2.option_text &&
           item.is_correct === item2.is_correct &&
           item.score === item2.score &&
           item.sort === item2.sort;
  });
};

// 防止无限循环的标志
let isUpdatingFromParent = false;
let isUpdatingFromChild = false;

// 监听本地数据变化
watch(() => options.value, (newVal) => {
  if (!isUpdatingFromParent && !isUpdatingFromChild) {
    isUpdatingFromChild = true;
    nextTick(() => {
      emit('update:modelValue', [...newVal]);
      isUpdatingFromChild = false;
    });
  }
}, { deep: true });

// 监听父组件数据变化
watch(() => props.modelValue, (newVal) => {
  if (!isUpdatingFromChild && !isArrayEqual(newVal, options.value)) {
    isUpdatingFromParent = true;
    nextTick(() => {
      options.value = [...newVal];
      isUpdatingFromParent = false;
    });
  }
}, { deep: true });

// 处理单选题的勾选逻辑
const handleSingleChoice = (selectedIndex: number) => {
  if (props.questionForm === 1|| props.questionForm === 3) {
    // 创建新数组，避免直接修改响应式数据
    const newOptions = options.value.map((item, index) => ({
      ...item,
      is_correct: index === selectedIndex
    }));
    
    // 一次性替换整个数组
    options.value = newOptions;
  }
};

// 添加选项
const addOption = () => {
  const sort = options.value.length > 0 ? 
    Math.max(...options.value.map(o => o.sort || 0)) + 1 : 1;
  
  const newOption = props.questionForm === 4 ? {
    option_text: '', 
    score: 0, 
    sort 
  } : {
    option_text: '', 
    is_correct: false, 
    sort 
  };
  
  // 创建新数组，避免直接push
  options.value = [...options.value, newOption];
};

// 删除最后一个选项
const removeLastOption = () => {
  if (options.value.length > 2) {
    // 创建新数组，避免直接pop
    options.value = options.value.slice(0, -1);
  }
};
</script>

<style scoped>
.question-options-editor {
  width: 100%;
}

.option-header {
  display: flex;
  margin-bottom: 10px;
  font-weight: bold;
  background-color: #f5f7fa;
  padding: 8px;
  border-radius: 4px;
}

.option-item {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  padding: 8px;
}

.option-actions {
  display: flex;
  justify-content: space-between;
  margin-top: 10px;
}
</style>

