<template>
  <el-dialog
    v-model="visible"
    :title="title"
    width="600px"
    :before-close="handleClose"
    destroy-on-close
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="120px"
      @keyup.enter="onSubmit"
    >
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="USP批次名称" prop="uspBatchName">
            <el-input
              v-model="form.uspBatchName"
              placeholder="请输入USP批次名称"
              clearable
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="USP批次编号" prop="uspBatchNo">
            <el-input
              v-model="form.uspBatchNo"
              placeholder="请输入USP批次编号"
              clearable
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="项目" prop="projectId">
            <el-select
              v-model="form.projectId"
              placeholder="请选择项目"
              clearable
              filterable
              style="width: 100%"
            >
              <el-option
                v-for="item in projectOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="onSubmit" :loading="loading">
          确认
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, nextTick, onMounted } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage } from 'element-plus'
import { UspBatchApi } from '/@/api/admin/UspBatchApi'
import { ProjectApi } from '/@/api/admin/ProjectApi'
import type { UspBatchDto } from '/@/api/types/uspBatchType'

interface Props {
  title?: string
}

const props = withDefaults(defineProps<Props>(), {
  title: 'USP批次信息'
})

const emit = defineEmits<{
  ok: []
}>()

const visible = ref(false)
const loading = ref(false)
const formRef = ref<FormInstance>()
const isEdit = ref(false)

const form = reactive<UspBatchDto>({
  id: undefined,
  uspBatchName: '',
  uspBatchNo: '',
  projectId: null,
  isDown: true,
  titer: null
})

const projectOptions = ref<Array<{ id: number; name: string }>>([])

const rules: FormRules = {
  uspBatchName: [
    { required: true, message: '请输入USP批次名称', trigger: 'blur' },
    { max: 255, message: 'USP批次名称长度不能超过255个字符', trigger: 'blur' }
  ],
  uspBatchNo: [
    { required: true, message: '请输入USP批次编号', trigger: 'blur' },
    { max: 50, message: 'USP批次编号长度不能超过50个字符', trigger: 'blur' }
  ],
  projectId: [
    { required: true, message: '请选择项目', trigger: 'change' }
  ]
}

onMounted(() => {
  getProjectOptions()
})

const open = (data?: UspBatchDto) => {
  visible.value = true
  isEdit.value = !!data?.id
  
  nextTick(() => {
    if (data) {
      Object.assign(form, data)
    } else {
      resetForm()
    }
    formRef.value?.clearValidate()
  })
}

const resetForm = () => {
  Object.assign(form, {
    id: undefined,
    uspBatchName: '',
    uspBatchNo: '',
    projectId: null,
    isDown: true,
    titer: null
  })
}

const handleClose = () => {
  visible.value = false
  loading.value = false
}

const onSubmit = async () => {
  try {
    await formRef.value?.validate()
    loading.value = true

    const api = new UspBatchApi()
    const res = isEdit.value 
      ? await api.update(form)
      : await api.add(form)

    if (res.success) {
      ElMessage.success(isEdit.value ? '编辑成功' : '新增成功')
      emit('ok')
      handleClose()
    }
  } catch (error) {
    console.error('提交失败:', error)
  } finally {
    loading.value = false
  }
}

const getProjectOptions = async () => {
  try {
    const res = await new ProjectApi().getPage({
      currentPage: 1,
      pageSize: 10000
    })

    if (res?.success) {
      projectOptions.value = res.data?.list?.map(item => ({
        id: item.id ?? 0,
        name: item.projectName ?? ''
      })) ?? []
    }
  } catch (error) {
    console.error('获取项目列表失败:', error)
  }
}

defineExpose({
  open
})
</script>

<style scoped>
.dialog-footer {
  text-align: right;
}
</style> 