<template>
  <a-modal
    v-model:visible="visible"
    title="选择评卷小题"
    width="406px"
    :zIndex="1000"
    wrapClassName="mark-dialog"
    @ok="handleOk"
    @cancel="handleCancel"
  >
    <a-form @keydown.stop="" @keypress.stop="">
      <a-form-item label="选择小题" :required="true" class="tw-mb-2">
        <a-select
          v-model:value="selectedQuestionId"
          placeholder="请选择小题"
          style="width: 100%"
        >
          <a-select-option
            v-for="item in markStore.status"
            :key="item.questionId"
            :value="item.questionId"
          >
            {{ `${item.mainNumber}-${item.subNumber}` }}
          </a-select-option>
        </a-select>
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script setup lang="ts">
import { ref, watch } from "vue";
import { useMarkStore } from "@/store";
import { updateUISetting } from "@/api/markPage";
import useTaskTips from "../composables/useTaskTips";

const markStore = useMarkStore();
const { clearPrevTips } = useTaskTips();

// Using $ref for visible, assuming Vue Reactivity Transform is enabled as in ModalMarkProblem.vue
// If not, this should be: const visible = ref(markStore.selectMarkingQuestionModalVisible);
let visible = $ref(markStore.selectMarkingQuestionModalVisible);
const selectedQuestionId = ref<string | undefined>(undefined);

watch(
  () => markStore.selectMarkingQuestionModalVisible,
  (newVal) => {
    visible = newVal; // Sync local $ref with store state
    if (newVal) {
      // When modal opens, pre-select with current markingQuestionId from store
      selectedQuestionId.value = markStore.curStatus?.questionId || undefined;
    }
  }
);

// Watch local 'visible' $ref to update store if modal is closed by 'x' or ESC
watch(
  () => visible,
  (newVal) => {
    if (markStore.selectMarkingQuestionModalVisible !== newVal) {
      markStore.selectMarkingQuestionModalVisible = newVal;
    }
  }
);

const handleOk = async () => {
  await updateUISetting(
    markStore.setting.mode,
    markStore.setting.uiSetting,
    markStore.setting.questionModel,
    selectedQuestionId.value
  );
  // 清除掉上一次评卷题目缓存，这样就不会提示试题切换信息了
  clearPrevTips();
  window.location.reload();
};

const handleCancel = () => {
  visible = false; // Close modal, which will trigger watcher to update store
};
</script>
