<template>
  <div
    :class="{
      container: true,
      'sidebar-open': $store.state.app.sidebar.opened,
    }"
  >
    <div
      ref="myIframe"
      id="reader-container"
      :class="{ 'reader-container': true, 'show-panel': panelVisible }"
    ></div>
    <RightPanel
      ref="RightPanel"
      :readOnly="routeParams.readOnly"
      :class="[
        'right-panel',
        panelVisible ? 'translateXLeft' : 'translateXRight',
      ]"
      @handleInsertText="handleInsertText"
      @handleOpenAddUpdateDialog="handleOpenAddUpdateDialog"
      @handleToggleNotePanel="handleToggleNotePanel"
    />
    <AddOrUpdateNoteDialog
      :formData="form"
      ref="AddOrUpdateNoteDialog"
      @update="handleUpdateRightPanel"
    />
  </div>
</template>
<script>
import WebOfficeSDK from "/public/weboffice/web-office-sdk-v1.1.19.es";
// import WebOfficeSDK from "/public/weboffice/web-office-sdk-solution-v2.0.4.es";
import RightPanel from "../components/rightPanel.vue";
import AddOrUpdateNoteDialog from "../components/addOrUpdateNoteDialog.vue";
import { addNearRead } from "@/api/user";
import { mapGetters } from "vuex";
import { getNoteByTag, getNoteAllTagList } from "@/api/doc/index";
export default {
  components: {
    RightPanel,
    AddOrUpdateNoteDialog,
  },
  data() {
    return {
      wpsInstance: {}, //wps实例
      controlButton: {}, //新建笔记按钮
      routeParams: {}, //路由传过来的参数
      // 新增笔记需要的参数
      form: {
        docId: "", //文档Id
        bookmarkContent: "", //原文内容
        noteContent: "", //笔记内容
        tagsArr: [], //标签
        jsonStr: {
          //笔记在文档中位置的详细信息（包括标记方式、颜色、页码、起始位置等）
          subtype: "下划线", //标记方式
          color: "#ffff00", //标记颜色
        },
      },
      panelVisible: false, //笔记的窗口
    };
  },
  mounted() {
    const { wpsUrl, token, fileId, extendName, readOnly } = this.$route.query;
    this.routeParams = {
      wpsUrl,
      token,
      fileId,
      extendName,
      readOnly: Boolean(readOnly),
    };
    this.form.docId = fileId;
    this.initWps(wpsUrl, token, fileId);
  },
  destroyed() {
    this.removeDocSelectionListener();
  },
  methods: {
    // 初始化WPS
    async initWps(wpsUrl, token, fileId) {
      this.wpsInstance = WebOfficeSDK.config({
        url: wpsUrl,
        mount: document.querySelector("#reader-container"),
      });
      this.wpsInstance.setToken({ token });
      await this.wpsInstance.ready();
      // 添加文档选区监听
      this.addDocSelectionListen();
    },

    // 添加文档选区监听
    async addDocSelectionListen() {
      // debugger;
      console.log("addDocSelectionListen");
      // 等待加载完毕
      const app = this.wpsInstance.Application;
      this.wpsInstance.ApiEvent.AddApiEventListener(
        "WindowSelectionChange",
        (data) => {
          console.log("WindowSelectionChange: ", data);
          // this.handleDocSelectionChange(data);
        }
      );
    },

    // 新增阅读记录
    async addViewRecord() {
      const params = {
        docId: this.routeParams.fileId,
        docSType: "docx", //枚举值docx,pdf
      };
      await addNearRead(params);
    },
    //
    // // 增加浏览记录
    // this.addViewRecord();
    // const { readOnly } = this.routeParams;
    // // 只有只读的才能新建笔记和监听
    // if (readOnly) {
    //   // this.initAddNoteButton();
    //   this.addDocSelectionListen();
    // }

    // // 高亮文本
    // async highlightSelection() {
    //   const app = this.wpsInstance.Application;

    //   const font = await app.ActiveDocument.Range(118, 207).Font;

    //   // 设置选定文字的高亮颜色
    //   font.HighLight = "#228B22";
    // },

    // 监听DOC文字选取变化
    async handleDocSelectionChange(data) {
      console.log("handleDocSelectionChange", data);
      const { begin, end } = data;
      // console.log(data);
      if (begin != undefined && (end != undefined) & (begin != end)) {
        const app = this.wpsInstance.Application;
        // 获取选中区域
        const range = await app.ActiveDocument.Range(begin, end);
        // 获取文本
        const text = await range.Text;
        // 获取所在页
        const currentPage =
          await app.ActiveDocument.ActiveWindow.Selection.Information(
            app.Enum.WdInformation.wdActiveEndPageNumber
          );
        // 填入原文
        this.form.bookmarkContent = text;
        // 填入笔记相关信息
        this.form.jsonStr = { ...this.form.jsonStr, begin, end, currentPage };
        if (text) {
          this.controlButton.Enabled = true;
        } else {
          this.controlButton.Enabled = false;
        }
      } else {
        this.form.bookmarkContent = "";
        this.controlButton.Enabled = false;
      }
    },
    async getDocCurrentPage() {
      const app = this.wpsInstance.Application;

      // 获取当前页数
      const currentPage =
        await app.ActiveDocument.ActiveWindow.Selection.Information(
          app.Enum.WdInformation.wdActiveEndPageNumber
        );
      console.log(currentPage);
    },

    // 初始化并监听新建笔记按钮
    async initAddNoteButton() {
      const app = this.wpsInstance.Application;
      // 通过 CommandBar 的 Controls 对象，可获取到对应类型的内容集合，从而做新增操作或者获取到具体内容进行操作
      // 定制元素对象：【开始 Tab】
      const controls = await app.CommandBars("StartTab").Controls;
      // 新增按钮型定制元素
      this.controlButton = await controls.Add(1);
      this.controlButton.Caption = "新建笔记";

      this.controlButton.Enabled = false;
      this.controlButton.OnAction = this.handleAddNote;
    },

    // //添加PDF选取监听
    // addPdfSelectionListen() {
    //   this.wpsInstance.ApiEvent.AddApiEventListener(
    //     "TextSelectChange",
    //     async (data) => {
    //       console.log("TextSelectChange");
    //       // 复制选中的批注文案
    //       const app = this.wpsInstance.Application;
    //       console.log("app", app);

    //       await app.ActivePDF.AnnoAPI.SetSelectionAnno({
    //         type: app.Enum.AnnoType.Highlight,
    //         color: "rgba(0,0,0,1)",
    //       });
    //     }
    //   );
    // },

    //新建笔记
    handleAddNote() {
      if (this.form.bookmarkContent) {
        this.$refs.AddOrUpdateNoteDialog.dialogVisible = true;
      } else {
        this.$message.warning("请选择一段文字后再新建笔记！");
      }
    },

    // 移除文字选取监听
    removeDocSelectionListener() {
      if (this.wpsInstance && this.wpsInstance.ApiEvent) {
        this.wpsInstance.ApiEvent.RemoveApiEventListener("TextSelectChange");
      }
    },

    // 移除pdf选取监听
    removeDocSelectionListener() {
      if (this.wpsInstance && this.wpsInstance.ApiEvent) {
        this.wpsInstance.ApiEvent.RemoveApiEventListener(
          "WindowSelectionChange",
          this.handleDocSelectionChange
        );
      }
    },

    // 更新右侧获取笔记
    handleUpdateRightPanel() {
      this.$refs.RightPanel.loadNoteData();
    },

    // 插入文字
    async handleInsertText(value) {
      if (!this.wpsInstance.WordApplication) {
        this.$message.error("文档初始化失败，请稍后重试");
        return;
      }
      await this.wpsInstance
        .WordApplication()
        .ActiveDocument.ActiveWindow.Selection.InsertAfter(value);
      this.$notify.success({
        title: "提示",
        message: "引入成功",
      });
    },
    // 打开编辑笔记窗口
    handleOpenAddUpdateDialog(item) {
      this.$refs.AddOrUpdateNoteDialog.dialogVisible = true;
    },

    // 关闭笔记窗口
    handleToggleNotePanel() {
      this.panelVisible = !this.panelVisible;
    },

    // 加载笔记列表,在此处调用因为本页面需要用来高亮显示文档中的笔记
    async loadNoteList() {
      this.loading = true;
      const { current, size } = this.noteList;
      const { content, tagId } = this.searchParams;
      const params = {
        currentPage: current,
        pageCount: size,
        id: tagId,
        content,
      };
      let res = await getNoteByTag(params);
      this.oldContent = content;
      this.loading = false;
      if (res.code == 200) {
        this.noteList = res.data;
        this.loadTagList();
      }
    },
  },
};
</script>

<style lang="scss" scoped>
@import "../components/index.scss";
</style>
<style>
.web-office-iframe {
  width: 100% !important;
}
</style>
