<template>
  <el-dialog 
    title="新增工学交替" 
    v-model="visible"
    :close-on-click-modal="false" 
    draggable
    width="800px">
    <el-form 
      ref="dataFormRef" 
      :model="form" 
      :rules="dataRules" 
      label-width="120px"
      v-loading="loading">
      <el-row :gutter="24">
        <el-col :span="12" class="mb20">
          <el-form-item label="班级" prop="classCode">
            <el-select 
              v-model="form.classCode" 
              placeholder="请选择班级" 
              clearable
              filterable
              style="width: 100%">
              <el-option
                v-for="item in classList"
                :key="item.classCode"
                :label="item.classNo"
                :value="item.classCode">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12" class="mb20">
          <el-form-item label="工学交替日期范围" prop="dateRange">
            <el-date-picker
              v-model="form.dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              style="width: 100%" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="visible = false">取 消</el-button>
        <el-button type="primary" @click="onSubmit" :disabled="loading">确 认</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts" name="StuWorkStudyAlternateFormDialog">
import { ref, reactive, nextTick, onMounted } from 'vue'
import { useMessage } from '/@/hooks/message'
import { addObj } from '/@/api/stuwork/stuworkstudyalternate'
import { getClassListByRole } from '/@/api/basic/basicclass'
import { queryAllStudentByClassCode } from '/@/api/basic/basicstudent'

const emit = defineEmits(['refresh'])

// 定义变量内容
const dataFormRef = ref()
const visible = ref(false)
const loading = ref(false)
const classList = ref<any[]>([])

// 提交表单数据
const form = reactive({
  classCode: '',
  dateRange: null as [string, string] | null
})

// 定义校验规则
const dataRules = {
  classCode: [
    { required: true, message: '请选择班级', trigger: 'change' }
  ],
  dateRange: [
    { required: true, message: '请选择工学交替日期范围', trigger: 'change' }
  ]
}


// 打开弹窗
const openDialog = async () => {
  visible.value = true
  nextTick(() => {
    dataFormRef.value?.resetFields()
    form.classCode = ''
    form.dateRange = null
  })
}

// 提交表单（接口文档要求 classCode、dateRange、stuNoList）
const onSubmit = async () => {
  if (!dataFormRef.value) return

  await dataFormRef.value.validate(async (valid: boolean) => {
    if (!valid) return

    if (!form.dateRange || form.dateRange.length !== 2) {
      useMessage().error('请选择日期范围')
      return
    }

    loading.value = true
    try {
      // 按班级获取学生列表，提取学号作为 stuNoList（接口必传）
      const stuRes = await queryAllStudentByClassCode(form.classCode)
      const list = stuRes?.data && Array.isArray(stuRes.data) ? stuRes.data : []
      const stuNoList = list.map((s: any) => s.stuNo).filter(Boolean)
      if (stuNoList.length === 0) {
        useMessage().warning('该班级暂无学生，无法新增工学交替')
        loading.value = false
        return
      }
      await addObj({
        classCode: form.classCode,
        dateRange: form.dateRange,
        stuNoList
      })
      useMessage().success('新增成功')
      visible.value = false
      emit('refresh')
    } catch (err: any) {
      if (!err?._messageShown) {
        useMessage().error(err?.msg || '新增失败')
      }
    } finally {
      loading.value = false
    }
  })
}

// 获取班级列表
const getClassListData = async () => {
  try {
    const res = await getClassListByRole()
    if (res.data) {
      classList.value = Array.isArray(res.data) ? res.data : []
    }
  } catch (err) {
    classList.value = []
  }
}

// 初始化
onMounted(() => {
  getClassListData()
})

// 暴露方法给父组件
defineExpose({
  openDialog
})
</script>

