<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="pen_number">
        <el-input v-model="formData.pen_number" placeholder="例如：A01-01" />
      </el-form-item>
      <el-form-item label="容量" prop="capacity">
        <el-input-number v-model="formData.capacity" :min="1" controls-position="right" style="width: 100%" />
      </el-form-item>
      <el-form-item v-if="isEdit" label="状态" prop="status">
        <el-select v-model="formData.status" placeholder="请选择状态" style="width: 100%">
          <el-option v-for="item in penStatusOptions" :key="item" :label="item" :value="item" />
        </el-select>
      </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 { createPen, updatePen } from '@/api/pen.js';

export default {
  name: 'PenForm',
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    penData: {
      type: Object,
      required: true
    },
    isEdit: {
      type: Boolean,
      default: false
    }
  },
  emits: ['update:visible', 'success', 'cancel'],
  setup(props, { emit }) {
    const formRef = ref(null);
    const loading = ref(false);
    const penStatusOptions = ["空闲", "使用中", "病猪栏", "康复栏", "清洗消毒", "维修中"];

    const initialFormData = () => ({
      id: null,
      pen_number: '',
      capacity: 10,
      status: '空闲',
      house_id: null
    });

    const formData = reactive(initialFormData());

    const rules = {
      pen_number: [
        { required: true, message: '请输入猪栏编号', trigger: 'blur' }
      ],
      capacity: [
        { required: true, message: '请输入容量', trigger: 'blur' },
        { type: 'integer', min: 1, message: '容量必须是大于0的整数', trigger: 'blur' }
      ],
      status: [
        { required: true, message: '请选择状态', trigger: 'change' }
      ]
    };

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

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

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

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

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

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