/**
 * ldesign v0.2.14
 * (c) 2022/11/2 16:16 built by swimly
 * @license MIT
 */

'use strict';

Object.defineProperty(exports, '__esModule', { value: true });

var VueCompositionAPI = require('@vue/composition-api');
var defineProperty838e4192 = require('../../chunks/defineProperty-838e4192.js');
var hooks_useConfig = require('../../hooks/use-config.js');
var hooks_lnode = require('../../hooks/lnode.js');
var components_watermark_hooks = require('./hooks.js');
var components_watermark_props = require('./props.js');
require('../config-provider/useConfig.js');
require('../config-provider/context.js');
require('lodash');
require('../../chunks/zh_CN.js');
require('lodash/isEmpty');
require('lodash/isFunction');
require('lodash/camelCase');
require('lodash/kebabCase');
require('../../hooks/render-lnode.js');

function ownKeys(object, enumerableOnly) {
  var keys = Object.keys(object);
  if (Object.getOwnPropertySymbols) {
    var symbols = Object.getOwnPropertySymbols(object);
    enumerableOnly && (symbols = symbols.filter(function (sym) {
      return Object.getOwnPropertyDescriptor(object, sym).enumerable;
    })), keys.push.apply(keys, symbols);
  }
  return keys;
}
function _objectSpread(target) {
  for (var i = 1; i < arguments.length; i++) {
    var source = null != arguments[i] ? arguments[i] : {};
    i % 2 ? ownKeys(Object(source), true).forEach(function (key) {
      defineProperty838e4192._defineProperty(target, key, source[key]);
    }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) {
      Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
    });
  }
  return target;
}
function generateBase64Url(_ref, onFinish) {
  var {
    width,
    height,
    gapX,
    gapY,
    offsetLeft,
    offsetTop,
    rotate,
    alpha,
    watermarkContent,
    lineSpace
  } = _ref;
  var canvas = document.createElement("canvas");
  var ctx = canvas.getContext("2d");
  if (!ctx) {
    console.warn("\u5F53\u524D\u73AF\u5883\u4E0D\u652F\u6301Canvas, \u65E0\u6CD5\u7ED8\u5236\u6C34\u5370");
    onFinish("");
    return;
  }
  var ratio = window.devicePixelRatio || 1;
  var canvasWidth = (gapX + width) * ratio;
  var canvasHeight = (gapY + height) * ratio;
  canvas.width = canvasWidth;
  canvas.height = canvasHeight;
  canvas.style.width = "".concat(gapX + width, "px");
  canvas.style.height = "".concat(gapY + height, "px");
  ctx.translate(offsetLeft * ratio, offsetTop * ratio);
  ctx.rotate(Math.PI / 180 * Number(rotate));
  ctx.globalAlpha = alpha;
  var markWidth = width * ratio;
  var markHeight = height * ratio;
  ctx.fillStyle = "transparent";
  ctx.fillRect(0, 0, markWidth, markHeight);
  var contents = Array.isArray(watermarkContent) ? watermarkContent : [_objectSpread({}, watermarkContent)];
  var top = 0;
  contents.forEach(item => {
    if (item.url) {
      var {
        url,
        isGrayscale = false
      } = item;
      item.top = top;
      top += height;
      var img = new Image();
      img.crossOrigin = "anonymous";
      img.referrerPolicy = "no-referrer";
      img.src = url;
      img.onload = () => {
        ctx.drawImage(img, 0, item.top * ratio, width * ratio, height * ratio);
        if (isGrayscale) {
          var imgData = ctx.getImageData(0, 0, ctx.canvas.width, ctx.canvas.height);
          var pixels = imgData.data;
          for (var i = 0; i < pixels.length; i += 4) {
            var lightness = (pixels[i] + pixels[i + 1] + pixels[i + 2]) / 3;
            pixels[i] = lightness;
            pixels[i + 1] = lightness;
            pixels[i + 2] = lightness;
          }
          ctx.putImageData(imgData, 0, 0);
        }
        onFinish(canvas.toDataURL());
      };
    } else if (item.text) {
      var {
        text,
        fontColor = "rgba(0, 0, 0, 0.1)",
        fontSize = 16,
        fontWeight = "normal"
      } = item;
      item.top = top;
      top += lineSpace;
      var markSize = Number(fontSize) * ratio;
      ctx.font = "normal normal ".concat(fontWeight, " ").concat(markSize, "px/").concat(markHeight, "px undefined");
      ctx.textAlign = "start";
      ctx.textBaseline = "top";
      ctx.fillStyle = fontColor;
      ctx.fillText(text, 0, item.top * ratio);
    }
  });
  onFinish(canvas.toDataURL());
}

