<template>
  <el-dialog
    :class="[
      'card-preview-dialog page-dialog',
      { 'is-print': this.viewType === 'print' },
    ]"
    :visible.sync="modalIsShow"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :modal="false"
    append-to-body
    fullscreen
    @opened="dialogOpened"
  >
    <div slot="title">题卡预览</div>
    <div slot="footer"></div>

    <card-preview
      v-if="modalIsShow"
      is-dialog
      :card-data="cardData"
      :view-type="viewType"
      :card-id="cardId"
      @confirm="confirm"
    ></card-preview>
  </el-dialog>
</template>

<script>
import CardPreview from "../views/CardPreview.vue";

export default {
  name: "card-preview-dialog",
  components: { CardPreview },
  props: {
    viewType: {
      type: String,
      default: "view",
    },
    cardData: {
      type: Object,
      default: null,
    },
    cardId: {
      type: String,
      default: null,
    },
    showWatermark: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      modalIsShow: false,
    };
  },
  methods: {
    cancel() {
      this.modalIsShow = false;
    },
    open() {
      this.modalIsShow = true;
    },
    confirm(content) {
      this.cancel();
      this.$emit("confirm", content);
    },
    dialogOpened() {
      if (this.showWatermark) this.setWatermark();
    },
    setWatermark() {
      const { loginName, realName } = this.$ls.get("user", {});
      const content = `${realName}(${loginName})`;

      const canvas = document.createElement("canvas");
      const ctx = canvas.getContext("2d");

      const fontSize = 40;
      ctx.font = `${fontSize}px serif`;
      const cInfo = ctx.measureText(content);
      const cwidth = Math.max(360, cInfo.width) * 1.2;
      canvas.width = cwidth;
      canvas.height = cwidth;

      ctx.font = `${fontSize}px serif`;
      ctx.fillStyle = "rgba(212,212,212,0.5)";
      ctx.textAlign = "center";
      ctx.textBaseline = "middle";
      const angle = (315 * Math.PI) / 180;
      const x = canvas.width / 2;
      const y = canvas.height / 2;

      ctx.translate(x, y);
      ctx.rotate(angle);
      ctx.fillText(content, 0, 0);

      const bgSize = 240;

      canvas.toBlob((val) => {
        if (!val) return;
        const watermarkBg = window.URL.createObjectURL(val);
        this.$el.querySelectorAll(".page-main-inner").forEach((dom) => {
          dom.setAttribute(
            "style",
            `background-image: url(${watermarkBg});background-repeat: repeat;background-size: ${bgSize}px ${bgSize}px;`
          );
        });
      });
    },
  },
};
</script>
