<template>
  <div class="detail-panel">
    <div v-for="(row, rowIndex) in processedData" :key="rowIndex" class="detail-row">
      <div
        v-for="(item, colIndex) in row"
        :key="colIndex"
        class="detail-col"
        :class="getColClass(item)"
        :style="{ width: getColWidth(item.span) }"
      >
        <!-- 每个列都有独立的边框 -->
        <div class="col-container">
          <!-- 左侧 Label -->
          <div class="detail-label">
            <el-tooltip
              :content="item.label"
              placement="top"
              :disabled="!isTextOverflow(item.label, 'label', `${rowIndex}-${colIndex}`)"
            >
              <span class="label-text">{{ item.label }}</span>
            </el-tooltip>
          </div>

          <!-- 右侧 Value -->
          <div class="detail-value">
            <el-tooltip
              :content="item.value"
              placement="top"
              :disabled="!isTextOverflow(item.value, 'value', `${rowIndex}-${colIndex}`)"
            >
              <span class="value-text">{{ item.value || '-' }}</span>
            </el-tooltip>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, nextTick, watch } from 'vue'

const props = defineProps({
  // 详情数据，支持两种格式：
  // 1. 一维数组: [{ label: '标签', value: '值', span: 8 }, ...]
  // 2. 二维数组: [[{ label: '标签1', value: '值1', span: 12 }, { label: '标签2', value: '值2', span: 12 }], ...]
  data: {
    type: [Array, Object],
    default: () => []
  },
  // 每行总span数（类似Element Plus的24分栏）
  rowSpan: {
    type: Number,
    default: 24
  },
  // 标签宽度，默认120px
  labelWidth: {
    type: String,
    default: '120px'
  },
  // 行高
  rowHeight: {
    type: String,
    default: '40px'
  },
  // 列间距
  colGap: {
    type: String,
    default: '16px'
  },
  // 是否显示列边框
  showColBorder: {
    type: Boolean,
    default: true
  }
})

// 处理数据，确保是二维数组格式
const processedData = computed(() => {
  if (!props.data || props.data.length === 0) return []

  // 如果已经是二维数组，直接返回
  if (Array.isArray(props.data[0]) && Array.isArray(props.data[0])) {
    return props.data
  }

  // 一维数组转换为二维数组
  const result = []
  let currentRow = []
  let currentSpan = 0

  props.data.forEach(item => {
    const span = item.span || Math.floor(props.rowSpan / 2) // 默认占一半

    if (currentSpan + span > props.rowSpan) {
      // 当前行已满，创建新行
      result.push([...currentRow])
      currentRow = [item]
      currentSpan = span
    } else {
      // 添加到当前行
      currentRow.push(item)
      currentSpan += span
    }
  })

  // 添加最后一行
  if (currentRow.length > 0) {
    result.push(currentRow)
  }

  return result
})

// 存储文本溢出状态
const overflowState = ref({})

// 检查文本是否溢出
const isTextOverflow = (text, type, key) => {
  if (!text) return false
  return overflowState.value[`${type}-${key}`] || false
}

// 获取列的宽度
const getColWidth = span => {
  const percentage = (span / props.rowSpan) * 100
  return `calc(${percentage}% - ${props.colGap})`
}

// 获取列的class
const getColClass = item => {
  const classes = []
  if (item.align) {
    classes.push(`align-${item.align}`)
  }
  return classes
}

// 检测文本溢出
const checkTextOverflow = () => {
  nextTick(() => {
    const labelElements = document.querySelectorAll('.label-text')
    const valueElements = document.querySelectorAll('.value-text')

    // 重置溢出状态
    overflowState.value = {}

    // 检测label溢出
    labelElements.forEach((el, index) => {
      const parentCol = el.closest('.detail-col')
      if (parentCol) {
        const rowIndex = Array.from(parentCol.parentNode.children).indexOf(parentCol)
        const colIndex = Array.from(parentCol.parentNode.parentNode.children).indexOf(
          parentCol.parentNode
        )
        const key = `${colIndex}-${rowIndex}`
        overflowState.value[`label-${key}`] = el.scrollWidth > el.clientWidth
      }
    })

    // 检测value溢出
    valueElements.forEach((el, index) => {
      const parentCol = el.closest('.detail-col')
      if (parentCol) {
        const rowIndex = Array.from(parentCol.parentNode.children).indexOf(parentCol)
        const colIndex = Array.from(parentCol.parentNode.parentNode.children).indexOf(
          parentCol.parentNode
        )
        const key = `${colIndex}-${rowIndex}`
        overflowState.value[`value-${key}`] = el.scrollWidth > el.clientWidth
      }
    })
  })
}

onMounted(() => {
  checkTextOverflow()
})

// 监听数据变化
watch(
  () => props.data,
  () => {
    nextTick(() => {
      checkTextOverflow()
    })
  },
  { deep: true }
)
</script>

<style lang="scss" scoped>
.detail-panel {
  /* border: 1px solid #dcdfe6; */
  border-radius: 4px;
  background-color: #fff;
}

.detail-row {
  display: flex;
  flex-wrap: wrap;
  min-height: v-bind(rowHeight);
  /* border-bottom: 1px solid #ebeef5; */
  gap: v-bind(colGap);
  padding: 0 calc(v-bind(colGap) / 2);

  &:last-child {
    border-bottom: none;
  }
}

.detail-col {
  display: flex;
  min-height: v-bind(rowHeight);

  // 对齐方式
  &.align-center {
    .detail-label,
    .detail-value {
      justify-content: center;
      text-align: center;
    }
  }

  &.align-right {
    .detail-label,
    .detail-value {
      justify-content: flex-end;
      text-align: right;
    }
  }
}

// 每个列的容器，添加独立边框
.col-container {
  display: flex;
  width: 100%;
  /* border: v-bind(showColBorder ? '1px solid #ebeef5' : 'none'); */
  border: 1px solid #ebeef5;
  border-radius: 4px;
  overflow: hidden;
  background-color: #fff;
  margin-bottom: 15px;

  // 鼠标悬停效果
  /* .detail-row:hover & {
    background-color: #f5f7fa;

    .detail-label {
      background-color: #e6f3ff;
    }
  } */
}

.detail-label {
  width: v-bind(labelWidth);
  min-width: v-bind(labelWidth);
  padding: 8px 12px;
  /* background-color: #f5f7fa; */
  border-right: 1px solid #ebeef5;
  display: flex;
  align-items: center;
  font-weight: 500;
  color: #606266;

  .label-text {
    display: block;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    width: 100%;
    font-size: 14px;
  }
}

.detail-value {
  flex: 1;
  padding: 8px 12px;
  display: flex;
  align-items: center;

  .value-text {
    display: block;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    width: 100%;
    color: #303133;
    font-size: 14px;
  }
}

// 响应式处理
@media (max-width: 768px) {
  .detail-col {
    width: 100% !important;
  }

  .col-container {
    border: 1px solid #ebeef5;
    margin-bottom: 8px;
  }
}
</style>
