/**
 * v-dialogDrag 弹窗拖拽
 * Copyright (c) 2019 ruoyi
 */

// 当前设备
const isDevice = localStorage.getItem('isDevice');

export default {
  bind(el, binding, vnode, oldVnode) {
    const value = binding.value;
    if (value == false) return;
    if (isDevice == 'PC') return;
    let initialTouchX = 0;
    let initialTouchY = 0;
    let initialLeft = 0;
    let initialTop = 0;

    el.addEventListener(
      'touchstart',
      (e) => {
        // e.preventDefault();
        e.stopPropagation();
        e.currentTarget.style.touchAction = 'none';
        const touch = e.touches[0];
        initialTouchX = touch.clientX;
        initialTouchY = touch.clientY;
        initialLeft = e.currentTarget.offsetLeft;
        initialTop = e.currentTarget.offsetTop;
      },
      false
    );
    el.addEventListener(
      'touchmove',
      function (e) {
        e.preventDefault();
        e.stopPropagation();
        const clientX = e.targetTouches[0].clientX;
        const clientY = e.targetTouches[0].clientY;
        // 限制拖拽范围
        const clientWidth = document.documentElement.clientWidth;
        const clientHeight = document.documentElement.clientHeight;

        // 计算边界限制
        const maxLeft = clientWidth - this.offsetWidth;
        const maxTop = clientHeight - this.offsetHeight;
        // 计算基于初始位置的移动量并应用边界限制
        const deltaX = clientX - initialTouchX;
        const deltaY = clientY - initialTouchY;
        const left = initialLeft + deltaX;
        const top = initialTop + deltaY;

        // 添加边界限制
        this.style.left = `${Math.max(0, Math.min(left, maxLeft))}px`;
        this.style.top = `${Math.max(0, Math.min(top, maxTop))}px`;
        localStorage.setItem(this.className, JSON.stringify([this.style.left, this.style.top]));
      },
      false
    );
    el.addEventListener('touchend', function (e) {}, false);
  },
};
