<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"
      :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 RightPanel from "./component/rightPanel.vue";
import AddOrUpdateNoteDialog from "./component/addOrUpdateNoteDialog.vue";
import { addNearRead } from "@/api/user";
import { mapGetters } from "vuex";
export default {
  components: {
    RightPanel,
    AddOrUpdateNoteDialog,
  },
  data() {
    return {
      wpsInstance: {}, //wps实例
      controlButton: {}, //新建笔记按钮
      routeParams: {}, //路由传过来的参数
      // 新增笔记需要的参数
      form: {
        docId: "", //文档Id
        bookmarkContent: "", //原文内容
        noteContent: "", //笔记内容
        tagsArr: [], //标签
      },
      panelVisible: false, //笔记的窗口
      // isSidebarOpen:false
    };
  },
  computed: {
    isSidebarOpen() {
      return this.$store.state.app.sidebar.opened;
    },
  },
  watch: {
    panelVisible(value) {
      debugger
      // 获取office-iframe的dom并修改宽度为100vw
      const officeIframe = document.getElementById("office-iframe");
      if (!value) {
        officeIframe.style.width = "100vw !important";
      } else {
        officeIframe.style.width = "100% !important";
      }
    },
  },
  mounted() {
    const { wpsUrl, token, fileId } = this.$route.query;
    this.routeParams = { wpsUrl, token, fileId };
    this.form.docId = fileId;
    this.initWps(wpsUrl, token);
  },
  destroyed() {
    this.removeSelectionChangeListener();
  },
  methods: {
    // 新增阅读记录
    async addViewRecord() {
      const params = {
        docId: this.routeParams.fileId,
        docSType: "docx", //枚举值docx,pdf
      };
      console.log("params", params);
      return;
      try {
        let res = await addNearRead(params);
        if (res.code == 200) {
          console.log(123);
        } 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) {
      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;
    },
  },
};
</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>