function randomMovingStyle() {
  var align = Math.floor(Math.random() * 4);
  var p1 = Math.floor(Math.random() * 70) + 30;
  var leftTopLimit = 0;
  var bottomLimit = 95;
  var rightLimit = 90;
  var keyframesStyle = "\n  @keyframes watermark {\n    0%   {left: ".concat(align === 1 ? rightLimit : align === 3 ? leftTopLimit : p1, "%; top: ").concat(align === 0 ? leftTopLimit : align === 2 ? bottomLimit : p1, "%;}\n    25% {left: ").concat(align === 0 ? rightLimit : align === 2 ? leftTopLimit : 100 - p1, "%; top: ").concat(align === 1 ? bottomLimit : align === 3 ? leftTopLimit : p1, "%;}\n    50% {left: ").concat(align === 1 ? leftTopLimit : align === 3 ? rightLimit : 100 - p1, "%; top: ").concat(align === 0 ? bottomLimit : align === 2 ? leftTopLimit : 100 - p1, "%;}\n    75% {left: ").concat(align === 0 ? leftTopLimit : align === 2 ? rightLimit : p1, "%; top: ").concat(align === 1 ? leftTopLimit : align === 3 ? bottomLimit : 100 - p1, "%;}\n    100% {left: ").concat(align === 1 ? rightLimit : align === 3 ? leftTopLimit : p1, "%; top: ").concat(align === 0 ? leftTopLimit : align === 2 ? bottomLimit : p1, "%;}\n  }\n  ");
  return keyframesStyle;
}

var injectStyle = style => {
  var styleElement = document.createElement("style");
  var styleSheet = null;
  document.head.appendChild(styleElement);
  styleSheet = styleElement.sheet;
  styleSheet.insertRule(style, styleSheet.cssRules.length);
};

var _Watermark = VueCompositionAPI.defineComponent({
  name: "LWatermark",
  props: components_watermark_props["default"],
  setup(props2) {
    const backgroundImage = VueCompositionAPI.ref("");
    const watermarkRef = VueCompositionAPI.ref();
    const watermarkContentRef = VueCompositionAPI.ref();
    const parent = VueCompositionAPI.ref();
    const gapX = VueCompositionAPI.computed(() => props2.movable ? 0 : props2.x);
    const gapY = VueCompositionAPI.computed(() => props2.movable ? 0 : props2.y);
    const rotate = VueCompositionAPI.computed(() => props2.movable ? 0 : props2.rotate);
    const backgroundRepeat = VueCompositionAPI.computed(() => {
      if (props2.movable) return "no-repeat";
      return props2.isRepeat ? "repeat" : "no-repeat";
    });
    const offsetLeft = VueCompositionAPI.computed(() => {
      var _props2$offset;
      return ((_props2$offset = props2.offset) === null || _props2$offset === void 0 ? void 0 : _props2$offset[0]) || gapX.value / 2;
    });
    const offsetTop = VueCompositionAPI.computed(() => {
      var _props2$offset2;
      return ((_props2$offset2 = props2.offset) === null || _props2$offset2 === void 0 ? void 0 : _props2$offset2[1]) || gapY.value / 2;
    });
    const bgImageOptions = {
      width: props2.width,
      height: props2.height,
      rotate: rotate.value,
      lineSpace: props2.lineSpace,
      alpha: props2.alpha,
      gapX: gapX.value,
      gapY: gapY.value,
      watermarkContent: props2.watermarkContent,
      offsetLeft: offsetLeft.value,
      offsetTop: offsetTop.value
    };
    VueCompositionAPI.onMounted(() => {
      var _watermarkRef$value;
      generateBase64Url(bgImageOptions, base64Url => {
        backgroundImage.value = base64Url;
      });
      parent.value = (_watermarkRef$value = watermarkRef.value) === null || _watermarkRef$value === void 0 ? void 0 : _watermarkRef$value.parentElement;
      const keyframesStyle = randomMovingStyle();
      injectStyle(keyframesStyle);
      components_watermark_hooks.useMutationObserver(parent.value, mutations => {
        if (props2.removable) return;
        mutations.forEach(mutation => {
          if (mutation.type === "childList") {
            const removeNodes = mutation.removedNodes;
            removeNodes.forEach(node => {
              const element = node;
              if (element === watermarkRef.value) parent.value.appendChild(element);
              if (element === watermarkContentRef.value) watermarkRef.value.appendChild(element);
            });
          }
        });
      }, {
        attributes: true,
        childList: true,
        characterData: true,
        subtree: true
      });
    });
    return {
      gapX,
      gapY,
      backgroundRepeat,
      backgroundImage,
      watermarkRef,
      watermarkContentRef,
      bgImageOptions
    };
  },
  watch: {
    watermarkContent(content) {
      generateBase64Url({
        ...this.bgImageOptions,
        watermarkContent: content
      }, base64Url => {
        this.backgroundImage = base64Url;
      });
    }
  },
  render() {
    const h = arguments[0];
    const COMPONENT_NAME = hooks_useConfig.usePrefixClass("watermark");
    const renderContent = hooks_lnode.useContent();
    return h("div", {
      "style": {
        position: "relative",
        overflow: "hidden",
        width: "100%"
      },
      "class": COMPONENT_NAME.value,
      "ref": "watermarkRef"
    }, [renderContent("default", "content"), h("div", {
      "ref": "watermarkContentRef",
      "style": {
        zIndex: this.zIndex,
        position: "absolute",
        left: 0,
        right: 0,
        top: 0,
        bottom: 0,
        width: "100%",
        height: "100%",
        backgroundSize: `${this.gapX + this.width}px`,
        pointerEvents: "none",
        backgroundRepeat: this.backgroundRepeat,
        backgroundImage: `url('${this.backgroundImage}')`,
        animation: this.movable ? `watermark infinite ${this.moveInterval * 4 / 60}s` : "none"
      }
    })]);
  }
});

exports["default"] = _Watermark;
//# sourceMappingURL=watermark.js.map
