<template>
  <choice
    v-model:checkboxAnswer="choiceValue"
    :element="question"
    :index="answerIndex"
    :is-preview="true"
    :errorMessage="question.error"
  />
</template>
<script setup lang="ts">
import { watch, ref, computed } from 'vue';
import Choice from '@/views/Design/components/Questions/Choice.vue';
import { validateMultiSelectQuestion } from '@/views/Survey/views/Preview/components/questions/validate/validateSelect';
import type { IQuestion } from '@/types/question';

type answerType = {
  [key: string]: string;
};

/**
 * answer 格式
 * {
 *   1:"1"
 *   2:"1"
 * }
 */
// 预览新增 v-model
const answer = defineModel<answerType>('answer', { default: undefined });
// const stem = defineModel<string>('stem', { default: '' });
const question = defineModel<IQuestion<IChoiceConfig>>('question', {
  default: { config: { is_required: false } }
});
const answerIndex = computed<string>(() => question.value.title);
// const list = defineModel<questionsList[]>('list', { default: [[]] });

console.log(`question`, question.value);

const choiceValue = ref<string[]>(parseAnswer(answer.value));

// // 预览新增 emit ['changeAnswer', 'previous', 'next']
const emit = defineEmits(['update:element', 'changeAnswer', 'previous', 'next', 'update:element']);

/**
 * 解析答案
 */
function parseAnswer(answer: answerType) {
  if (!answer) return [];
  return Object.keys(answer);
}

// 监听选择的值，如果选择的值变化，重新生成答案
// 同时判断选择的答案是否有错误
watch(
  () => choiceValue.value,
  (value) => {
    question.value.error = validateMultiSelectQuestion(
      value,
      question.value.list[0].options,
      question.value.config!
    );
    // 有错误就不更新
    if (question.value.error) {
      // 清空答案的内容
      question.value.answer = void 0;
      console.log(question.value);
      return;
    }
    const res: answerType = {};
    choiceValue.value.forEach((key) => {
      res[key] = '1';
    });
    answer.value = res;
    // console.log(res);
    emit('changeAnswer', res);
  }
);
</script>
