<template>
  <el-dialog
    :model-value="modelValue"
    title="仓室数量设置"
    width="500px"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    @update:model-value="$emit('update:modelValue', $event)"
    @open="initializeState"
  >
    <el-form :model="roomForm" label-width="120px">
      <el-form-item label="仓室数量">
        <el-input
          v-model="roomForm.totalRooms"
          controls-position="right"
          style="width: 150px"
          disabled
        />
      </el-form-item>
      <el-form-item label="仓室分几排">
        <el-input-number
          v-model="roomForm.rows"
          :min="1"
          :max="20"
          controls-position="right"
          @change="handleRowsChange"
        />
      </el-form-item>
    </el-form>

    <!-- 分布表格 -->
    <div class="distribution-table">
      <div class="table-title">
        仓室数量分布
        <div
          v-if="distributionDiff !== 0"
          :class="[
            'distribution-warning',
            distributionDiff > 0 ? 'warning-less' : 'warning-less',
          ]"
        >
          当前仓室总数{{ distributionDiff > 0 ? "大于" : "小于" }}默认仓室数量
          {{ Math.abs(distributionDiff) }} 个，请修改。
        </div>
      </div>
      <el-table
        :data="distributionData"
        style="width: 100%"
        size="small"
        border
      >
        <el-table-column prop="row" label="排" width="180" />
        <el-table-column prop="count" label="仓数量">
          <template #default="{ row }">
            <el-input-number
              v-model="row.count"
              :min="1"
              :max="50"
              controls-position="right"
              size="small"
              @change="handleDistributionChange"
            />
          </template>
        </el-table-column>
      </el-table>
    </div>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="$emit('update:modelValue', false)">取消</el-button>
        <el-button type="primary" @click="handleConfirm" :disabled="distributionDiff !== 0">
          确认
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, computed, watch } from "vue";

const props = defineProps({
  modelValue: Boolean,
  totalRooms: {
    type: Number,
    required: true
  },
  initialDistribution: {
    type: Array,
    default: () => []
  }
});

const emit = defineEmits(["update:modelValue", "confirm"]);

const roomForm = ref({
  totalRooms: 0,
  rows: 0
});

const distributionData = ref([]);

const initializeState = () => {
  if (props.modelValue) {
    roomForm.value.totalRooms = props.totalRooms;
    
    if (props.initialDistribution && props.initialDistribution.length > 0) {
      roomForm.value.rows = props.initialDistribution.length;
      distributionData.value = props.initialDistribution.map((row, index) => ({
        row: `第${index + 1}排`,
        count: row.length
      }));
    } else {
      roomForm.value.rows = 0;
      distributionData.value = [];
    }
  }
};

watch(() => props.modelValue, (newVal) => {
  if (newVal) {
    initializeState();
  }
}, { immediate: true });

const distributionDiff = computed(() => {
  const total = distributionData.value.reduce(
    (sum, item) => sum + item.count,
    0
  );
  return total - roomForm.value.totalRooms;
});

const handleRowsChange = (value) => {
  const total = roomForm.value.totalRooms;
  if (!total || !value) return;

  // 计算每行的基础数量（向下取整）和余数
  const baseValue = Math.floor(total / value);
  const remainder = total % value;

  // 生成分布数据
  distributionData.value = Array.from({ length: value }, (_, index) => {
    return {
      row: `第${index + 1}排`,
      count: index < remainder ? baseValue + 1 : baseValue
    };
  });
};

const handleDistributionChange = () => {
  // 分布数量变化时不需要特殊处理，distributionDiff会自动计算
};

const handleConfirm = () => {
  if (distributionDiff.value === 0) {
    emit("confirm", distributionData.value);
    emit("update:modelValue", false);
  }
};
</script>

<style lang="scss" scoped>
.dialog-footer {
  display: flex;
  justify-content: center;
  gap: 12px;
}

.distribution-table {
  margin-top: 20px;
  border-top: 1px solid #ebeef5;
  padding-top: 20px;
}

.table-title {
  font-size: 14px;
  color: #2182a0;
  margin-bottom: 16px;
  font-weight: 500;
}

.distribution-warning {
  display: inline-block;
  font-size: 13px;
  margin-left: 12px;
  padding: 1px 8px;
  box-sizing: border-box;
  border-radius: 4px;

  &.warning-more {
    color: #e6a23c;
    background-color: #fdf6ec;
  }

  &.warning-less {
    color: #f56c6c;
    background-color: #fef0f0;
  }
}

:deep(.el-input-number.el-input-number--small) {
  width: 130px;
}

:deep(.distribution-table .el-table--border .el-table__cell) {
  border-right: 1px solid #ebeef5 !important;
}
</style> 