<template>
  <div class="submit-container">
    <div class="page-header">
      <h2>提交任务</h2>
    </div>

    <el-card>
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="脚本内容" prop="script">
          <el-input
            v-model="form.script"
            type="textarea"
            :rows="10"
            placeholder="请输入脚本内容"
          />
        </el-form-item>

        <el-form-item label="任务名称" prop="job_name">
          <el-input v-model="form.job_name" placeholder="请输入任务名称" />
        </el-form-item>

        <el-form-item label="分区" prop="partition">
          <el-input v-model="form.partition" placeholder="请输入分区" />
        </el-form-item>

        <el-form-item label="QOS" prop="qos">
          <el-input v-model="form.qos" placeholder="请输入 QOS" />
        </el-form-item>

        <el-form-item label="CPU数量" prop="cpus">
          <el-input-number v-model="form.cpus" :min="1" />
        </el-form-item>

        <el-form-item label="时间限制" prop="time_limit">
          <el-input v-model="form.time_limit" placeholder="如: 1:00:00" />
        </el-form-item>

        <el-form-item label="工作目录" prop="work_dir">
          <el-input v-model="form.work_dir" placeholder="请输入工作目录" />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" :loading="submitting" @click="handleSubmit">
            提交
          </el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { submitJob } from '@/api/jobs'
import type { SubmitJobRequest } from '@/types/jobs'
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'

const router = useRouter()
const formRef = ref<FormInstance>()
const submitting = ref(false)

const form = reactive<SubmitJobRequest>({
  script: '',
  job_name: '',
  partition: '',
  qos: '',
  cpus: undefined,
  time_limit: '',
  work_dir: '',
})

const rules: FormRules = {
  script: [
    { required: true, message: '请输入脚本内容', trigger: 'blur' },
  ],
}

const handleSubmit = async () => {
  if (!formRef.value) return
  await formRef.value.validate(async (valid) => {
    if (!valid) return
    submitting.value = true
    try {
      const resp = await submitJob({ ...form })
      if (resp.success) {
        ElMessage.success(`任务提交成功，Job ID: ${resp.data?.job_id}`)
        setTimeout(() => {
          router.push('/jobs')
        }, 1000)
      } else {
        ElMessage.error(resp.error || '提交失败')
      }
    } catch {
      // Error already handled by Axios interceptor
    } finally {
      submitting.value = false
    }
  })
}

const handleReset = () => {
  form.script = ''
  form.job_name = ''
  form.partition = ''
  form.qos = ''
  form.cpus = undefined
  form.time_limit = ''
  form.work_dir = ''
  formRef.value?.clearValidate()
}
</script>
