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

<script setup lang="ts">
import MatrixQuestion from '@/views/Design/components/Questions/MatrixQuestion.vue';
import { computed, onUnmounted, ref, watch } from 'vue';
import type { IQuestion, IQuestionOption } from '@/types/question';
import { validateMatrixCheckbox } from '@/views/Survey/views/Preview/components/questions/validate/validateMatrixCheckbox';
import type { MatrixCheckboxAnswerType } from '@/views/Survey/views/Preview/components/questions/types/previewMatrix';
import type { IMatrixCheckboxConfig } from '@/types/questions/matrixCheckbox';
import { validateList } from '@/views/Survey/views/Preview/hooks/useValidateQuestion';

// const questionType = defineModel<number>('questionType', { required: false });

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

console.log(`question value: `, question.value);
const answerIndex = computed(() => question.value.title);
const emit = defineEmits(['changeAnswer', 'previous', 'next']);
// 示例
// {
//   "1_1": 1,
//   "1_2": 1,
//   "2_1": 1,
//   "2_2": 1
// }
const answer = defineModel<MatrixCheckboxAnswerType>('answer', {
  // 临时赋值, 用于测试
  // default: () => ({
  //   "1_1": 1,
  //   "1_2": 1,
  //   "2_1": 1,
  //   "2_2": 1
  // })
});
// const answerIndex = defineModel('answerIndex');
// const answerSn = defineModel('answerSn');
// const answerSurveySn = defineModel('answerSurveySn');

// 记录行和列的索引
// 记录的格式如下，
// [
//   [0, 1],
//   [0, 1]
// ]
const rowRecord = ref<number[][]>([]);

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

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

  return rowRecordList;
}

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

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

// 查看parseAnswer的返回值
// console.log(`parseAnswer value:`, parseAnswer(answer.value!))

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

watch(
  rowRecord,
  (value) => {
    // console.log(`record has changed`, rowRecord.value);
    // 重新生成 answer
    const newAnswer = {} as MatrixCheckboxAnswerType;
    rowRecord.value.forEach((rowOptions, rowIndex) => {
      rowOptions.forEach((colIndex) => {
        const key = `${rowIndex + 1}_${colIndex + 1}`;
        newAnswer[key] = 1;
      });
    });

    /**
     * 校验
     */
    const res: string = validateMatrixCheckbox(
      value,
      question.value.config!,
      question.value.list as IQuestionOption[]
    );
    console.log('res', res);
    question.value.error = res;
    // 如果校验失败，清空 answer
    if (res.length) {
      question.value.answer = undefined;
      return;
    }
    answer.value = newAnswer;
    emit('changeAnswer', newAnswer);
  },
  { deep: true }
);
</script>
