<template>
  <el-form
    ref="formRef"
    :model="formModel"
    :rules="formRules"
    label-width="120px"
  >
    <el-form-item label="选做题规则" prop="ruleSelecCount">
      <el-input-number
        v-model="formModel.ruleSelecCount"
        :min="1"
        :max="formModel.ruleTotalCount"
        :step="1"
        :precision="0"
        :controls="false"
        step-strictly
        placeholder="请输入"
        style="width: 80px"
      />
      <span>选</span>
      <el-input-number
        v-model="formModel.ruleTotalCount"
        :min="formModel.ruleSelecCount"
        :max="99"
        :step="1"
        :precision="0"
        :controls="false"
        step-strictly
        placeholder="请输入"
        style="width: 80px"
      />
    </el-form-item>

    <el-form-item label="取分规则" prop="scoreRule">
      <el-radio-group v-model="formModel.scoreRule">
        <el-radio value="MAX_SCORE">最高分</el-radio>
        <el-radio value="MIN_SCORE">最低分</el-radio>
        <el-radio value="MIN_SCORE_NO_ZERO">最低分(去掉0分)</el-radio>
      </el-radio-group>
    </el-form-item>

    <div class="rule-description">
      <p><strong>规则说明：</strong></p>
      <p>• 选做题数量：学生需要选择作答的题目数量</p>
      <p>• 总题数：该选做题组包含的题目总数</p>
      <p>• 取分规则：当学生作答题目数量超过选做题数量时的计分方式</p>
    </div>
  </el-form>
</template>

<script setup lang="ts">
  import { ref, watch, nextTick } from 'vue';
  import type { FormInstance, FormRules } from 'element-plus';
  import type { OptionalScoreRule } from '@/api/types/subject';
  import { isEmpty } from '@/utils/utils';

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

  interface FormData {
    ruleSelecCount: number;
    ruleTotalCount: number;
    scoreRule: OptionalScoreRule;
  }

  interface Props {
    modelValue: FormData;
  }

  const props = defineProps<Props>();
  const emit = defineEmits<{
    'update:modelValue': [value: FormData];
  }>();

  const formRef = ref<FormInstance>();
  const formModel = ref<FormData>({ ...props.modelValue });

  // 监听表单数据变化，同步到父组件
  const isUpdatingFromParent = ref(false);
  watch(
    formModel,
    (newVal) => {
      if (!isUpdatingFromParent.value) {
        emit('update:modelValue', { ...newVal });
      }
    },
    { deep: true }
  );

  // 监听父组件数据变化
  watch(
    () => props.modelValue,
    (newVal) => {
      isUpdatingFromParent.value = true;
      formModel.value = { ...newVal };
      nextTick(() => {
        isUpdatingFromParent.value = false;
      });
    },
    { deep: true }
  );

  const formRules: FormRules<keyof FormData> = {
    ruleSelecCount: [
      {
        validator: (rule, value, callback) => {
          if (
            !isEmpty(formModel.value.ruleTotalCount) ||
            !isEmpty(formModel.value.ruleSelecCount)
          ) {
            return callback(new Error('请完成数量输入'));
          }

          if (
            formModel.value.ruleSelecCount >= formModel.value.ruleTotalCount
          ) {
            return callback(new Error('选做题数量不能大于总题数'));
          }

          return callback();
        },
        trigger: 'change',
      },
    ],
    scoreRule: [
      { required: true, message: '请选择取分规则', trigger: 'change' },
    ],
  };

  // 暴露验证方法
  const validate = () => {
    return formRef.value?.validate();
  };

  defineExpose({
    validate,
  });
</script>

<style scoped>
  .rule-description {
    background-color: #f5f7fa;
    padding: 16px;
    border-radius: 4px;
    margin-top: 20px;
  }

  .rule-description p {
    margin: 0 0 8px 0;
    color: #606266;
    font-size: 14px;
  }

  .rule-description p:last-child {
    margin-bottom: 0;
  }

  .rule-description strong {
    color: #303133;
  }
</style>
