import { computed, onBeforeMount, onMounted, onUnmounted, ref } from "vue";
import { debounce } from "@/utils/index";

export function useVModel(props, propsName, emit) {
  return computed({
    get() {
      return new Proxy(props[propsName], {
        get(target, key, receiver) {
          return Reflect.get(target, key, receiver);
        },
        set(target, key, val) {
          emit(`update:${propsName}`, { ...target, [key]: val });
          return true;
        },
      });
    },
    set(val) {
      emit(`update:${propsName}`, val);
    },
  })

}
// 全屏
export function useFullScreen() {
  const isFullScreen = ref(false)
  const toggleFullScreen = (domId: string) => {
    if (!isFullScreen.value) {
      requestFullScreen(domId);
    } else {
      exitFull();
    }
    isFullScreen.value = !isFullScreen.value;
  }
  //全屏
  const requestFullScreen = (el) => {
    const element: any = document.querySelector(`#${el}`);
    let win: any = window
    var requestMethod =
      element.requestFullScreen || //W3C
      element.webkitRequestFullScreen || //Chrome等
      element.mozRequestFullScreen || //FireFox
      element.msRequestFullScreen; //IE11

    if (requestMethod) {
      requestMethod.call(element);
    } else if ("ActiveXObject" in window) {
      //for Internet Explorer
      var wscript = win.ActiveXObject("WScript.Shell");
      if (wscript !== null) {
        wscript.SendKeys("{F11}");
      }
    }

  }
  //退出全屏
  const exitFull = () => {
    // 判断各种浏览
    let doc: any = document
    let win: any = window
    var exitMethod =
      doc.exitFullscreen || //W3C
      doc.mozCancelFullScreen || //Chrome等
      doc.webkitExitFullscreen; //FireFox
    if (exitMethod) {
      exitMethod.call(doc);
    } else if (typeof win.ActiveXObject !== "undefined") {
      var wscript = new win.ActiveXObject("WScript.Shell");
      if (wscript !== null) {
        wscript.SendKeys("{F11}");
      }
    }
  }
  const checkFull = () => {
    let doc: any = document
    //判断浏览器是否处于全屏状态 （需要考虑兼容问题）
    var flag = doc.mozFullScreen ||
      doc.fullScreen ||
      //谷歌浏览器及Webkit内核浏览器
      doc.webkitIsFullScreen ||
      doc.webkitRequestFullScreen ||
      doc.mozRequestFullScreen ||
      doc.msFullscreenEnabled
    if (flag === undefined) {
      isFullScreen.value = false
    }
    return flag;

  }

  const fullChange = () => {
    if (!checkFull() && isFullScreen.value) {
      isFullScreen.value = false;
    }
  }
  onMounted(() => {
    window.addEventListener('resize', fullChange)
  });
  onUnmounted(() => {
    window.removeEventListener('resize', fullChange)
  });
  return { isFullScreen, toggleFullScreen };
}

// 监听窗口大小
export function useResize(fn = () => { }) {
  const handleResize = debounce(fn, 200);
  onMounted(() => {
    window.addEventListener("resize", handleResize);
  });
  onUnmounted(() => {
    window.removeEventListener("resize", handleResize);
  });
}