<template>
  <el-dialog
    v-model="visible"
    :title="title"
    width="800px"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    top="10vh"
    append-to-body
    @close="handleClose"
    @open="modalBeforeOpen"
  >
    <el-steps :active="currentStep" finish-status="success">
      <el-step title="设置规则" />
      <el-step
        v-for="(step, index) in ruleFormData.selectiveCount"
        :key="index"
        :title="`选择试题组${index + 1}`"
      />
    </el-steps>

    <div style="margin-top: 20px">
      <!-- 第一步：设置规则 -->
      <div v-if="currentStep === 0">
        <OptionalRuleForm ref="ruleFormRef" v-model="ruleFormData" />
      </div>

      <!-- 选择试题步骤 -->
      <div v-if="currentStep > 0">
        <div style="margin-bottom: 16px; font-weight: bold">
          选择试题组{{ currentStep }}（第{{ currentStep }}个选做题区）
        </div>
        <OptionalQuestionSelect
          ref="questionSelectRef"
          v-model="currentStepSelection"
          :subject-code="props.rowData?.subjectCode"
          :current-step="currentStep"
          :selected-parts="selectedParts"
        />
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="close">取消</el-button>
        <el-button v-if="currentStep > 0" @click="prevStep">上一步</el-button>
        <el-button
          v-if="currentStep < ruleFormData.selectiveCount"
          type="primary"
          @click="nextStep"
        >
          下一步
        </el-button>
        <el-button
          v-if="currentStep === ruleFormData.selectiveCount"
          type="primary"
          :loading="loading"
          @click="confirm"
        >
          保存
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
  import { ref, computed, reactive } from 'vue';
  import { ElMessage } from 'element-plus';
  import { saveOptionalQuestionRule } from '@/api/subject';
  import type {
    OptionalRuleItem,
    OptionalRuleUpdateParam,
    OptionalRulePart,
  } from '@/api/types/subject';
  import useModal from '@/hooks/modal';
  import useLoading from '@/hooks/loading';
  import { objModifyAssign } from '@/utils/utils';
  import OptionalRuleForm from './OptionalRuleForm.vue';
  import OptionalQuestionSelect from './OptionalQuestionSelect.vue';

  defineOptions({
    name: 'ModifyOptionalQuestionRule',
  });

  /* modal */
  const { visible, open, close } = useModal();
  defineExpose({ open, close });

  interface Props {
    rowData: OptionalRuleItem;
  }

  const props = withDefaults(defineProps<Props>(), {
    rowData: () => {},
  });

  const emit = defineEmits(['modified']);

  const isEdit = computed(() => !!props.rowData?.id);
  const title = computed(() => `${isEdit.value ? '编辑' : '新增'}选做题规则`);

  const currentStep = ref(0);
  const ruleFormRef = ref();
  const questionSelectRef = ref();

  // 规则表单数据
  const initialRuleFormData = {
    selectivePart: 1,
    selectiveCount: 1,
    scorePolicy: 2 as const,
  };
  const ruleFormData = reactive({ ...initialRuleFormData });

  // 选中的结构
  const selectedParts = ref<OptionalRulePart[]>([]);
  // 当前步骤选择的试题
  const currentStepSelection = ref<number[]>([]);

  const handleClose = () => {
    currentStep.value = 0;
    objModifyAssign(ruleFormData, initialRuleFormData);
    selectedParts.value = [];
    currentStepSelection.value = [];
  };

  // 下一步
  const nextStep = async () => {
    if (currentStep.value === 0) {
      // 验证第一步表单
      const valid = await ruleFormRef.value?.validate().catch(() => false);
      if (!valid) return;
    } else {
      // 验证当前步骤的试题选择
      const valid = await questionSelectRef.value
        ?.validate()
        .catch(() => false);
      if (!valid) return;

      // 构建当前步骤的OptionalRulePart数据
      const currentPart: OptionalRulePart = {
        selectivePart: currentStep.value.toString(),
        mainNumbers: currentStepSelection.value,
      };
      selectedParts.value.push(currentPart);
    }

    currentStep.value++;
    currentStepSelection.value = [];
  };

  // 上一步
  const prevStep = () => {
    if (currentStep.value > 1) {
      // 清除当前步骤的OptionalRulePart数据
      selectedParts.value.pop();
      currentStepSelection.value = selectedParts.value.slice(-1)[0].mainNumbers;
    } else {
      currentStepSelection.value = [];
    }
    currentStep.value--;
  };

  // 提交
  const { loading, setLoading } = useLoading();
  const confirm = async () => {
    // 验证最后一步
    const valid = await questionSelectRef.value?.validate().catch(() => false);
    if (!valid) return;

    // 构建最后一步的OptionalRulePart数据
    const lastPart: OptionalRulePart = {
      selectivePart: currentStep.value.toString(),
      mainNumbers: currentStepSelection.value,
    };
    selectedParts.value.push(lastPart);

    setLoading(true);
    const params: OptionalRuleUpdateParam = {
      ...ruleFormData,
      parts: selectedParts.value,
    };

    if (props.rowData?.id) {
      params.id = props.rowData.id;
    }

    let res = true;
    await saveOptionalQuestionRule(params).catch(() => {
      res = false;
    });
    setLoading(false);
    if (!res) return;

    ElMessage.success(`${title.value}成功！`);
    emit('modified');
    close();
  };

  /* init modal */
  function modalBeforeOpen() {
    if (props.rowData?.id) {
      // 编辑模式
      objModifyAssign(ruleFormData, {
        selectivePart: props.rowData.selectivePart || 1,
        selectiveCount: props.rowData.selectiveCount || 1,
        scorePolicy: props.rowData.scorePolicy || 2,
      });
      selectedParts.value = props.rowData.parts || [];
    } else {
      // 新增模式
      objModifyAssign(ruleFormData, initialRuleFormData);
      selectedParts.value = [];
    }
    currentStep.value = 0;
    currentStepSelection.value = [];
  }
</script>
