<template>
  <el-dialog
    title="群内调栏"
    :model-value="visible"
    @update:model-value="$emit('update:visible', $event)"
    width="500px"
    :before-close="handleClose"
  >
    <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
      <el-form-item label="调出猪栏" prop="fromPenID">
        <el-select v-model="form.fromPenID" placeholder="请选择调出猪栏" style="width: 100%;" @change="handleFromPenChange">
          <el-option
            v-for="pen in sourcePens"
            :key="pen.id"
            :label="`${pen.pen_number} (存栏: ${pen.current_pig_count})`"
            :value="pen.id"
            :disabled="pen.current_pig_count === 0"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="调入猪栏" prop="toPenID">
        <el-select v-model="form.toPenID" placeholder="请选择调入猪栏" style="width: 100%;" :disabled="!form.fromPenID">
          <el-option
            v-for="pen in destinationPens"
            :key="pen.id"
            :label="`${pen.pen_number} (存栏: ${pen.current_pig_count})`"
            :value="pen.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="调栏数量" prop="quantity">
        <el-input-number
          v-model="form.quantity"
          :min="1"
          :max="maxQuantity"
          :disabled="!form.fromPenID"
          placeholder="请输入数量"
          style="width: 100%;"
        />
      </el-form-item>
      <el-form-item label="备注" prop="remarks">
        <el-input v-model="form.remarks" 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 { transferPigsWithinBatch } from '@/api/pigBatch.js';

export default {
  name: 'TransferPigsModal',
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    batch: {
      type: Object,
      required: true,
    },
  },
  emits: ['update:visible', 'success'],
  data() {
    return {
      loading: false,
      form: {
        fromPenID: null,
        toPenID: null,
        quantity: 1,
        remarks: '',
      },
      rules: {
        fromPenID: [{ required: true, message: '请选择调出猪栏', trigger: 'change' }],
        toPenID: [{ required: true, message: '请选择调入猪栏', trigger: 'change' }],
        quantity: [{ required: true, message: '请输入调栏数量', trigger: 'blur' }],
      },
    };
  },
  computed: {
    sourcePens() {
      return this.batch.pens || [];
    },
    destinationPens() {
      if (!this.form.fromPenID) return [];
      return this.batch.pens.filter(pen => pen.id !== this.form.fromPenID);
    },
    maxQuantity() {
      if (!this.form.fromPenID) return 1;
      const selectedPen = this.sourcePens.find(p => p.id === this.form.fromPenID);
      return selectedPen ? selectedPen.current_pig_count : 1;
    },
  },
  watch: {
    visible(newVal) {
      if (newVal) {
        this.resetForm();
      }
    },
  },
  methods: {
    handleFromPenChange(penId) {
      this.form.toPenID = null;
      this.form.quantity = 1;
      const selectedPen = this.sourcePens.find(p => p.id === penId);
      if (selectedPen && selectedPen.current_pig_count === 0) {
        this.$message.warning('该猪栏没有猪，无法调出。');
        this.form.fromPenID = null;
      }
    },
    handleSubmit() {
      this.$refs.formRef.validate(async (valid) => {
        if (valid) {
          if (this.form.quantity > this.maxQuantity) {
            this.$message.error('调栏数量不能超过当前存栏量');
            return;
          }
          this.loading = true;
          try {
            await transferPigsWithinBatch(this.batch.id, this.form);
            this.$message.success('调栏成功');
            this.$emit('success');
            this.handleClose();
          } catch (error) {
            this.$message.error('调栏失败: ' + (error.response?.data?.message || error.message));
            console.error('Failed to transfer pigs:', error);
          } finally {
            this.loading = false;
          }
        }
      });
    },
    handleClose() {
      this.$emit('update:visible', false);
    },
    resetForm() {
      if (this.$refs.formRef) {
        this.$refs.formRef.resetFields();
      }
      this.form = {
        fromPenID: null,
        toPenID: null,
        quantity: 1,
        remarks: '',
      };
    },
  },
};
</script>

<style scoped>
.dialog-footer {
  text-align: right;
}
</style>
