import { _debounce } from '@/utils/index';
const oft = 0; // 楼层偏移量
let DEBOUNCE_FN = () => {}; // 存放防抖scroll fn

export default {
  data() {
    return {
      floorScrollType: '', // 滚动类型  target：指定  ''自行滚动
    };
  },
  methods: {
    // 去往指定楼层
    toFloor({ targetId }) {
      this.floorScrollType = 'target';
      document.querySelector('main.main').scrollTo({
        top: document.getElementById(targetId).offsetTop - document.documentElement.scrollTop,
        behavior: 'smooth'
      });
      this.floorId = targetId;
      setTimeout(() => {
        this.floorScrollType = '';
      }, 1500);
    },
    // 楼层滚动
    handleScroll() {
      // console.log(this.floorScrollType);
      if(this.floorScrollType) {
        return;
      }
      const bodyTop = (document.documentElement.scrollTop || document.body.scrollTop) + (this.oft != undefined ? this.oft : oft);
      const arr = this.floor.map(v => {
        let offsetTop = document.getElementById(v.targetId).offsetTop;
        return { targetId: v.targetId, offsetTop };
      });
      // 找寻floorId
      let floorId = '';
      arr.forEach((v, idx) => {
        if (idx === 0) {
          // 第一个
          if (bodyTop < arr[idx + 1].offsetTop) {
            floorId = arr[idx].targetId;
          }
        } else if (idx === arr.length - 1) {
          // 最后一个
          if (bodyTop >= v.offsetTop) {
            floorId = v.targetId;
          }
        } else {
          if (bodyTop >= v.offsetTop && bodyTop < arr[idx + 1].offsetTop) {
            floorId = v.targetId;
          }
        }
      });
      this.floorId = floorId;
    },
  },
  mounted() {
    this.handleScroll();
    DEBOUNCE_FN = _debounce(this.handleScroll, 200);
    window.addEventListener('scroll', DEBOUNCE_FN);
  },
  destroyed() {
    window.removeEventListener('scroll', DEBOUNCE_FN);
  }
};