<template>
  <el-dialog
    title="分配猪只"
    :model-value="visible"
    @update:model-value="$emit('update:visible', $event)"
    width="30%"
    @close="resetForm"
  >
    <el-form ref="form" :model="form" :rules="rules" label-width="100px">
      <el-form-item label="未分配数量">
        <span>{{ unassignedPigCount }}</span>
      </el-form-item>
      <el-form-item label="分配数量" prop="quantity">
        <el-input-number v-model="form.quantity" :min="1" :max="unassignedPigCount" />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="$emit('update:visible', false)">取 消</el-button>
        <el-button type="primary" @click="handleConfirm">确 定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script>
export default {
  name: 'AllocatePigsDialog',
  props: {
    visible: {
      type: Boolean,
      required: true
    },
    unassignedPigCount: {
      type: Number,
      required: true
    },
    penId: {
      type: Number,
      required: true
    }
  },
  emits: ['update:visible', 'confirm'],
  data() {
    return {
      form: {
        quantity: 1
      },
      rules: {
        quantity: [
          { required: true, message: '请输入分配数量', trigger: 'blur' },
          { type: 'integer', message: '请输入整数', trigger: 'blur' },
          { validator: this.validateQuantity, trigger: 'blur' }
        ]
      }
    };
  },
  methods: {
    validateQuantity(rule, value, callback) {
      if (value > this.unassignedPigCount) {
        callback(new Error('分配数量不能超过未分配数量'));
      } else {
        callback();
      }
    },
    handleConfirm() {
      this.$refs.form.validate(valid => {
        if (valid) {
          this.$emit('confirm', { penId: this.penId, quantity: this.form.quantity });
          this.$emit('update:visible', false);
        }
      });
    },
    resetForm() {
      this.$refs.form.resetFields();
      this.form.quantity = 1;
    }
  }
};
</script>
