<template>
  <div
    :class="{
      'wps-reader': true,
      'sidebar-open': $store.state.app.sidebar.opened,
    }"
  >
    <div ref="myIframe" id="wps-container" class="wps-container"></div>
    <RightPanel
      class="right-panel"
      @handleInsertText="handleInsertText"
      @handleOpenAddUpdateDialog="handleOpenAddUpdateDialog"
    />
    <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: [], //标签
      },
      // isSidebarOpen:false
    };
  },
  computed: {
    // ...mapGetters(["sidebar"]),
    isSidebarOpen() {
      return this.$store.state.app.sidebar.opened;
    },
  },
  // watch:{
  //   'sidebar.opened':{
  //     handler(value){
  //       this.isSidebarOpen =
  //     },
  //     immediate:true
  //   }
  // },
  mounted() {
    const { wpsUrl, token, fileId } = this.$route.query;
    this.routeParams = { wpsUrl, token, fileId };
    this.form.docId = fileId;
    this.initWps(wpsUrl, token);
    console.log("isSidebarOpen", this.isSidebarOpen);
  },
  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(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) {
      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: calc((100vw - 54px) * 0.8); //默认宽度是sidebar收起的宽度
    overflow: hidden;
  }

  .right-panel {
    width: calc((100vw - 54px) * 0.2); //默认宽度是sidebar收起的宽度
  }

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

.sidebar-open {
  .wps-container {
    width: calc((100vw - 200px) * 0.8); //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>
