<template>
  <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">
      <GroupQuestionSelect
        ref="questionSelectRef"
        v-model="ruleFormData.questions"
        :subject-id="props.rowData?.subjectCode"
      />
    </div>
    <!-- 第二步：设置规则 -->
    <div v-if="currentStep === 1">
      <GroupRuleForm
        ref="ruleFormRef"
        v-model="ruleFormData"
        :edit-type="editType"
      />
    </div>
  </div>

  <div class="dialog-footer">
    <el-button @click="cancel">取消</el-button>
    <el-button v-if="currentStep > 0 && !isEdit" @click="prevStep"
      >上一步</el-button
    >
    <el-button v-if="currentStep < 1" type="primary" @click="nextStep">
      下一步
    </el-button>
    <el-button
      v-if="currentStep === 1 && isReset"
      type="danger"
      @click="onDelete"
    >
      删除
    </el-button>
    <el-button
      v-if="currentStep === 1 && isEdit"
      type="danger"
      @click="onReset"
    >
      重置修改
    </el-button>
    <el-button
      v-if="currentStep === 1"
      type="primary"
      :loading="loading"
      @click="confirm"
    >
      保存
    </el-button>
  </div>
</template>

<script setup lang="ts">
  import { ref, computed, reactive, onMounted } from 'vue';
  import { useRoute, useRouter } from 'vue-router';
  import { ElMessage } from 'element-plus';
  import { getMarkGroupInfo, markGroupUpdate } from '@/api/mark';
  import type { MarkGroupUpdateParams } from '@/api/types/mark';
  import useLoading from '@/hooks/loading';

  import { objModifyAssign } from '@/utils/utils';

  import GroupRuleForm from './GroupRuleForm.vue';
  import GroupQuestionSelect from './GroupQuestionSelect.vue';

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

  // 编辑类型：新增、编辑、重置
  type EditType = 'add' | 'edit' | 'reset';

  const route = useRoute();
  const router = useRouter();

  const editType = ref<EditType>('add');
  const isEdit = computed(() => editType.value === 'edit');
  const isReset = computed(() => editType.value === 'reset');
  // const isAdd = computed(() => editType.value === 'add');

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

  // 规则表单数据
  const getInitialRuleFormData = (): MarkGroupUpdateParams => {
    return {
      id: route.params?.groupId,
      subjectCode: route.params.subjectCode,
      groupNo: 0,
      name: '',
      markingArea: [],
      questions: [],
      doubleMarking: false,
      arbitrationType: 'GROUP',
      doubleMarkingRatio: undefined,
      arbitrationThreshold: undefined,
      combinationStrategy: 'AVG_SCORE',
      threeMarkingRule: 'CLOSE',
    };
  };
  const ruleFormData = reactive(getInitialRuleFormData());

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

  // 下一步
  const nextStep = async () => {
    if (currentStep.value === 0) {
      // 验证第一步表单

      const valid = await questionSelectRef.value
        ?.validate()
        .catch(() => false);
      if (!valid) return;
    }
    currentStep.value++;
  };

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

  const onReset = () => {
    editType.value = 'reset';
    currentStep.value = 0;
  };

  const onDelete = async () => {
    // TODO: 删除分组
  };

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

    setLoading(true);
    const params: MarkGroupUpdateParams = {
      ...ruleFormData,
      questions: selectedQuestions.value,
    };

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

    ElMessage.success(`保存成功！`);
  };

  /* init modal */
  async function initData() {
    if (route.params?.groupId) {
      // 编辑模式
      const res = await getMarkGroupInfo(route.params.groupId);
      objModifyAssign(ruleFormData, res);
      editType.value = 'edit';
      currentStep.value = 1;
    } else {
      editType.value = 'add';
      currentStep.value = 0;
    }
    currentStep.value = 0;
  }

  function cancel() {
    router.go(-1);
  }

  onMounted(() => {
    initData();
  });
</script>
