<template>
  <rate
    v-model:element="question"
    v-model:answer-value="value"
    :active="false"
    :is-preview="true"
    :index="answerIndex"
    :errorMessage="question.error"
  />
</template>

<script setup lang="ts">
import Rate from '@/views/Design/components/Questions/Rate.vue';
import { computed, nextTick, ref, watch } from 'vue';
import type { IQuestion } from '@/types/question';
import { validateAnswerNum } from '@/views/Survey/views/Preview/components/questions/validate/validateAnswer';
import type { IRateConfig } from '@/types/questions/rateConfig';

const value = ref<number[]>([]);
// // 预览新增 emit ['changeAnswer', 'previous', 'next']
const emit = defineEmits(['changeAnswer', 'previous', 'next', 'update:element']);
const question = defineModel<IQuestion<IRateConfig>>('question', {
  default: { config: { is_required: false } }
});

// 配置内容
const config = computed(() => question.value?.config);
// 选项
const options = computed(() => question.value?.list[0]?.options ?? []);

/**
 * answer 的答案类型
 * {
 *     "1": 10
 * }
 */
const answer = defineModel<NPSAnswerType>('answer', { default: undefined });
const answerIndex = computed(() => question.value?.title ?? 0);

parseAnswer();

// 解析答案
function parseAnswer() {
  if (!answer.value) return;
  // 如果有答案，清空数值
  value.value.length = 0;
  // 然后开始赋值
  for (const answerKey in answer.value) {
    if (answer.value[answerKey] < 0) continue;
    nextTick(() => (value.value[answerKey - 1] = answer.value[answerKey]));
  }
}

/**
 * 生成NPS答案
 */
function genAnswer(value: number[]): NPSAnswerType {
  const res: any = {};
  value.forEach((value, index) => {
    if (value < 0) return;

    res[index + 1] = value;
  });
  return res;
}

watch(
  () => value,
  (answerValue) => {
    console.log('value', answerValue);
    const errorMessage = validateAnswerNum(answerValue.value, config.value!, options.value);
    console.log('errorMessage', errorMessage);
    question.value.error = errorMessage;
    if (errorMessage.length > 0) {
      // 清空答案
      question.value.answer = undefined;
      return;
    }
    answer.value = genAnswer(answerValue.value);
    // 提交答案
    emit('changeAnswer', answer.value);
  },
  { deep: true }
);
</script>

<style scoped></style>
