<template>
  <div class="pig-batch-list">
    <div v-for="batch in pigBatches" :key="batch.id" class="pig-batch-item">
      <div class="batch-header" @click="toggleExpand(batch)">
        <div class="batch-info">
          <div class="batch-info-line">
            <span>批次编号: {{ batch.batch_number }}</span>
            <span>状态: {{ batch.status }}</span>
            <span>初始数量: {{ batch.initial_count }}</span>
            <span v-if="batch.currentTotalQuantity !== undefined && batch.currentTotalQuantity !== null">当前总数: {{
                batch.currentTotalQuantity
              }}</span>
            <span v-if="batch.origin_type">批次来源: {{ batch.origin_type }}</span>
          </div>
          <div class="batch-info-line">
            <span v-if="batch.start_date">批次开始日期: {{ formatRFC3339(batch.start_date) }}</span>
            <span v-if="batch.end_date">
              批次结束日期:
              <template v-if="formatRFC3339(batch.end_date) === '0001-01-01 08:00:00'">
                正在饲养中
              </template>
              <template v-else>
                {{ formatRFC3339(batch.end_date) }}
              </template>
            </span>
            <span v-if="batch.unassigned_pig_count !== undefined && batch.unassigned_pig_count > 0" class="red-text">
              未分配数量: {{ batch.unassigned_pig_count }}
            </span>
          </div>
        </div>
        <div class="batch-actions">
          <el-button size="small" type="primary" @click.stop="showAddPenDialog(batch)" :disabled="!batch.is_active">
            增加猪栏
          </el-button>
          <el-button
            size="small"
            type="success"
            @click.stop="emitTransferPigs(batch)"
            :disabled="!batch.is_active || !batch.pens || batch.pens.length < 2"
            title="将猪从一个猪栏转移到同一批次的另一个猪栏"
          >
            群内调栏
          </el-button>
          <el-button size="small" @click.stop="emitEditBatch(batch)">编辑</el-button>
          <el-button size="small" type="danger" @click.stop="emitDeleteBatch(batch)">删除</el-button>
        </div>
      </div>
      <div v-if="batch.isExpanded" class="batch-content">
        <div v-if="batch.pens && batch.pens.length > 0" class="pig-pen-list">
          <PigBatchPenCard
              v-for="pen in batch.pens"
              :key="pen.id"
              :pen="pen"
              :isBatchActive="batch.is_active"
              @allocate-pigs="showAllocatePigsDialog($event, batch)"
              @remove="emitRemovePen"
          />
        </div>
        <div v-else class="no-pens-message">
          <p>该猪群下没有猪栏信息。</p>
        </div>
      </div>
    </div>

    <!-- 增加猪栏对话框 -->
    <el-dialog title="选择猪栏" v-model="addPenDialogVisible" width="30%">
      <el-select v-model="selectedPenId" placeholder="请选择猪栏" style="width: 100%;">
        <el-option
            v-for="pen in availablePens"
            :key="pen.id"
            :label="pen.label"
            :value="pen.id">
        </el-option>
      </el-select>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addPenDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="assignPen">确 定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 分配猪只对话框 -->
    <AllocatePigsDialog
        v-if="allocatePigsDialogVisible"
        :visible.sync="allocatePigsDialogVisible"
        :unassigned-pig-count="currentBatch ? currentBatch.unassigned_pig_count : 0"
        :pen-id="selectedPenForAllocation ? selectedPenForAllocation.id : 0"
        @confirm="handleAllocatePigs"
    />
  </div>
</template>

<script>
import PigBatchPenCard from './PigBatchPenCard.vue';
import AllocatePigsDialog from './AllocatePigsDialog.vue';
import {getAllPens, getAllPigHouses, movePigsIntoPen} from '../api/pigBatch';
import {formatRFC3339} from '../utils/format'; // 导入格式化函数

