<template>
  <div class="pdfExpress">
    <div class="title">
      <svg class="icon" @click="showCompareSearch" v-if="compareFlag">
        <title>对比阅读</title>
        <use :xlink:href="`#icon-compare`"></use>
      </svg>
      <p :title="article.name">{{ article.name }}</p>
    </div>

    <div ref="viewer" class="content"></div>
    <el-dialog
      width="1300px"
      title="文档搜索"
      top="5vh"
      :visible.sync="compareSearch"
      class="CompareSearch"
      :close-on-click-modal="false"
      v-dialog-drag
    >
      <compare-search @changeRow="changeRow($event)" />
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeComparSearch">取 消</el-button>
        <el-button type="primary" @click="openCompareWindow">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog
      :append-to-body="true"
      v-if="compareWindowFlag"
      fullscreen
      :visible.sync="compareWindowFlag"
      class="CompareWindow"
      :close-on-click-modal="false"
    >
      <compare-window
        :articleCompare="compareSearchCurrentRow"
        :compareWindowFlag="compareWindowFlag"
      />
    </el-dialog>
  </div>
</template>

<script>
import WebViewer from "@pdftron/webviewer";
import { pdfAddOrUpdate, getBookMark, pdfRemoveMark } from "@/api/doc/bookMark";

export default {
  name: "readPdf",
  // props: ["article"],
  components: {
    // compareSearch: () => import("./components/compareSearch.vue"),
    // compareWindow: () => import("./components/compareWindow.vue"),
  },
  watch: {
    "$store.state.currentUser"(c, o) {
      console.log("c", c);
      this.isReadOnly = c === null;
      if (this.instance) {
        this.instance.dispose();
        document.querySelector("#webviewer-1").remove();
      }
      this.WebViewerInit();
    },
  },
  data() {
    return {
      noteArray: [],
      instance: undefined,
      isReadOnly:
        this.$store.state.currentUser?.userInfo?.username === undefined,
      compareSearch: false,
      compareSearchCurrentRow: undefined,
      compareWindowFlag: false,
      compareFlag: document.querySelector(".compareWindow") === null,
      article: {}, //文章信息
    };
  },
  methods: {
    openCompareWindow() {
      if (this.compareSearchCurrentRow !== undefined) {
        this.compareSearch = false;
        this.compareWindowFlag = true;
      }
    },
    closeComparSearch() {
      this.compareSearch = false;
      this.compareSearchCurrentRow = undefined;
    },
    changeRow(e) {
      this.compareSearchCurrentRow = e;
    },
    showCompareSearch() {
      this.compareSearch = true;
    },
    getBookMark() {
      let p = {
        docId: this.article.id,
        docSType: this.article.docSType,
      };
      getBookMark(p).then((res) => {
        if (res?.result?.xml) {
          for (let i = 0; i < res.result.xml.length; i++) {
            let tag = res.result.xml[i];
            this.instance.annotManager
              .importAnnotCommand(tag)
              .then((res) => {});
          }
        }
      });
    },
    documentLoaded() {
      this.instance.docViewer.on("documentLoaded", () => {
        setTimeout(() => {
          this.getBookMark();
          this.instance.docViewer.refreshAll();
          this.instance.docViewer.updateView();
        }, 1000);
        this.instance.setCurrentPageNumber(1);
        this.instance.setZoomLevel(1.2);
        this.instance.setNoteDateFormat("YYYY-MM-DD HH:mm");
        if (this.article.showMenu) {
          this.instance.toggleElement("leftPanel");
          this.instance.toggleElement("notesPanel");
        }
        let userName =
          this.$store.state.currentUser?.userInfo?.username || "游客";
        this.instance.setAnnotationUser(userName);
      });
    },
    annotationChanged() {
      this.instance.annotManager.on(
        "annotationChanged",
        (annotations, action, info) => {
          if (
            [
              "highlight",
              "underline",
              "squiggly",
              "strikeout",
              "text",
            ].includes(annotations[0].elementName)
          ) {
            if (info.imported === false || info.imported === undefined) {
              this.instance.annotManager.getAnnotCommand().then((res) => {
                if (action === "add" || action === "modify") {
                  this.addOrUpdateMark(res);
                } else {
                  this.deleteMark(annotations[0]);
                }
              });
            }
          }
        }
      );
    },
    updateReply() {},
    deleteReply() {
      this.instance.annotManager.on(
        "deleteReply",
        (annotation, parent, root) => {}
      );
    },
    addReply() {
      this.instance.annotManager.on("addReply", (annotation, root) => {});
    },
    addOrUpdateMark(e) {
      let p = new FormData();
      p.append("docId", this.article.id);
      p.append("docSType", this.article.docSType);
      p.append("xmlParams", e);
      //  zwj p.append('xmlParams', e) 标签(多个用逗号分割)
      p.append("tags", "问题");
      pdfAddOrUpdate(p).then((res) => {
        if (res.code === 500) {
          this.$message.error(res.message);
        } else {
          this.$message.success("操作成功");
        }
      });
    },
    deleteMark(e) {
      let p = new FormData();
      p.append("uniqueId", e.Id);
      pdfRemoveMark(p).then((res) => {
        if (res.code === 200) {
          this.$message.success("删除成功");
        } else {
          this.$message.error("删除失败，请重试");
        }
      });
    },
    updateMark() {},
    setWatermark() {
      this.instance.docViewer.setWatermark({
        // Draw diagonal watermark in middle of the document
        diagonal: {
          fontSize: 60, // or even smaller size
          fontFamily: "sans-serif",
          color: "#67c3e0",
          opacity: 50, // from 0 to 100
          text: "CNKI",
        },
      });
      this.instance.docViewer.getWatermark().then((res) => {
        debugger;
      });
    },
    contextMenuPopup() {
      this.instance.contextMenuPopup.add({
        type: "actionButton",
        label: "some-label",
        onClick: (e, a) => {},
      });
    },
    setHeaderItems() {
      this.instance.setHeaderItems((header) => {
        header.push({
          type: "toggleElementButton",
          img: "ic_left_sidebar_black_24px",
          element: "leftPanel",
        });
      });
    },
    WebViewerInit() {
      let _this = this;
      console.log("article", this.article);
      WebViewer(
        {
          path: "/static/webviewer",
          // initialDoc: '/static/webviewer/demo.pdf', // replace with your own PDF file
          initialDoc: this.article.url, // replace with your own PDF file
          fullAPI: true,
          config: "/static/webviewer/ui/webViewerConfig.js",
          isReadOnly:
            this.isReadOnly || this.$route.query.isReadOnly === "true",
        },
        this.$refs.viewer
      ).then((instance) => {
        this.instance = instance;
        instance.setLanguage("zh_cn");
        this.documentLoaded();
        this.annotationChanged();
        this.deleteReply();
        this.addReply();
        this.contextMenuPopup();

        this.instance.annotManager.on(
          "setNoteText",
          (annotation, parent, root) => {}
        );

        this.instance.annotManager.on(
          "fieldChanged",
          (annotation, parent, root) => {}
        );
      });
    },
    // 获取文章信息
    getArticleInfo() {
      this.article = {
        name: this.$route.query.title,
        id: this.$route.query.id,
        docSType: this.$route.query.docSType,
        url: this.$route.query.pdfSrc,
        showMenu: true,
      };
      this.WebViewerInit();
    },
  },
  mounted() {
    this.getArticleInfo();
  },
};
</script>
<style lang="scss">
.CompareSearch {
  & > .el-dialog {
    border-radius: 8px !important;
  }

  .el-dialog__header {
    border-bottom: 1px solid #e6e6e6;
  }
}

