<!-- 编辑弹窗 -->
<template>
  <Dialog v-model="visible"    :title="'添加试卷任务'" width="460"    @open="handleOpen" center>
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="80px"
      @submit.prevent=""
    >
    <el-form-item label="任务编号" prop="taskNum">
        <el-input clearable v-model="form.taskNum" placeholder="请输入编号" disabled/>
      </el-form-item>
      <el-form-item label="任务名称" prop="taskName">
        <el-input
          clearable
          v-model="form.taskName"
          placeholder="请输入任务名称"
        />
      </el-form-item>
      <el-form-item label="专业" prop="taskSpecialty">
        <el-select
          v-model="form.taskSpecialty"
          placeholder="请选择专业"
          clearable
        >
          <el-option
            v-for="item in specialtyOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="试卷任务模式" prop="taskType">

        <el-radio-group v-model="form.taskType">
          <el-radio
            v-for="dict in getIntDictOptions(DICT_TYPE.TASK_TYPE)"
            :key="dict.value"
            :value="dict.value"
          >
            {{ dict.label }}
          </el-radio>
        </el-radio-group>

      </el-form-item> -->


      <el-form-item label="是否为模板" prop="isTemplate">



        <el-radio-group v-model="form.isTemplate">
          <el-radio
            v-for="dict in getIntDictOptions(DICT_TYPE.SYS_YES_NO)"
            :key="dict.value"
            :value="dict.value"
          >
            {{ dict.label }}
          </el-radio>
        </el-radio-group>

      </el-form-item>
  

      
      <el-form-item label="是否启用" prop="status">

        <el-radio-group v-model="form.status">
          <el-radio
            v-for="dict in getIntDictOptions(DICT_TYPE.SYS_STATUS)"
            :key="dict.value"
            :value="dict.value"
          >
            {{ dict.label }}
          </el-radio>
        </el-radio-group>


     
      </el-form-item>



      
    </el-form>
    <template #footer>
      <el-button @click="handleCancel">取消</el-button>
      <el-button type="primary" :loading="loading" @click="save">
        保存
      </el-button>
    </template>
  </Dialog>
</template>

<script setup>
  import { ref, reactive, nextTick } from 'vue';
  import { onMounted } from 'vue';
  import { useFormData } from '@/utils/use-form-data';
  import { addTask, updateTask,getSpecialtyList } from '@/api/system/task';
  import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
  const props = defineProps({
    /** 修改回显的数据 */
    data: Object
  });
// 专业选项列表
const specialtyOptions = ref([]);
  const emit = defineEmits(['done']);


  const message = useMessage() // 消息弹窗

  /** 弹窗是否打开 */
  const visible = defineModel({ type: Boolean });

  /** 是否是修改 */
  const isUpdate = ref(false);

  /** 提交状态 */
  const loading = ref(false);

  /** 表单实例 */
  const formRef = ref(null);

  /** 表单数据 */
  const [form, resetFields, assignFields] = useFormData({
    taskId: void 0,
    taskName: '',
    taskNum:'',
    taskSpecialty: '',
    taskType: '1',
    isTemplate: '',
    status: '',
    updateTime: '',
    updateBy: '',
    deptId: '',
    userId: ''
  });

    /** 表单验证规则 */
    const rules = reactive({
    taskName: [
      { required: true, message: '任务名称不能为空', trigger: 'blur' }
    ],
    // taskSpecialty: [
    //   { required: true, message: '请选择专业', trigger: 'change' }
    // ],
  
    isTemplate: [
      { required: true, message: '请选择是否为模板', trigger: 'change' }
    ],
    status: [
      { required: true, message: '请选择是否启用', trigger: 'change' }
    ]
  });

  /** 关闭弹窗 */
  const handleCancel = () => {
    visible.value = false;
  };
// 获取专业下拉列表
const fetchSpecialtyOptions = async () => {
  try {
    const data = await getSpecialtyList();
    // 假设返回格式为 [{ label: '计算机', value: 'computer' }, ...]
       // 过滤空字符串并转成下拉格式
       console.log(data)
    specialtyOptions.value = data
      .filter(item => item) // 过滤空字符串
      .map(item => ({
        label: item,
        value: item
      }));
  } catch (e) {
    message.error('获取专业列表失败：' + e.message);
  }
};
  /** 保存编辑 */
  const save = () => {
    formRef.value?.validate?.((valid) => {
      if (!valid) {
        return;
      }
      loading.value = true;
      const saveOrUpdate = isUpdate.value ? updateTask : addTask;
      saveOrUpdate(form)
        .then((msg) => {
          loading.value = false;
          message.success(msg);
          handleCancel();
          emit('done');
        })
        .catch((e) => {
          loading.value = false;
          message.error(e.message);
        });
    });
  };

  /** 弹窗打开事件 */
  const handleOpen = () => {
    if (props.data) {
      assignFields(props.data);
      isUpdate.value = true;
    } else {
      resetFields();
      isUpdate.value = false;
    }
          // 设置批次为 当前时间 + 5位随机数
          const now = new Date();
        const pad = (n) => n.toString().padStart(2, '0');
        const datetimeStr = [
          now.getFullYear(),
          pad(now.getMonth() + 1),
          pad(now.getDate()),
          pad(now.getHours()),
          pad(now.getMinutes()),
          pad(now.getSeconds())
        ].join('');

        const randomNum = Math.floor(Math.random() * 100000).toString().padStart(5, '0');
        //taskNum 赋值 randomNum
        
    // 把 taskNum 设置为当前时间+随机数
    form.taskNum = `${datetimeStr}${randomNum}`;
    nextTick(() => {
      nextTick(() => {
        formRef.value?.clearValidate?.();
      });
    });
  };
  onMounted(() => {
  fetchSpecialtyOptions();
});
defineExpose({ handleOpen })
</script> 