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

<script setup lang="ts">
// import MatrixText from '@/views/Design/components/Questions/MatrixText.vue';
import { computed, ref, watch } from 'vue';
import MatrixQuestion from '@/views/Design/components/Questions/MatrixQuestion.vue';
const answerIndex = computed(() => question.value?.title ?? 0);

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

const question = defineModel<question>('question', { default: () => {} });
const emit = defineEmits(['changeAnswer', 'previous', 'next']);
// 示例
// {
//   "1_1": 1,
//   "1_2": 1,
//   "2_1": 1,
//   "2_2": 1
// }
const answer = defineModel<answerType>('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');

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

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

// console.log(`answer value`, answer.value);
/**
 * 解析 answer
 */
function parseAnswer(answer: answerType) {
  const rowRecordList: string[][] = [];
  Object.entries(answer).forEach(([key, value]) => {
    const [row, col] = key.split('_');
    // 如果对应位置不存在数组， 重新建立
    if (!rowRecordList[Number(row) - 1]) rowRecordList[Number(row) - 1] = [];
    // console.log(`value ${value}`);
    rowRecordList[Number(row) - 1][Number(col) - 1] = value;
  });
  rowRecord.value = rowRecordList;

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

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

watch(
  rowRecord,
  () => {
    // 重新生成 answer
    const newAnswer: answerType = {};
    rowRecord.value.forEach((rows, rowIndex) => {
      rows.forEach((col, colIndex) => {
        newAnswer[`${rowIndex + 1}_${colIndex + 1}`] = col;
      });
    });
    answer.value = newAnswer;
    emit('changeAnswer', newAnswer);
  },
  { deep: true }
);
</script>
