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

const props = defineProps<{ layout?: string }>();
const isVertical = $computed(() => props.layout === "vertical");
const container: HTMLDivElement = $ref();
const state = reactive({ dragging: false, split: 50 });
const boundSplit = $computed(() => {
  const { split } = state;
  return split < 20 ? 20 : split > 80 ? 80 : split;
});

let startPosition = 0;
let startSplit = 0;
function dragStart(e: MouseEvent) {
  state.dragging = true;
  startPosition = isVertical ? e.pageY : e.pageX;
  startSplit = boundSplit;
}

function dragMove(e: MouseEvent) {
  if (state.dragging) {
    const position = isVertical ? e.pageY : e.pageX;
    const totalSize = isVertical
      ? container.offsetHeight
      : container.offsetWidth;
    const dp = position - startPosition;
    state.split = startSplit + ~~((dp / totalSize) * 100);
    // console.log({
    //   isVertical,
    //   totalSize,
    //   dp,
    //   split: state.split,
    // });
  }
}

function dragEnd() {
  state.dragging = false;
}
</script>

<template>
  <div
    ref="container"
    class="split-pane"
    :class="{
      dragging: state.dragging,
      vertical: isVertical,
    }"
    @mousemove="dragMove"
    @mouseup="dragEnd"
    @mouseleave="dragEnd"
  >
    <div
      class="left"
      :style="{ [isVertical ? 'height' : 'width']: boundSplit + '%' }"
    >
      <slot name="left" />
      <div class="dragger" @mousedown.prevent="dragStart" />
    </div>
    <div
      class="right"
      :style="{ [isVertical ? 'height' : 'width']: 100 - boundSplit + '%' }"
    >
      <slot name="right" />
    </div>
  </div>
</template>

<style scoped>
.split-pane {
  display: flex;
  /* 为了chrome58更改，上层需要是flex，这里的高度才能保证是100%的父容器高度 */
  /* height: 100%; */
  position: relative;
}
.split-pane.dragging {
  cursor: ew-resize;
}
.dragging .left,
.dragging .right {
  pointer-events: none;
}
.left,
.right {
  position: relative;
  height: 100%;
}
/* .left { */
/* border-right: 1px solid var(--border); */
/* overflow: auto; */
/* } */
.dragger {
  position: absolute;
  z-index: 3;
  top: 0;
  bottom: 0;
  right: -5px;
  width: 10px;
  cursor: ew-resize;
  background-color: #e1e1e1;
}
.toggler {
  display: none;
  z-index: 3;
  position: absolute;
  left: 50%;
  bottom: 20px;
  padding: 8px 12px;
  border-radius: 8px;
  transform: translateX(-50%);
  box-shadow: 0 3px 8px rgba(0, 0, 0, 0.25);
}
/* vertical */
.split-pane.vertical {
  display: block;
}
.split-pane.vertical.dragging {
  cursor: ns-resize;
}
.vertical .dragger {
  top: auto;
  height: 10px;
  width: 100%;
  left: 0;
  right: 0;
  bottom: -5px;
  cursor: ns-resize;
}
.vertical .left,
.vertical .right {
  width: 100%;
}
.vertical .left {
  border-right: none;
  /* border-bottom: 1px solid var(--border); */
}
/* .right {
  overflow: scroll;
  z-index: 1000;
} */
</style>
