<template>
  <el-dialog
    :model-value="visible"
    :title="title"
    @close="handleClose"
    :close-on-click-modal="false"
    width="500px"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="rules"
      label-width="100px"
      @submit.prevent
    >
      <el-form-item label="猪舍名称" prop="name">
        <el-input v-model="formData.name" placeholder="请输入猪舍名称" />
      </el-form-item>
      <el-form-item label="描述" prop="description">
        <el-input v-model="formData.description" type="textarea" placeholder="请输入描述信息" />
      </el-form-item>
    </el-form>

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

<script>
import { ref, reactive, watch, computed, nextTick } from 'vue';
import { ElMessage } from 'element-plus';
import { createPigHouse, updatePigHouse } from '@/api/pigHouse.js';

export default {
  name: 'PigHouseForm',
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    houseData: {
      type: Object,
      default: () => ({})
    },
    isEdit: {
      type: Boolean,
      default: false
    }
  },
  emits: ['update:visible', 'success', 'cancel'],
  setup(props, { emit }) {
    const formRef = ref(null);
    const loading = ref(false);

    const initialFormData = () => ({
      id: null,
      name: '',
      description: ''
    });

    const formData = reactive(initialFormData());

    const rules = {
      name: [
        { required: true, message: '请输入猪舍名称', trigger: 'blur' }
      ]
    };

    const title = computed(() => (props.isEdit ? '编辑猪舍' : '添加猪舍'));

    const handleClose = () => {
      emit('update:visible', false);
      emit('cancel');
      Object.assign(formData, initialFormData());
      nextTick(() => {
        formRef.value?.resetFields();
      });
    };

    const handleSubmit = async () => {
      if (!formRef.value) return;
      await formRef.value.validate(async (valid) => {
        if (valid) {
          loading.value = true;
          try {
            const submitData = { name: formData.name, description: formData.description };
            let response;
            if (props.isEdit) {
              response = await updatePigHouse(formData.id, submitData);
            } else {
              response = await createPigHouse(submitData);
            }
            emit('success', response.data);
            handleClose();
          } catch (error) {
            ElMessage.error((props.isEdit ? '更新' : '创建') + '猪舍失败: ' + (error.message || '未知错误'));
          } finally {
            loading.value = false;
          }
        }
      });
    };

    watch(() => props.houseData, (newVal) => {
      Object.assign(formData, initialFormData());
      if (props.isEdit && newVal && newVal.id) {
        formData.id = newVal.id;
        formData.name = newVal.name;
        formData.description = newVal.description;
      }
    }, { immediate: true, deep: true });

    watch(() => props.visible, (newVal) => {
        if (newVal && !props.isEdit) {
            Object.assign(formData, initialFormData());
            nextTick(() => {
                formRef.value?.clearValidate();
            });
        }
    });

    return {
      formRef,
      loading,
      formData,
      rules,
      title,
      handleClose,
      handleSubmit
    };
  }
};
</script>

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