<template>
  <div
    :class="{
      'wps-reader': true,
      'sidebar-open': $store.state.app.sidebar.opened,
    }"
  >
    <div ref="myIframe" id="wps-container" class="wps-container"></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-sdk19.es";
// import WebOfficeSDK from "/public/weboffice/web-office-sdk-solution-v2.0.4.es";
import RightPanel from "./component/rightPanel.vue";
import AddOrUpdateNoteDialog from "./component/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: {
          //笔记在文档中位置的详细信息（包括标记方式、颜色、页码、起始位置等）
          markingMode: "下划线", //标记方式
          color: "#ffff00", //标记颜色
        },
      },
      panelVisible: false, //笔记的窗口
    };
  },
  computed: {
    isSidebarOpen() {
      return this.$store.state.app.sidebar.opened;
    },
  },
  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({
        wpsUrl,
        mount: document.querySelector("#wps-container"),
      });
      this.wpsInstance.setToken({ token });
      // 等待加载完毕
      await this.wpsInstance.ready();
      // 增加浏览记录
      this.addViewRecord();
      const { readOnly } = this.routeParams;
      console.log("readOnly", readOnly);
      // 只有只读的才能新建笔记和监听
      if (readOnly) {
        // this.initAddNoteButton();
        this.addDocSelectionListen();
      }
    },

    // 新增阅读记录
    async addViewRecord() {
      const params = {
        docId: this.routeParams.fileId,
        docSType: "docx", //枚举值docx,pdf
      };
      await addNearRead(params);
    },

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

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

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

    // 添加DOC监听选取文字
    addDocSelectionListen() {
      // 注册选取监听
      this.wpsInstance.ApiEvent.AddApiEventListener(
        "WindowSelectionChange",
        (data) => {
          this.handleDocSelectionChange(data);
        }
      );
    },

    // 监听DOC文字选取变化
    async 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>
.wps-reader {
  display: flex;
  position: relative;
  .wps-container {
    transition: all ease 0.5s;
    width: calc(100vw - 54px); //默认宽度是sidebar收起的宽度
    overflow: hidden;
  }
  .right-panel {
    position: absolute;
    right: 0;
    top: 0;
    transition: all ease 0.5s;
    width: calc((100vw - 54px) * 0.2); //默认宽度是sidebar收起的宽度
  }
  .translateXLeft {
    transform: translateX(0);
  }
  .translateXRight {
    transform: translateX(calc((100vw - 54px) * 0.2));
  }

  .wps-container,
  .right-panel {
    height: calc(100vh - 84px);
    transition: all ease 0.5s;
  }
}

.sidebar-open {
  .wps-container {
    width: calc(100vw - 200px); //sidebar展开后的宽度
  }

  // .right-panel {
  //   width: calc((100vw - 200px) * 0.2); //默认宽度是sidebar收起的宽度
  // }
}
.add-note-container {
  background-color: #999;
  width: 100px;
  height: 100px;
  padding: 20px;
}
</style>
<style>
.web-office-iframe {
  width: 100% !important;
}
</style>
