<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-code="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"
      :loading="deleteLoading"
      @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>

  <!-- 授权码 -->
  <CodeConfirmDialog
    ref="codeConfirmDialogRef"
    :progress="curMarkerGroupProgress"
    @modified="onCodeConfirm"
  />
</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,
    markGroupDelete,
  } 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';
  import CodeConfirmDialog from '../components/CodeConfirmDialog.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: undefined,
      subjectCode: route.params.subjectCode,
      groupNumber: Number(route.params.groupNumber),
      reset: false,
      groupName: '',
      picList: [],
      questions: [],
      openDouble: false,
      arbitrateType: 'GROUP',
      doubleRate: undefined,
      arbitrateThreshold: undefined,
      scorePolicy: 'AVG_SCORE',
      thirdPolicy: 'CLOSE',
      deleteCode: undefined,
    };
  };
  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;
    ruleFormData.reset = true;
  };

  const { loading: deleteLoading, setLoading: setDeleteLoading } = useLoading();
  const codeConfirmDialogRef = ref<InstanceType<typeof CodeConfirmDialog>>();
  const curMarkerGroupProgress = ref(0);
  const onDelete = () => {
    codeConfirmDialogRef.value?.open();
  };
  async function onCodeConfirm(deleteCode: string) {
    setDeleteLoading(true);
    const params = {
      subjectCode: ruleFormData.subjectCode!,
      number: ruleFormData.groupNumber!,
      deleteCode,
    };
    let res = true;
    await markGroupDelete(params).catch(() => {
      res = false;
    });
    setDeleteLoading(false);
    if (!res) return;

    ElMessage.success(`删除成功！`);
    router.go(-1);
  }

  // 提交
  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,
      editType.value === 'add' ? 'add' : 'update'
    ).catch(() => {
      res = false;
    });
    setLoading(false);
    if (!res) return;

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

  /* init modal */
  async function initData() {
    if (route.params?.groupNumber) {
      // 编辑模式
      const res = await getMarkGroupInfo({
        subjectCode: route.params.subjectCode,
        groupNumber: Number(route.params.groupNumber),
      });
      curMarkerGroupProgress.value = res.percent;
      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>
