<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)"
  >
    <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.frontCompartNo" style="width: 120px" @change="handleRoomChange">
            <el-option
              v-for="cell in statusData"
              :key="cell.frontCompartNo"
              :label="`${cell.frontCompartNo}仓`"
              :value="cell.frontCompartNo"
            />
          </el-select>
        </div>
        <div class="input-group">
          <span>电磁阀分布数量：</span>
          <el-input-number
            v-model="valveForm.valveNum"
            :min="0"
            controls-position="right"
            style="width: 120px"
            :class="{ 'is-error': errorMessage }"
          />
        </div>
        <div class="input-group">
          <span>布袋数量：</span>
          <el-input-number
            v-model="valveForm.bagNum"
            :min="0"
            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.valveNum === null || valveForm.bagNum === null"
        >设置</el-button>
      </div>
    </div>

    <!-- 分布表格 -->
    <div class="bagNum-table">
      <div class="table-title">
        仓室脉冲阀数量分布
        <span class="valve-valveNum-info">
          (当前分配: {{ currentTotalValves }}/{{ valveForm.total }})
        </span>
      </div>
      <div class="valve-bagNum-grid">
        <div class="valve-row">
          <div
            v-for="(cell, colIndex) in statusData"
            :key="colIndex"
            class="valve-cell"
            :class="{ 'active-cell': cell.frontCompartNo === valveForm.frontCompartNo }"
            @click="valveForm.frontCompartNo = cell.frontCompartNo; handleRoomChange(cell.frontCompartNo)"
          >
            <div class="cell-index">{{ cell.frontCompartNo }}仓</div>
            <div class="cell-value">{{ cell.valveNum }} <span>({{ cell.bagNum }})</span></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";
import { getValveAllocation } from "@/request/api/dustOverview";

const props = defineProps({
  modelValue: Boolean,
  data: {
    type: Object,
    default: () => []
  }
});

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

const valveForm = ref({
  total: 0,
  rows: 0,
  frontCompartNo: 0,
  valveNum: 0,
  bagNum: 0
});

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

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

// 计算当前修改后的总数量
const projectedTotalValves = computed(() => {
  // 找到当前修改的仓室
  const selectedRoom = statusData.value.find(cell => cell.frontCompartNo === valveForm.value.frontCompartNo);
  if (!selectedRoom) return currentTotalValves.value;
  
  // 计算替换后的总数
  const diff = valveForm.value.valveNum - selectedRoom.valveNum;
  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.data.valveNum;
    getAllocation({
      customerId: props.data.customerId,
      dusterNo: props.data.deviceNo
    });
    // valveForm.value.total = props.totalValves;
    // statusData.value = [...props.statusData]; // 深拷贝状态数据
    // errorMessage.value = "";
    
    // // 如果有数据，默认选中第一个仓室
    // if (statusData.value.length > 0) {
    //   valveForm.value.frontCompartNo = statusData.value[0].index;
    //   valveForm.value.valveNum = statusData.value[0].valveNum;
    //   valveForm.value.bagNum = statusData.value[0].valveNum; // 默认布阀数量等于电磁阀数量
    // }
  }
};

const getAllocation = (params) => {
  getValveAllocation(params).then(res => {
    if (res.code === 1 && res.data.valveList.length > 0) {
      statusData.value = res.data.valveList;
      valveForm.value.frontCompartNo = statusData.value[0].frontCompartNo;
      valveForm.value.valveNum = statusData.value[0].valveNum;
      valveForm.value.bagNum = statusData.value[0].bagNum;
    }
  })
}

// getToken("customerId"),

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

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

// 监听阀门数量变化，实时验证
watch(() => valveForm.value.valveNum, () => {
  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.valveNum = baseValue + (index < remainder ? 1 : 0);
  });
  
  // 更新当前选中仓室的值
  handleRoomChange(valveForm.value.frontCompartNo);
  errorMessage.value = ""; // 重置错误信息
};

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

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

const handleConfirm = () => {
  // 最终确认时再次验证总数是否符合要求
  console.log(statusData.value);
  const totalValves = statusData.value.reduce((sum, cell) => sum + cell.valveNum, 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;
  }
}

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

.valve-bagNum-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 8px;
    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 {
      display: flex;
      justify-content: center;
      align-items: end;
      font-size: 16px;
      color: #606266;
      span {
        font-size: 12px;
        line-height: 18px;
        color: #909399;
        margin-left: 2px;
      }
    }
  }
}

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