<template>
  <div class="wps-reader">
    <div ref="myIframe" id="wps-container" class="wps-container"></div>
    <RightPanel
      class="right-panel"
      @handleInsertText="handleInsertText"
      @handleOpenAddUpdateDialog="handleOpenAddUpdateDialog"
    />
  </div>
</template>
<script>
import WebOfficeSDK from "/public/weboffice/web-office-sdk-v1.1.19.es";
import RightPanel from "./component/rightPanel.vue";

export default {
  components: {
    RightPanel,
  },
  data() {
    return {
      wpsInstance: {}, //wps实例
      controlButton: {}, //新建笔记按钮
      routeParams:{},//路由传过来的参数
    };
  },
  mounted() {
    const { wpsUrl, token, fileId } = this.$route.query;
    this.routeParams = { wpsUrl, token, fileId }
    this.initWps(wpsUrl, token);
  },
  destroyed() {
    this.removeSelectionChangeListener();
  },
  methods: {
    // 新增阅读记录
    async addViewRecord() {
      const params = {
        docId: this.routeParams.fileId,
        docSType: "docx", //枚举值docx,pdf
      };
      try {
        let res = await addNearRead(params);
        if (res.code == 200) {
          // console.log();
        } else {
          throw res.code;
        }
      } catch (error) {
        console.error(error);
      }
    },
    // 初始化WPS
    async initWps(wpsUrl, token) {
      this.wpsInstance = WebOfficeSDK.config({
        wpsUrl,
        mount: document.querySelector("#wps-container"),
      });
      this.wpsInstance.setToken({ token });
      // 等待加载完毕
      await this.wpsInstance.ready();
      this.addSelectionListen();
      this.initAddNoteButton();
      this.addViewRecord();
    },

    // 添加监听选取文字
    addSelectionListen() {
      // 注册选取监听
      this.wpsInstance.ApiEvent.AddApiEventListener(
        "WindowSelectionChange",
        (data) => {
          this.handleSelectionChange(data);
        }
      );
    },
    // 初始化并监听新建笔记按钮
    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;
    },

    // 监听文字选取变化
    async handleSelectionChange(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;
        this.form.bookmarkContent = text;
        if (text) {
          this.controlButton.Enabled = true;
        } else {
          this.controlButton.Enabled = false;
        }
      } else {
        this.form.bookmarkContent = "";
        this.controlButton.Enabled = false;
      }
    },

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

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

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

    // 插入文字
    async handleInsertText(value) {
      await this.wpsInstance
        .WordApplication()
        .ActiveDocument.ActiveWindow.Selection.InsertAfter(value);
      this.$notify.success({
        title: "提示",
        message: "引入成功",
      });
    },

    handleOpenAddUpdateDialog(item) {
      this.$refs.AddOrUpdateNoteDialog.dialogVisible = true;
    },
  },
};
</script>
<style lang="scss" scoped>
.wps-reader {
  display: flex;
  .wps-container {
    width: 80vw;
    height: 100vh;
    overflow: hidden;
  }
  .right-panel {
    width: 20vw;
  }
}
.add-note-container {
  background-color: #999;
  width: 100px;
  height: 100px;
  padding: 20px;
}
</style>
