<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 title="选择试题" />
    </el-steps>

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

      <!-- 第二步：选择试题 -->
      <div v-if="currentStep === 1">
        <OptionalQuestionSelect
          ref="questionSelectRef"
          v-model="selectedQuestions"
          :subject-id="props.rowData?.subjectId"
        />
      </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 < 1" type="primary" @click="nextStep">
          下一步
        </el-button>
        <el-button
          v-if="currentStep === 1"
          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,
  } 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 = {
    ruleSelecCount: 1,
    ruleTotalCount: 1,
    scoreRule: 'MAX_SCORE' as const,
  };
  const ruleFormData = reactive({ ...initialRuleFormData });

  // 选中的试题
  const selectedQuestions = ref<number[]>([]);

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

  // 下一步
  const nextStep = async () => {
    if (currentStep.value === 0) {
      // 验证第一步表单
      const valid = await ruleFormRef.value?.validate().catch(() => false);
      if (!valid) return;
    }
    currentStep.value++;
  };

  // 上一步
  const prevStep = () => {
    currentStep.value--;
  };

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

    setLoading(true);
    const params: OptionalRuleUpdateParam = {
      ...ruleFormData,
      questionStructureIds: selectedQuestions.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, {
        ruleSelecCount: props.rowData.ruleSelecCount,
        ruleTotalCount: props.rowData.ruleTotalCount,
        scoreRule: props.rowData.scoreRule,
      });
      selectedQuestions.value = props.rowData.questionStructureIds || [];
    } else {
      // 新增模式
      objModifyAssign(ruleFormData, initialRuleFormData);
      selectedQuestions.value = [];
    }
    currentStep.value = 0;
  }
</script>
