/*
 * @Author: your name
 * @Date: 2021-05-31 11:35:48
 * @LastEditTime: 2021-06-01 14:59:00
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \precise_delivery_distribution_front\src\hooks\useWatermark.ts
 */
import { getCurrentInstance, onBeforeUnmount, ref, Ref, unref } from "vue";
import store from "@/store";

const domSymbol = Symbol("watermark-dom");

export function useWatermark(
  appendEl: Ref<HTMLElement | null> = ref(document.body)
) {
  let func: Fn = () => { };
  const id = domSymbol.toString();

  //清除水印
  const clear = () => {
    const domId = document.getElementById(id);
    if (domId) {
      const el = unref(appendEl);
      el && el.removeChild(domId);
    }
    window.removeEventListener("resize", func);
  };
  //创建水印
  const createWatermark = (str: string) => {
    clear();

    const can = document.createElement("canvas");
    can.width = 300;
    can.height = 240;

    const cans = can.getContext("2d");
    if (cans) {
      cans.rotate((-20 * Math.PI) / 120);
      cans.font = "30px Vedana";
      cans.fillStyle = "rgba(0, 0, 0, 0.06)";
      cans.textAlign = "left";
      cans.textBaseline = "middle";
      cans.fillText(str, can.width / 20, can.height);
    }

    const div = document.createElement("div");
    div.id = id;
    div.style.pointerEvents = "none";
    div.style.top = "0px";
    div.style.left = "0px";
    div.style.position = "absolute";
    div.style.zIndex = "100000";
    div.style.width = document.documentElement.clientWidth + "px";
    div.style.height = document.documentElement.clientHeight + "px";
    div.style.background =
      "url(" + can.toDataURL("image/png") + ") left top repeat";
    const el = unref(appendEl);
    el && el.appendChild(div);

    //监听dom树发现DOM改变重新生成水印防止人为F12清除dom节点
    const MutationObserver =
      window.MutationObserver || window.WebKitMutationObserver;
    if (MutationObserver) {
      let mo: any = new MutationObserver(function () {
        const __wm = document.getElementById(id);
        if (!__wm) {
          mo.disconnect();
          mo = null;
          createWatermark(str);
        }
      });
      mo.observe(document.body, {
        attributes: true,
        subtree: true,
        childList: true,
      });
    }

    return id;
  };
  //设置水印
  function setWatermark(
    str: string = store.state.app.user.nickname || "内部资料"
  ) {
    createWatermark(str);
    func = () => {
      createWatermark(str);
    };
    window.addEventListener("resize", func);
    const instance = getCurrentInstance();
    if (instance) {
      onBeforeUnmount(() => {
        clear();
      });
    }
  }

  return { setWatermark, clear };
}
