<template>
  <el-dialog
    v-model="visible"
    title="打回"
    width="500px"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    top="10vh"
    append-to-body
    @close="handleClose"
    @open="modalBeforeOpen"
  >
    <el-form
      ref="formRef"
      :model="formModel"
      :rules="rules"
      label-width="100px"
    >
      <el-form-item label="打回原因" prop="rejectType">
        <el-select
          v-model="formModel.rejectType"
          placeholder="请选择打回原因"
          style="width: 100%"
        >
          <el-option
            v-for="item in rejectTypeList"
            :key="item.id"
            :label="item.name"
            :value="item.name"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="详情描述">
        <el-input
          v-model="formModel.rejectReason"
          type="textarea"
          :rows="4"
          placeholder="请输入详情描述"
          maxlength="500"
          show-word-limit
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="close">取消</el-button>
        <el-button type="primary" :loading="loading" @click="confirm">
          打回
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
  import { ref, reactive, onMounted } from 'vue';
  import type { FormInstance, FormRules } from 'element-plus';
  import { ElMessage } from 'element-plus';
  import type { MarkRejectTaskParam } from '@/api/types/mark';
  import type { RejectTypeItem } from '@/api/types/reject';
  import { markTaskReject } from '@/api/mark';
  import { getRejectTypeList } from '@/api/reject';
  import useModal from '@/hooks/modal';
  import useLoading from '@/hooks/loading';
  import { objAssign } from '@/utils/utils';
  import { useAppStore } from '@/store';

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

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

  interface Props {
    taskId?: number; // 任务ID
  }

  const props = defineProps<Props>();
  const emit = defineEmits(['modified']);

  const appStore = useAppStore();

  const formRef = ref<FormInstance>();
  const rejectTypeList = ref<RejectTypeItem[]>([]);

  const initialFormState: MarkRejectTaskParam = {
    id: 0,
    rejectType: '',
    rejectReason: '',
  };

  const formModel = reactive<MarkRejectTaskParam>({ ...initialFormState });

  const rules: FormRules<keyof MarkRejectTaskParam> = {
    rejectType: [
      { required: true, message: '请选择打回原因', trigger: 'change' },
    ],
  };

  const handleClose = () => {
    formRef.value?.resetFields();
    Object.assign(formModel, initialFormState);
  };

  /* confirm */
  const { loading, setLoading } = useLoading();
  async function confirm() {
    if (!formRef.value) return;

    const valid = await formRef.value?.validate().catch(() => false);
    if (!valid) return;

    setLoading(true);
    const datas = objAssign(formModel, {});
    let res = true;
    await markTaskReject(datas).catch(() => {
      res = false;
    });
    setLoading(false);
    if (!res) return;
    ElMessage.success('打回成功！');
    emit('modified');
    close();
  }

  /* init modal */
  function modalBeforeOpen() {
    if (props.taskId) {
      formModel.id = props.taskId;
    }
  }

  /* 获取打回类型列表 */
  async function loadRejectTypeList() {
    if (!appStore.curExam.id) return;
    try {
      const res = await getRejectTypeList(appStore.curExam.id);
      rejectTypeList.value = res || [];
    } catch (error) {
      console.error('获取打回类型列表失败:', error);
      rejectTypeList.value = [];
    }
  }

  onMounted(() => {
    // 获取打回类型列表
    loadRejectTypeList();
  });
</script>
