<script setup lang="ts">
import { type Component, computed, defineModel } from 'vue';
import MatrixCheckbox from '@/views/Design/components/Questions/MatrixCheckbox.vue';
import MatrixText from '@/views/Design/components/Questions/MatrixText.vue';
import MatrixRadio from '@/views/Design/components/Questions/MatrixRadio.vue';

const question = defineModel<question>('element', {
  type: Object,
  default: () => {
    return {};
  }
});
const rowRecord = defineModel<unknown[]>('rowRecord', { required: false, default: () => [] });
const isPreview = defineModel<boolean>('isPreview', { required: false, default: false });

// eslint-disable-next-line
const activeComponent = computed<Component>(() => {
  switch (question.value.question_type) {
    case 8:
      return MatrixText;
    case 9:
      return MatrixRadio;
    case 10:
      return MatrixCheckbox;
  }
});

if (question.value?.list) question.value.options = question.value?.list;
// 行标签
const rows = defineModel<questionOptionType[]>('rows', { required: false, default: () => [] });
rows.value.length < 1 && (rows.value = question.value?.options[0] ?? []);
// 列标签
const cols = defineModel<questionOptionType[]>('cols', { required: false, default: () => [] });
cols.value.length < 1 && (cols.value = question.value?.options[1] ?? []);

// console.log(rows.value, cols.value);
// const columnLabels = useTemplateRef<HTMLElement[]>('columnLabels');

// 注意, element.options 里面的东西是数组，第一项内容是行标签内容，第二项内容是列标签内容
// 类型 AI 生成 切勿盲目相信，以实际为准
/* const props = */
defineProps<{
  index: number;
  active: boolean;
}>();

const emit = defineEmits(['update:element']);
const emitValue = () => {
  // console.log(question.value);
  emit('update:element', question.value);
};
const errorMessage = defineModel('errorMessage', {
  type: String,
  default: ''
});
</script>

<template>
  <van-field
    v-model="question.stem"
    :label="question.stem"
    :required="question.config.is_required === 1"
    label-align="top"
    class="contenteditable-question-title"
  >
    <template #left-icon>
      {{ index + 1 }}
    </template>
    <!-- 使用 title 插槽来自定义标题 -->
    <template #label>
      <contenteditable
        v-model="question.stem"
        :active="active"
        className="contenteditable-label"
        @blur="emitValue"
        :errorMessage="errorMessage"
      />
    </template>

    <template #input>
      <Component
        :is="activeComponent"
        v-model:rowRecord="rowRecord"
        v-model:element="question"
        v-model:rows="rows"
        v-model:cols="cols"
        :is-preview="isPreview"
        :active="active"
        style="overflow: scroll; width: 88vw"
      />
    </template>
  </van-field>
</template>
<style lang="scss" scoped>
.matrix-table {
  width: 100%;
  border-collapse: collapse;
  color: black;

  & > tbody {
    overflow: scroll;
  }

  th,
  td {
    border-width: 0 0 1px;
    text-align: center;
  }
}

.td-input {
  text-align: center;
}
</style>