.CompareWindow {
  & > .el-dialog {
    background-color: rgba(0, 0, 0, 0.5) !important;

    & > .el-dialog__header {
      .el-dialog__headerbtn {
        width: 40px;
        height: 40px;
        margin-top: 6px;
        margin-right: 10px;
        border-radius: 30px;
        background-color: rgba(0, 0, 0, 0.5);
        font-size: 40px !important;
        transition: all 1s ease;

        .el-icon-close {
          color: #ffffff;
        }
      }

      .el-dialog__headerbtn:hover {
        transform: rotate(180deg);
      }
    }
  }
}
</style>

<style lang="scss" scoped>
.pdfExpress {
  width: 100%;
  height: calc(100vh - 70px);

  & > .title {
    width: 100%;
    height: 50px;
    background-color: #f1f3f5;
    line-height: 50px;
    font-size: 30px;
    font-family: cursive;

    & > .icon {
      cursor: pointer;
      margin-top: 6px;
      margin-left: 10px;
      float: left;
      border-radius: 6px;
      font-weight: bold;
      background-color: #dde6ee;
      padding: 6px;
      width: 22px;
      height: 22px;
    }

    & > p {
      margin: 0 auto;
      width: 50%;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
      color: #185db7;
      font-weight: bold;
      text-align: center;
    }
  }

  & > .content {
    height: 100%;
  }
}
</style>
