<template>
  <MatrixQuestion
    v-model:rowRecord="rowRecord"
    :rows="rows.options"
    :cols="cols.options"
    :index="answerIndex"
    :element="question"
    :is-preview="true"
    :active="false"
    :errorMessage="question.error"
  />
</template>

<script setup lang="ts">
import { computed, onUnmounted, ref, watch } from 'vue';
import MatrixQuestion from '@/views/Design/components/Questions/MatrixQuestion.vue';
import type { IQuestion, IQuestionOption } from '@/types/question';
import { validateAnswerNum } from '@/views/Survey/views/Preview/components/questions/validate/validateAnswer';
import type { IMatrixCheckboxConfig } from '@/types/questions/matrixCheckbox';
import { validateList } from '@/views/Survey/views/Preview/hooks/useValidateQuestion';
// const questionType = defineModel<number>('questionType', { required: false });

// 矩阵单选的答案类型
type answerType = {
  [key: string]: 1;
};

// preview props
// const stem = defineModel('stem');
// const list = defineModel<questionsList[]>('list', { required: false });
const config = defineModel<IMatrixCheckboxConfig>('config', { required: false });
const question = defineModel<IQuestion>('question', {
  default: () => {}
});

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

const answerIndex = computed(() => question.value?.title ?? 0);
// console.log(question.value);
const emit = defineEmits(['changeAnswer', 'previous', 'next']);
// 示例
// {
//   "1_2": 1,
//   "2_2": 1
// }
const answer = defineModel<answerType>('answer', {
  // 临时赋值, 用于测试
  default: () => ({
    // "1_2": 1,
    // "2_2": 1
  })
});
// const answerIndex = defineModel('answerIndex');
// const answerSn = defineModel('answerSn');
// const answerSurveySn = defineModel('answerSurveySn');
// 记录行和列的索引
const rowRecord = ref<number[]>([]);

// 假如 answer 有数值，需要解析 answer ，然后传递 record 给子组件
answer.value && parseAnswer(answer.value);

/**
 * 解析 answer
 */
function parseAnswer(answer: answerType) {
  // console.log(`come in parseAnswer`);
  const rowRecordList: number[] = [];
  Object.entries(answer).forEach(([key]) => {
    const [row, col] = key.split('_');
    rowRecordList[Number(row) - 1] = Number(col) - 1;
  });
  rowRecord.value = rowRecordList;
  return rowRecordList;
}

/**
 * 获取行和列的内容
 * 行的内容在 question.list[0].options
 * 列的内容在 question.list[1].options
 */
const [rows, cols] = <IQuestionOption[]>question.value?.list;

// 将校验函数 push 给 validateList，以便与点击下一页进行校验。
// 备选方法，此外还可以兼容 pc 答题行为
const validateFun = () => {
  // 答案长度校验
  question.value.error = validateAnswerNum(rowRecord.value, config.value!, rows.options);
};

validateList.value.push(validateFun);
onUnmounted(() => {
  // 在页面卸载的时候，将校验函数从 validateList 中移除
  validateList.value = validateList.value.filter((func) => func !== validateFun);
});

watch(
  rowRecord,
  () => {
    // console.log(`record has changed`, rowRecord.value);
    // 生成 answer
    const newAnswer: answerType = {};
    rowRecord.value.forEach((row, col) => {
      newAnswer[`${col + 1}_${row + 1}`] = 1;
    });

    // 如果行记录答案不够，那么就不进行传递答案
    // if (rowRecord.value.length !== rows.options.length) return;
    const errMsg = validateAnswerNum(rowRecord.value, config.value!, rows.options);
    question.value.error = errMsg;

    // 如果答案有错误，那么就不进行传递答案,并重置之前的答案
    if (errMsg.length > 0) {
      answer.value = {};
      return;
    }

    answer.value = newAnswer;
    emit('changeAnswer', newAnswer);
  },
  { deep: true }
);
</script>
