<template>
  <div :class="isNoShowAction ? 'noAction' : ''" style="width: 100%">
    <n-form
      ref="formRef"
      label-placement="left"
      size="medium"
      :model="state"
      :rules="formRules"
      require-mark-placement="left"
    >
      <n-form-item v-if="props.type !== 'shortAnswer'" :show-label="false" path="option">
        <n-dynamic-input
          v-model:value="state.option"
          show-sort-button
          placeholder="请输入"
          :min="props.min"
          :max="props.max"
          :disabled="props.disableAll"
          @create="handleCreate"
        >
          <template #default="{ value, index }">
            <div style="display: flex; align-items: center">
              <n-form-item
                ignore-path-change
                :show-label="false"
                :path="`option[${index}].optionName`"
                :rule="contentRule"
              >
                <n-button
                  disabled
                  size="large"
                  class="answerTitle"
                  style="width: 47px"
                >
                  {{ props.serialNumStr[index] }}
                </n-button>
                <n-input
                  v-model:value="value.optionName"
                  type="text"
                  size="large"
                  class="answerContent flex-1"
                  :readonly="props.type === 'tureOrFalse'"
                  :disabled="props.disableAll"
                  :placeholder="
                    props.type === 'completion'
                      ? `请输入第${index + 1}个空的答案`
                      : '请输入选项内容'
                  "
                  @keydown.enter.prevent
                />
                <n-radio
                  v-if="props.type === 'radio' || props.type === 'tureOrFalse'"
                  :checked="state.answers.includes(props.serialNumStr[index])"
                  :disabled="props.disableAll"
                  @update:checked="() => handleRadioChange(value, index)"
                />
                <n-checkbox
                  v-else-if="props.type === 'check'"
                  :checked="state.answers.includes(props.serialNumStr[index])"
                  :disabled="props.disableAll"
                  @update:checked="
                    (checked) => handleCheckboxChange(index, checked)
                  "
                />
              </n-form-item>
            </div>
          </template>
        </n-dynamic-input>
      </n-form-item>
      <n-form-item v-else :show-label="false" path="shortAnswerVal">
        <n-input
          v-model:value="state.shortAnswerVal"
          type="textarea"
          show-count
          :maxlength="1000"
          :autosize="{
            minRows: 5,
            maxRows: 7,
          }"
          @update:value="handleSAChange"
          placeholder="请输入答案"
        />
      </n-form-item>
    </n-form>
  </div>
</template>
<script setup>
import { ref, reactive } from "vue";
import {
  BagAddOutline as AddIcon,
  ChevronDownCircleOutline as DownIcon,
  BagRemoveOutline as RemoveIcon,
  ChevronUpCircleOutline as UpIcon,
} from "@vicons/ionicons5";
import { cloneDeep } from "lodash-es";

const props = defineProps({
  option: {
    type: [Array, String],
    default: [],
    required: true,
  },
  // completion 填空题 radio 单选 check 多选 tureOrFalse 判断题 shortAnswer 简答题
  type: {
    type: String,
    default: "radio",
    required: true,
  },
  answers: {
    type: Array,
    default: [],
    required: false,
  },
  min: {
    type: Number,
    default: 1,
    required: true,
  },
  max: {
    type: Number,
    default: 9,
    required: true,
  },
  serialNumStr: {
    type: Array,
    default: ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J"],
    required: false,
  },
  disableAll:{
    type: Boolean,
    default: false,
    required: false,
  }
});
const emits = defineEmits(["update:value"]);
const formRef = ref(null);
const state = reactive({
  option: [],
  shortAnswerVal: "",
  answers: [],
});

const formRules = reactive({
  shortAnswerVal: {
    required: true,
    message: "请选择",
    trigger: ["blur", "change"],
  },
  option: {
    message: "未勾选答案",
    validator: (rule, value) => validateValAnswer(rule, value),
  },
});

const validateValRequire = (rule, value) => {
  if (!value || value?.trim() === "") {
    return false;
  }
  return true;
};

const validateValAnswer = (rule, value) => {
  if (props.type === "completion" || props.type === "shortAnswer") {
    return true;
  }
  return state.answers.length ? true : false;
};

const contentRule = reactive([
  {
    required: true,
    message: "请输入",
    validator: (rule, value) => validateValRequire(rule, value),
    trigger: ["blur", "change"],
  },
]);

const exposeValue = computed(() => {
  let listT = [];
  listT = state.option.map((v, i) => {
    return {
      optionId: props.serialNumStr[i],
      optionName: props.type !== 'completion'? v.optionName:'',
    };
  });
  return listT;
});

const answerVal = computed(() => {
  let answerT = [];
  if (!exposeValue.value.length && props.type !=='shortAnswer') {
    return [];
  }
  switch (props.type) {
    case "radio":
      answerT = state.answers;
      break;
    case "check":
      answerT = state.answers;
      break;
    case "tureOrFalse":
      answerT = state.answers;
      break;
    case "completion":
      answerT = state.option.map((v) => v.optionName);
      break;
    case "shortAnswer":
      answerT = state.answers;
      break;
    default:
      break;
  }
  return answerT;
});

const validateComputed = computed(() => {
  let fn = null;
  if (formRef?.value) {
    fn = formRef?.value.validate;
  }
  return fn;
});

defineExpose({
  exposeValue,
  answerVal,
  validate: validateComputed,
});

const isNoShowAction = computed(() => {
  let flag = false;
  switch (props.type) {
    case "tureOrFalse":
      flag = true;
      break;

    default:
      flag = false;
      break;
  }
  return flag;
});

const handleCreate = (index) => {
  return {
    optionId: "",
    optionName: "",
    isCheck: false,
  };
};

const handleSAChange = (value) => {
  state.answers = [value ? value.trim() : ""];
};

const handleRadioChange = (value, index) => {
  state.answers = [props.serialNumStr[index]];
};

const handleCheckboxChange = (index, checked) => {
  if (checked) {
    state.answers.push(props.serialNumStr[index]);
  } else {
    state.answers = state.answers.filter(
      (v) => v !== props.serialNumStr[index]
    );
  }
};

const initData = () => {
  if (props.type !== "shortAnswer") {
    state.option = cloneDeep(props.option);
    state.answers = cloneDeep(props.answers);
    state.shortAnswerVal = "";
  } else {
    state.option = [];
    state.answers = [];
    state.shortAnswerVal = cloneDeep(props.answers[0]);
  }
};

watch(
  props,
  (newValue, oldValue) => {
    initData();
  },
  { deep: true, immediate: true }
);
</script>
<style lang="scss" scoped>
.answerTitle {
  margin-right: 10px;
}

.answerContent {
  width: 600px;
  margin-right: 20px;
}
.noAction {
  :deep(.n-dynamic-input-item__action) {
    display: none;
  }
}
</style>
