<template>
  <el-dialog
    v-model="visible"
    title="编辑选做题组"
    width="800px"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    top="10vh"
    append-to-body
    @close="handleClose"
    @open="modalBeforeOpen"
  >
    <el-button type="primary" @click="addRule">新增</el-button>
    <el-table v-loading="loading" :data="ruleList" border stripe>
      <el-table-column label="选做题组" width="120">
        <template #default="{ row }">
          {{ `${row.ruleSelecCount}选${row.ruleTotalCount}` }}
        </template>
      </el-table-column>

      <el-table-column label="规则" width="150">
        <template #default="{ row }">
          {{ dictFilter.optionalScoreRule(row.scoreRule) }}
        </template>
      </el-table-column>

      <el-table-column label="大题名称" prop="mainTitle"> </el-table-column>

      <el-table-column label="分值" width="100">
        <template #default="{ row }">
          {{ row.score }}
        </template>
      </el-table-column>

      <el-table-column label="操作" width="120">
        <template #default="{ row }">
          <el-button type="primary" size="small" @click="editRule(row)">
            编辑
          </el-button>
          <el-button type="danger" size="small" @click="deleteRule(row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <template #footer> </template>
  </el-dialog>

  <ModifyOptionalQuestionRule
    ref="modifyOptionalQuestionRuleRef"
    :row-data="OptionalRuleItem"
    @modified="ruleModified"
  />
</template>

<script setup lang="ts">
  import { ref } from 'vue';
  import { ElMessage } from 'element-plus';
  import {
    getOptionalQuestionRuleList,
    deleteOptionalQuestionRule,
  } from '@/api/subject';
  import type { OptionalRuleItem } from '@/api/types/subject';
  import useModal from '@/hooks/modal';
  import useLoading from '@/hooks/loading';
  import { modalConfirm } from '@/utils/ui';
  import { dictFilter } from '@/utils/filter';

  import ModifyOptionalQuestionRule from './ModifyOptionalQuestionRule.vue';

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

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

  interface Props {
    subjectCode: string;
  }

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

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

  const modifyOptionalQuestionRuleRef =
    ref<InstanceType<typeof ModifyOptionalQuestionRule>>();
  const ruleList = ref<OptionalRuleItem[]>([]);
  const curRow = ref<OptionalRuleItem>();
  const { loading, setLoading } = useLoading();

  const handleClose = () => {
    ruleList.value = [];
  };

  // 加载选做题规则列表
  const getList = async () => {
    if (!props.subjectCode) return;

    setLoading(true);
    try {
      const data = await getOptionalQuestionRuleList(props.subjectCode);
      ruleList.value = data || [];
    } catch (error) {
      ElMessage.error('获取选做题规则列表失败');
      ruleList.value = [];
    } finally {
      setLoading(false);
    }
  };

  // 编辑规则
  const editRule = (row: OptionalRuleItem) => {
    curRow.value = row;
    modifyOptionalQuestionRuleRef.value?.open();
  };

  // 新增规则
  const addRule = () => {
    curRow.value = {};
    modifyOptionalQuestionRuleRef.value?.open();
  };

  // 删除规则
  const deleteRule = async (row: OptionalRuleItem) => {
    const confirm = await modalConfirm(
      '确定要删除这条选做题规则吗？',
      '提示'
    ).catch(() => false);
    if (!confirm) return;

    try {
      await deleteOptionalQuestionRule(row.id);
      ElMessage.success('删除成功');
      getList();
      emit('modified');
    } catch (error) {
      console.error('删除失败:', error);
    }
  };

  const ruleModified = () => {
    getList();
    emit('modified');
  };

  /* init modal */
  const modalBeforeOpen = () => {
    getList();
  };
</script>
