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

type answerType = {
  options?: any[];
  value: { [key: number]: number };
};

// // 预览新增 v-model
const answer = defineModel<answerType>('answer', { default: undefined });
const answerIndex = computed(() => question.value.title);
// const stem = defineModel<string>('stem', { default: '' });
const question = defineModel<IQuestion>('question', {
  default: { config: { is_required: false } }
});

// 选项列表
const list = useGetList(question);
// console.log(`list`, list.value);
const choiceValue = ref<string>('0');

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

if (answer.value) {
  parseAnswer();
}

/**
 * 如果再次加载组件， 组件内已经有 answer. 那么开始解析答案
 */
function parseAnswer() {
  for (const key in answer.value.value) {
    choiceValue.value = key;
  }
}

/**
 * 自动生成答案，伴随 answer 的变化
 */
watch(
  () => choiceValue.value,
  () => {
    // console.log(`choiceValue`, choiceValue.value);
    const res = {
      // options: list.value.flatMap((group) => group.options || []),
      value: {
        [choiceValue.value]: 1
      }
      // value: choiceValue.value
    };
    answer.value = res;
    // console.log(`answer`, res);
    emit('changeAnswer', res);
  }
);
</script>
