<template>
  <el-dialog
    :model-value="modelValue"
    title="电磁阀数量设置"
    width="800px"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    @update:model-value="$emit('update:modelValue', $event)"
    @open="initializeState"
  >
    <div class="valve-setting">
      <div class="setting-row">
        <div class="input-group">
          <span>电磁阀总数量：</span>
          <el-input v-model="valveForm.total" style="width: 120px" disabled />
        </div>
        <el-button type="primary" @click="handleAverageDistribute"
          >平均分布生成</el-button
        >
      </div>
      <div class="table-title">仓室脉冲阀数量分布</div>
      <div class="setting-row">
        <div class="input-group">
          <span>仓室编号：</span>
          <el-select v-model="valveForm.roomNo" style="width: 120px" @change="handleRoomChange">
            <el-option
              v-for="cell in statusData"
              :key="cell.index"
              :label="`${cell.index}仓`"
              :value="cell.index"
            />
          </el-select>
        </div>
        <div class="input-group">
          <span>电磁阀分布数量：</span>
          <el-input-number
            v-model="valveForm.valveCount"
            :min="1"
            controls-position="right"
            style="width: 120px"
            :class="{ 'is-error': errorMessage }"
          />
        </div>
        <div class="input-group">
          <span>布阀数量：</span>
          <el-input-number
            v-model="valveForm.distribution"
            :min="1"
            controls-position="right"
            style="width: 120px"
          />
        </div>
      </div>
      
      <!-- 错误提示 -->
      <div v-if="errorMessage" class="error-message">
        <i class="el-icon-warning"></i>
        {{ errorMessage }}
      </div>
      
      <div>
        <el-button 
          type="primary" 
          class="save-btn" 
          @click="handleSave"
          :disabled="!!errorMessage || valveForm.valveCount === null || valveForm.distribution === null"
        >保存</el-button>
      </div>
    </div>

    <!-- 分布表格 -->
    <div class="distribution-table">
      <div class="table-title">
        仓室脉冲阀数量分布
        <span class="valve-count-info">
          (当前分配: {{ currentTotalValves }}/{{ valveForm.total }})
        </span>
      </div>
      <div class="valve-distribution-grid">
        <div class="valve-row">
          <div
            v-for="(cell, colIndex) in statusData"
            :key="colIndex"
            class="valve-cell"
            :class="{ 'active-cell': cell.index === valveForm.roomNo }"
            @click="valveForm.roomNo = cell.index; handleRoomChange(cell.index)"
          >
            <div class="cell-index">{{ cell.index }}仓</div>
            <div class="cell-value">{{ cell.count }}</div>
          </div>
        </div>
      </div>
    </div>

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

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

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

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

const valveForm = ref({
  total: 0,
  rows: 0,
  roomNo: 0,
  valveCount: 0,
  distribution: 0
});

const statusData = ref([]);
const errorMessage = ref("");

// 计算当前已分配的电磁阀总数量
const currentTotalValves = computed(() => {
  return statusData.value.reduce((sum, cell) => sum + cell.count, 0);
});

// 计算当前修改后的总数量
const projectedTotalValves = computed(() => {
  // 找到当前修改的仓室
  const selectedRoom = statusData.value.find(cell => cell.index === valveForm.value.roomNo);
  if (!selectedRoom) return currentTotalValves.value;
  
  // 计算替换后的总数
  const diff = valveForm.value.valveCount - selectedRoom.count;
  return currentTotalValves.value + diff;
});

// 验证是否超过总数限制
const validateValveCount = computed(() => {
  if (projectedTotalValves.value > valveForm.value.total) {
    return {
      valid: false,
      message: `超出电磁阀总数限制，当前配置后总数为 ${projectedTotalValves.value}，超出限制 ${projectedTotalValves.value - valveForm.value.total} 个`
    };
  }
  return { valid: true, message: "" };
});

const initializeState = () => {
  if (props.modelValue) {
    valveForm.value.total = props.totalValves;
    statusData.value = [...props.statusData]; // 深拷贝状态数据
    errorMessage.value = "";
    
    // 如果有数据，默认选中第一个仓室
    if (statusData.value.length > 0) {
      valveForm.value.roomNo = statusData.value[0].index;
      valveForm.value.valveCount = statusData.value[0].count;
      valveForm.value.distribution = statusData.value[0].count; // 默认布阀数量等于电磁阀数量
    }
  }
};

