<template>
  <div>
    <el-dialog
      v-model="dialogVisible"
      destroy-on-close
      :title="formData.id ? '编辑培养基' : '新增培养基'"
      draggable
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      width="900px"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="120px"
        size="default"
      >
        <!-- 基本信息 -->
        <div class="form-section">
          <div class="section-title">基本信息</div>
          <el-row :gutter="25">
            <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
              <el-form-item label="培养基名称" prop="mediumName" :rules="[{ required: true, message: '请输入培养基名称', trigger: ['blur', 'change'] }]">
                <el-input v-model="form.mediumName" clearable placeholder="请输入培养基名称" />
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
              <el-form-item label="启用状态">
                <el-switch
                  v-model="form.status"
                  active-text="启用"
                  inactive-text="禁用"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </div>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleCancel" size="default">取 消</el-button>
          <el-button type="primary" @click="handleSubmit" size="default" :loading="loading">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, watch, computed } from 'vue'
import { ElMessage } from 'element-plus'
import type { FormInstance } from 'element-plus'
import { ItemDefBasicMediumApi } from '/@/api/admin/item-def-basic-medium'
import type { BasicMediumDto } from '/@/types/data-contracts'

const props = defineProps<{
  visible: boolean
  formData: Partial<BasicMediumDto>
}>()

const emit = defineEmits<{
  (e: 'update:visible', value: boolean): void
  (e: 'success'): void
}>()

const api = new ItemDefBasicMediumApi()
const formRef = ref<FormInstance>()
const loading = ref(false)

// 使用计算属性处理 visible 的双向绑定
const dialogVisible = computed({
  get: () => props.visible,
  set: (val) => emit('update:visible', val)
})

const form = reactive<Partial<BasicMediumDto>>({
  mediumName: '',
  status: true
})

const rules = {
  mediumName: [
    { required: true, message: '请输入培养基名称', trigger: ['blur', 'change'] }
  ]
}

// 监听 formData 变化，更新表单数据
watch(
  () => props.formData,
  (newVal) => {
    if (newVal) {
      Object.assign(form, newVal)
    }
  },
  { immediate: true }
)

// 监听 visible 变化，重置表单
watch(
  () => props.visible,
  (newVal) => {
    if (!newVal) {
      formRef.value?.resetFields()
    }
  }
)

const handleCancel = () => {
  emit('update:visible', false)
}

const handleSubmit = async () => {
  if (!formRef.value) return

  await formRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true
      try {
        // 确保必填字段有值
        const submitData: BasicMediumDto = {
          mediumName: form.mediumName || '',
          status: form.status ?? true,
          id: form.id || 0,
          createdTime: form.createdTime || new Date().toISOString(),
          modifiedTime: new Date().toISOString(),
          isDeleted: false
        }

        if (form.id) {
          // 编辑
          const res = await api.update(submitData)
          if (res.success) {
            ElMessage.success('修改成功')
            emit('success')
            emit('update:visible', false)
          } else {
            ElMessage.error('修改失败')
          }
        } else {
          // 新增
          const res = await api.add(submitData)
          if (res.success) {
            ElMessage.success('新增成功')
            emit('success')
            emit('update:visible', false)
          } else {
            ElMessage.error(res.msg || '新增失败')
          }
        }
      } catch (error) {
        console.error('操作失败:', error)
        ElMessage.error('操作失败')
      } finally {
        loading.value = false
      }
    }
  })
}
</script>

<style lang="scss" scoped>
.form-section {
  margin-bottom: 24px;

  .section-title {
    font-size: 16px;
    font-weight: bold;
    margin-bottom: 16px;
    padding-left: 8px;
    border-left: 4px solid var(--el-color-primary);
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}
</style>
