import {
  toolOpen,
  whitePenShow,
  penShow,
  isPlay,
  isHidden
} from './globalTools';
import { defineComponent, onMounted, onUnmounted, ref, watch } from 'vue';
import { useRoute } from 'vue-router';
import styles from './index.module.less';
import iconTool from './images/icon-tool.png';
import iconNote from './images/icon-note.png';
import iconWhiteboard from './images/icon-whiteboard.png';
import gArrowRight from './images/g-arrow-right.png';
import { nextTick } from 'process';
import { useNetwork } from '@vueuse/core';
import { showToast } from 'vant';
import Pen from '@/views/coursewarePlay/component/tools/pen';

export default defineComponent({
  name: 'globalTools',
  setup() {
    const { isOnline } = useNetwork()
    const isMask = ref(false); // 是否显示遮罩层，为了处理云教练里面拖动不了的问题
    const route = useRoute();
    // watch(
    //   () => route.path,
    //   () => {
    //     handleStatus();
    //   }
    // );
    const iconToolsDom = ref<HTMLDivElement>();
    const expendToolsDom = ref<HTMLDivElement>();

    function openTool() {
      if (isLock) return;
      isPlay.value = false
      toolOpen.value = !toolOpen.value;
    }

    function openType(type: 'note' | 'whiteboard') {
      if (isLock) return;
      console.log(isOnline.value, 'isOnline.value')
      if(!isOnline.value) {
        showToast('网络异常')
        return
      }
      if (type === 'note') {
        penShow.value = true;

        isHidden.value = true;
      } else if (type === 'whiteboard') {
        whitePenShow.value = true;
        isHidden.value = true;
      }
    }

    function handleStatus() {
      isHidden.value = route.path === '/login' ? true : false;
    }

    function computePos(type: 'width' | 'height', value: number) {
      const clientNum =
        type == 'width'
          ? document.documentElement.clientWidth
          : document.documentElement.clientHeight;
      return {
        pos: ((clientNum - value) / 2).toFixed(5)
      };
    }

    /* 拖拽还没有兼容rem */
    let isLock = false;
    let toolMoveY = 0; // 移动的距离
    function drag(el: HTMLElement) {
      function mousedown(e: MouseEvent | TouchEvent) {
        const isTouchEv = isTouchEvent(e);
        const event = isTouchEv ? e.touches[0] : e;
        isLock = false;
        isMask.value = true;
        const parentElement = el;
        const parentElementRect = parentElement.getBoundingClientRect();
        const downX = event.clientX;
        const downY = event.clientY;
        // const clientWidth = document.documentElement.clientWidth
        const clientHeight = document.documentElement.clientHeight;
        // const minLeft = 0
        const minTop = 0;
        // const maxLeft = clientWidth - parentElementRect.width
        const maxTop = clientHeight - parentElementRect.height;
        function onMousemove(e: MouseEvent | TouchEvent) {
          const event = isTouchEvent(e) ? e.touches[0] : e;
          // let moveX = parentElementRect.left + (e.clientX - downX)
          let moveY = parentElementRect.top + (event.clientY - downY);
          // let moveY = e.clientY - downY
          // moveX = moveX < minLeft ? minLeft : moveX > maxLeft ? maxLeft : moveX
          moveY = moveY < minTop ? minTop : moveY > maxTop ? maxTop : moveY;
          toolMoveY = moveY;
          document.documentElement.style.setProperty(
            '--toolTranslateY',
            `${moveY}px`
          );

          // 计算移动的距离
          const cX = event.clientX - downX;
          const cY = event.clientY - downY;

          // 如果移动距离超过一定阈值，则认为是拖动
          if (Math.abs(cX) > 3 || Math.abs(cY) > 3) {
            isLock = true; // 设置为拖动状态
          }
        }
        function onMouseup() {
          document.removeEventListener(
            isTouchEv ? 'touchmove' : 'mousemove',
            onMousemove
          );
          document.removeEventListener(
            isTouchEv ? 'touchend' : 'mouseup',
            onMouseup
          );
          isMask.value = false;
        }
        document.addEventListener(
          isTouchEv ? 'touchmove' : 'mousemove',
          onMousemove
        );
        document.addEventListener(
          isTouchEv ? 'touchend' : 'mouseup',
          onMouseup
        );
      }
      el.addEventListener('mousedown', mousedown);
      el.addEventListener('touchstart', mousedown);
    }
    function isTouchEvent(e: MouseEvent | TouchEvent): e is TouchEvent {
      return window.TouchEvent && e instanceof window.TouchEvent;
    }
    //重新计算位置 居中
    function refreshPos() {
      // computePos("height", iconToolsDom.value?.clientHeight ||
      // console.log(iconToolsDom.value?.clientHeight);
      const posHeight = computePos(
        'height',
        iconToolsDom.value?.clientHeight || 0
      );
      if (iconToolsDom.value) {
        document.documentElement.style.setProperty(
          '--toolTranslateY',
          `${posHeight.pos}px`
        );
      }
    }
    let rect: any;
    function onResize() {
      rect = rect ? rect : iconToolsDom.value?.getBoundingClientRect();
      const clientHeight = document.documentElement.clientHeight;
      const maxTop = clientHeight - rect.height;
      if (toolMoveY >= maxTop) {
        document.documentElement.style.setProperty(
          '--toolTranslateY',
          `${maxTop}px`
        );
      }
    }
    onMounted(() => {
      handleStatus();
      drag(iconToolsDom.value!);
      drag(expendToolsDom.value!);
      nextTick(() => {
        refreshPos();
      })
      window.addEventListener('resize', onResize);
    });

    onUnmounted(() => {
      window.removeEventListener('resize', onResize);
    });
    return () => (
      <div>
        <div
          class={[
            styles.globalTools,
            isPlay.value ? styles.isPlay : '',
            isHidden.value ? styles.isHidden : ''
          ]}>
          {isMask.value && <div class={styles.mask}></div>}

          <div
            class={[[styles.iconTools, toolOpen.value ? styles.hideTools : '']]}
            ref={iconToolsDom}>
            <img onClick={openTool} src={iconTool} />
          </div>
          <div
            class={[styles.expendTools, toolOpen.value ? styles.showTools : '']}
            ref={expendToolsDom}>
            <img onClick={() => openType('note')} src={iconNote} />
            <img
              onClick={() => openType('whiteboard')}
              class={styles.iconWhiteboard}
              src={iconWhiteboard}
            />
            <img
              onClick={openTool}
              class={styles.iconArrow}
              src={gArrowRight}
            />
          </div>
        </div>
        <Pen
          show={penShow.value}
          tip="请确认是否退出批注？"
          close={() => {
            penShow.value = false;
            isHidden.value = false;
          }}
        />
        <Pen
          show={whitePenShow.value}
          isWhite
          tip="请确认是否退出白板？"
          close={() => {
            whitePenShow.value = false;
            isHidden.value = false;
          }}
        />
      </div>
    );
  }
});