export default {
  name: 'PigBatchList',
  components: {
    PigBatchPenCard,
    AllocatePigsDialog
  },
  props: {
    pigBatches: {
      type: Array,
      required: true
    }
  },
  emits: ['edit-batch', 'delete-batch', 'add-pen', 'remove-pen', 'assign-pen-to-batch', 'reload-data', 'transfer-pigs'],
  data() {
    return {
      addPenDialogVisible: false,
      availablePens: [],
      selectedPenId: null,
      currentBatch: null, // To store the batch for which we are adding a pen
      allocatePigsDialogVisible: false,
      selectedPenForAllocation: null
    };
  },
  methods: {
    formatRFC3339,
    toggleExpand(batch) {
      batch.isExpanded = !batch.isExpanded;
    },
    async fetchAvailablePens() {
      try {
        const [pensResponse, housesResponse] = await Promise.all([
          getAllPens(),
          getAllPigHouses()
        ]);

        const pens = pensResponse.data;
        const houses = housesResponse.data;

        // Create a map for quick lookup of house names by ID
        const houseMap = new Map(houses.map(house => [house.id, house.name]));

        // Filter for pens that are not assigned to any batch
        const unassignedPens = pens.filter(pen => !pen.pig_batch_id);

        this.availablePens = unassignedPens.map(pen => ({
          id: pen.id,
          label: `${pen.pen_number} (${houseMap.get(pen.house_id) || '未知猪舍'})`
        }));
      } catch (error) {
        console.error("Error fetching pens or houses:", error);
        this.$message.error("获取猪栏或猪舍信息失败");
      }
    },
    showAddPenDialog(batch) {
      this.currentBatch = batch;
      this.selectedPenId = null; // Reset selection
      this.fetchAvailablePens();
      this.addPenDialogVisible = true;
    },
    assignPen() {
      if (this.selectedPenId && this.currentBatch) {
        this.$emit('assign-pen-to-batch', {
          batchId: this.currentBatch.id,
          penId: this.selectedPenId
        });
        this.addPenDialogVisible = false;
      } else {
        this.$message.warning("请选择一个猪栏");
      }
    },
    showAllocatePigsDialog(pen, batch) {
      this.currentBatch = batch;
      this.selectedPenForAllocation = pen;
      this.allocatePigsDialogVisible = true;
    },
    async handleAllocatePigs({penId, quantity}) {
      try {
        await movePigsIntoPen(this.currentBatch.id, {toPenID: penId, quantity});
        this.$message.success('猪只分配成功');
        this.allocatePigsDialogVisible = false;
        this.$emit('reload-data'); // 通知父组件重新加载数据
      } catch (error) {
        console.error('Error allocating pigs:', error);
        this.$message.error('分配猪只失败');
      }
    },
    // 猪群操作
    emitEditBatch(batch) {
      this.$emit('edit-batch', batch);
    },
    emitDeleteBatch(batch) {
      this.$emit('delete-batch', batch);
    },
    emitTransferPigs(batch) {
      this.$emit('transfer-pigs', batch);
    },
    // 猪栏操作
    emitRemovePen(pen) {
      this.$emit('remove-pen', pen);
    }
  }
}
</script>

<style scoped>
.pig-batch-list {
  width: 100%;
}

.pig-batch-item {
  border: 1px solid #eee;
  border-radius: 4px;
  margin-bottom: 16px;
  overflow: hidden;
}

.batch-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  cursor: pointer;
  background-color: #f9f9f9;
  transition: background-color 0.3s;
}

.batch-header:hover {
  background-color: #f0f0f0;
}

.batch-info {
  display: flex;
  flex-direction: column; /* 垂直堆叠子元素 */
  gap: 8px; /* 行间距 */
}

.batch-info-line {
  display: flex;
  flex-wrap: wrap;
  gap: 0 20px; /* 列间距 */
}

.batch-info-line:first-child span:first-child {
  font-weight: bold;
}

.batch-info span {
  font-size: 14px;
  color: #606266;
}

.batch-actions {
  display: flex;
  gap: 10px;
}

.batch-content {
  padding: 16px;
  border-top: 1px solid #eee;
}

.pig-pen-list {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
}

.no-pens-message {
  color: #909399;
  text-align: center;
  padding: 20px 0;
}

.batch-info-line .red-text {
  color: red !important;
}
</style>
