<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="0"
          :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
        :resizable="false"
      >
        <el-table-column prop="compartPositionRow" label="排" width="180">
          <template #default="{ row }">
            <span>第{{ row.compartPositionRow }}排</span>
          </template>
        </el-table-column>
        <el-table-column prop="compartPositionColumnNum" label="仓数量">
          <template #default="{ row }">
            <el-input-number
              v-model="row.compartPositionColumnNum"
              :min="1"
              :max="1000"
              controls-position="right"
              size="small"
              @change="handleDistributionChange"
            />
          </template>
        </el-table-column>
      </el-table>
    </div>

    <template #footer>
      <span class="dialog-footer all-select-btn">
        <el-button @click="$emit('update:modelValue', false)" class="cancel-btn-balck-theme">取消</el-button>
        <el-button
          type="default"
          class="search-btn-balck-theme"
          @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,
  data: {
    type: Object,
    default: () => {},
  },
});

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

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

const distributionData = ref([]);

const initializeState = () => {
  if (props.data.deviceNo) {
    const { compartNum, compartRowNum, compartHealthList } = props.data;
    roomForm.value.totalRooms = compartNum || 0;
    roomForm.value.rows = compartRowNum || 0;

    if (compartHealthList && compartHealthList.length > 0) {
      roomForm.value.rows = compartHealthList.length;
      distributionData.value = compartHealthList.map((row, index) => ({
        compartPositionRow: index + 1,
        compartPositionColumnNum: row.length,
      }));
    } else {
      roomForm.value.rows = 0;
      distributionData.value = [];
    }
  }
};

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

const distributionDiff = computed(() => {
  const total = distributionData.value.reduce(
    (sum, item) => sum + item.compartPositionColumnNum,
    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 {
      compartPositionRow: index + 1,
      compartPositionColumnNum: index < remainder ? baseValue + 1 : baseValue,
    };
  });
};

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

const handleConfirm = () => {
  if (distributionDiff.value <= 0) {
    const { deviceNo, compartNum } = props.data;
    emit("confirm", {
      compartNum,
      dusterNo: deviceNo,
      compartRowNum: roomForm.value.rows,
      detailList: 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 rgb(51, 50, 50);
  padding-top: 20px;
}

.table-title {
  font-size: 14px;
  color: var(--success);
  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>
