<template>
    <div class="col scroll-box" id="scrollBox" @scroll="(e)=>scrollHandle(e)">
        <div :style="{width: innerW}" id="scrollInnerTemplate"></div>
    </div>
</template>

<script>
export default {
  props: {
    targetBox: {
      type: String,
      required: true
    },
    targetWrap: {
      type: String,
      required: true
    }
  },
  data() {
    return {
        innerW:'0px',
        ratio:0,
        boxRatio:0
    };
  },
  methods: {
    createResizeObserver() {
      this.resizeObserver = new ResizeObserver(entries => {
        this.calcHandle()
      });
      this.resizeObserver.observe(document.querySelector(`#${this.targetBox}`));
      this.resizeObserver.observe(document.querySelector(`#${this.targetWrap}`));
    },
    destroyResizeObserver() {
      if (this.resizeObserver) {
        this.resizeObserver.disconnect();
      }
    },
    calcHandle(){
        const box = document.querySelector('#scrollBox')
        const tb = document.querySelector(`#${this.targetBox}`)
        const tw = document.querySelector(`#${this.targetWrap}`)
        const zoom = tw.style.zoom?tw.style.zoom:1
        if(box && tb && tw){
            this.ratio = (tw.offsetWidth*zoom)/tb.offsetWidth
            this.innerW = `${this.ratio * box.offsetWidth}px`
            this.boxRatio = tb.offsetWidth/box.offsetWidth
        }
    },
    scrollHandle(e){
      const box = document.querySelector('#scrollBox')
      const sl = box.scrollLeft*this.boxRatio
      this.$emit("scrollChange", sl);
    }
  },
  mounted() {
    this.createResizeObserver();
    
  },
  beforeDestroy() {
    this.destroyResizeObserver();
  }
};
</script>

<style>
.scroll-box{
    overflow-x: auto;
    overflow-y: hidden;
    height: 15px;
}
.scroll-box::-webkit-scrollbar {
  width: 6px;
  height: 6px;
}
.scroll-box::-webkit-scrollbar-thumb {
  background-color: #888;
  border-radius: 6px;
}

.scroll-box::-webkit-scrollbar-thumb:hover {
  background-color: #555;
}
.scroll-box::-webkit-scrollbar-track {
  background-color: #f1f1f1;
}
</style>
