<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="100px"
      @keyup.enter="onSubmit"
    >
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="批次名称" prop="preBatchName">
            <el-input
              v-model="form.preBatchName"
              placeholder="请输入批次名称"
              clearable
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="批次编号" prop="preBatchNo">
            <el-input
              v-model="form.preBatchNo"
              placeholder="请输入批次编号"
              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 { PreBatchApi } from '/@/api/admin/PreBatchApi'
import { ProjectApi } from '/@/api/admin/ProjectApi'
import type { PreBatchDto } from '/@/api/types/preBatchType'

interface Props {
  title?: string
}

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

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

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

const form = reactive<PreBatchDto>({
  id: undefined,
  preBatchName: '',
  preBatchNo: '',
  projectId: null,
  isDown: true,
  titer: null
})

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

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

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

const open = (data?: PreBatchDto) => {
  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,
    preBatchName: '',
    preBatchNo: '',
    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 PreBatchApi()
    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> 