<template>
  <div class="page-comp comp-drag-split">
    <div class="content" ref="containerRef" @mouseleave="stopDragFun">
      <div v-show="!hideLeft" class="left-box" :style="{ width: leftWidth + 'px' }">
        <slot name="left" />
      </div>
      <div v-show="!hideLeft" class="darg-line" @mousedown="startDragFun">||</div>
      <div class="right-box">
        <div class="right-content">
          <div class="slot">
            <slot name="right" />
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue';

interface Props {
  leftContentWidth: any;
  hideLeft?: boolean;
}

const props = withDefaults(defineProps<Props>(), {
  leftContentWidth: 0,
  hideLeft: false,
});

const leftWidth = ref(props.leftContentWidth); // 左侧初始宽度
const containerRef = ref<any>(null);
let isDragging = false;

// 开始拖拽
const startDragFun = () => {
  isDragging = true;
  document.addEventListener('mousemove', dragFun);
  document.addEventListener('mouseup', stopDragFun);
};

// 拖拽中
const dragFun = (e: any) => {
  if (!isDragging || !containerRef.value) return;
  const containerRect = containerRef.value.getBoundingClientRect();
  let newLeftWidth = e.clientX - containerRect.left;
  const minPaneWidth = 50; // 最小宽度
  const maxLeftWidth = containerRect.width - minPaneWidth - 10; // 拖拽区域宽度
  newLeftWidth = Math.max(minPaneWidth, Math.min(newLeftWidth, maxLeftWidth));
  leftWidth.value = newLeftWidth;
};

// 停止拖拽
const stopDragFun = () => {
  isDragging = false;
  document.removeEventListener('mousemove', dragFun);
  document.removeEventListener('mouseup', stopDragFun);
};
</script>

<style lang="scss" scoped>
.comp-drag-split {
  width: 100%;
  height: 100%;
  .content {
    display: flex;
    width: 100%;
    height: 100%;
  }
  .left-box {
    overflow-y: auto;
  }
  .right-box {
    flex: 1;
    height: 100%;
    .right-content {
      display: flex;
      height: 100%;
      .slot {
        flex: 1;
        width: 0;
      }
    }
  }
  .darg-line {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 10px;
    background-color: var(--el-bg-color-page);
    color: var(--el-text-color-secondary);
    font-weight: bold;
    user-select: none;
    cursor: w-resize;
    &:hover {
      background-color: var(--el-border-color);
    }
  }
}
</style>