// 当选中的仓室改变时，更新电磁阀分布数量
const handleRoomChange = (roomIndex) => {
  const selectedRoom = statusData.value.find(cell => cell.index === roomIndex);
  if (selectedRoom) {
    valveForm.value.valveCount = selectedRoom.count;
    valveForm.value.distribution = selectedRoom.count;
    errorMessage.value = "";
  }
};

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

// 监听阀门数量变化，实时验证
watch(() => valveForm.value.valveCount, () => {
  const validation = validateValveCount.value;
  errorMessage.value = validation.valid ? "" : validation.message;
});

const handleAverageDistribute = () => {
  if (!statusData.value || statusData.value.length === 0) return;

  const total = Number(valveForm.value.total) || 0;
  const totalRooms = statusData.value.length;
  
  if (totalRooms === 0 || total === 0) return;

  // 计算基础平均值（向下取整）和余数
  const baseValue = Math.floor(total / totalRooms);
  const remainder = total % totalRooms;

  // 平均分配阀数量 多余的阀数量分配到前面的仓室
  statusData.value.forEach((cell, index) => {
    cell.count = baseValue + (index < remainder ? 1 : 0);
  });
  
  // 更新当前选中仓室的值
  handleRoomChange(valveForm.value.roomNo);
  errorMessage.value = ""; // 重置错误信息
};

const handleSave = () => {
  // 验证是否超出限制
  const validation = validateValveCount.value;
  console.log(valveForm.value.valveCount);
  if (!validation.valid) {
    errorMessage.value = validation.message;
    return;
  }

  // 保存当前选中仓室的电磁阀分布数量
  const selectedRoom = statusData.value.find(cell => cell.index === valveForm.value.roomNo);
  if (selectedRoom) {
    selectedRoom.count = valveForm.value.valveCount;
    
    // 更新错误信息
    errorMessage.value = "";
  }
};

const handleConfirm = () => {
  // 最终确认时再次验证总数是否符合要求
  const totalValves = statusData.value.reduce((sum, cell) => sum + cell.count, 0);
  if (totalValves > valveForm.value.total) {
    errorMessage.value = `电磁阀总数超出限制 ${totalValves - valveForm.value.total} 个，请调整后再提交`;
    return;
  }
  
  emit("confirm", statusData.value);
  emit("update:modelValue", false);
};
</script>

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

.valve-setting {
  .setting-row {
    display: flex;
    align-items: center;
    gap: 20px;
    margin-bottom: 20px;

    .input-group {
      display: flex;
      align-items: center;
      gap: 8px;

      span {
        white-space: nowrap;
        color: #606266;
      }
    }
  }
  .save-btn {
    display: block;
    width: 120px;
    margin: 0 auto;
  }
}

.error-message {
  color: #F56C6C;
  background-color: #FEF0F0;
  padding: 8px 16px;
  border-radius: 4px;
  margin: 10px 0;
  font-size: 14px;
  display: flex;
  align-items: center;
  
  i {
    margin-right: 8px;
    font-size: 16px;
  }
}

.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;
  
  .valve-count-info {
    font-size: 12px;
    color: #909399;
    margin-left: 8px;
  }
}

.valve-distribution-grid {
  display: flex;
  flex-direction: column;
  gap: 8px;
  padding: 12px;
  background: #f5f7fa;
  border-radius: 4px;

  .valve-row {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
  }

  .valve-cell {
    width: 41px;
    background: white;
    padding: 4px;
    border-radius: 4px;
    text-align: center;
    border: 1px solid #dcdfe6;
    transition: all 0.3s;
    cursor: pointer;
    
    &.active-cell {
      box-shadow: 0 0 10px 0 rgba(64, 158, 255, 0.8);
      transform: scale(1.05);
    }

    .cell-index {
      font-size: 12px;
      color: #909399;
      margin-bottom: 8px;
    }

    .cell-value {
      font-size: 14px;
      color: #606266;
    }
  }
}

:deep(.is-error) {
  .el-input__inner {
    border-color: #F56C6C;
  }
  
  .el-input-number__decrease,
  .el-input-number__increase {
    border-color: #F56C6C;
  }
}
</style> 