<template>
  <div class="container GCLS-BOOK-Container">
    <div
      id="content-scroll"
      class="content"
      :class="[type ? 'content-top' : '']"
    >
      <div
        id="data-screen"
        v-loading="loading"
        :class="['inner', fullscreen ? 'inner-full' : '']"
      >
        <div class="resule-box" v-if="ViewMode === 'Result'">
          <span>用时：{{ handleDateTime(this.duration) }}</span>
          <span
            >答对：<span style="color: #2ca767">{{ rightNumber }}</span>
            个</span
          >
          <span
            >答错：<span style="color: #ed342d">{{ errorNumber }}</span>
            个</span
          >
        </div>
        <div v-if="chapterId" class="title-box">
          <img
            v-if="!treeFlag"
            src="../assets/common/icon-view-back.png"
            @click="treeShow"
          />
          <img
            v-if="!treeFlag"
            src="../assets/common/icon-treelist.png"
            @click="chooseCourseware"
          />
        </div>

        <template v-if="category == 'OC' || !category">
          <Preview
            v-if="chapterId && context"
            ref="previewAnswer"
            :context="context"
            :book-answer-content="bookAnswerContent"
            bookclientwidth="900"
            :task-model="TaskModel"
            @handleBookUserAnswer="handleBookUserAnswer"
          />
        </template>
        <template
          v-if="
            category == 'NPC' &&
            ((bookAnswerContent && TaskModel === 'ANSWER') ||
              TaskModel !== 'ANSWER')
          "
        >
          <Booknpc
            v-if="chapterId && context"
            ref="previewBook"
            :context="context"
            :current-tree-i-d="chapterId"
            :father-tree-data="FatherTreeData"
            :change-id="changeId"
            :theme-color="themeColor"
            :is-show-title="false"
            :task-model="TaskModel"
            :is-show-save="showSaveFlag"
            :book-answer-content="bookAnswerContent"
            :is-answer-item-show="isAnswerItemShow"
            :previewType="previewType"
            :previewGroupId="previewGroupId"
            @finishTaskMaterial="finishTaskMaterial"
          />
        </template>
        <template v-if="category == 'NNPE'">
          <Booknnpe
            v-if="chapterId && context"
            ref="previewAnswerNNPE"
            :context="context"
            :current-tree-i-d="chapterId"
            :father-tree-data="FatherTreeData"
            :change-id="changeId"
            :theme-color="themeColor"
            :is-show-title="false"
            :is-answer-item-show="true"
            :task-model="TaskModel"
            :is-show-save="showSaveFlag"
            :book-answer-content="bookAnswerContent"
            @finishTaskMaterial="finishTaskMaterial"
          />
        </template>
        <template v-if="category == 'RLC'">
          <Bookrlc
            v-if="chapterId && context"
            ref="previewAnswerRLC"
            :context="context"
            :current-tree-i-d="chapterId"
            :father-tree-data="FatherTreeData"
            :change-id="changeId"
            :theme-color="themeColor"
            :is-show-title="false"
            :book-font-size="bookFontSize"
            :is-answer-item-show="isAnswerItemShow"
            :task-model="TaskModel"
            :is-show-save="showSaveFlag"
            :book-answer-content="bookAnswerContent"
            @finishTaskMaterial="finishTaskMaterial"
          />
        </template>
      </div>
    </div>
  </div>
</template>

<script>
import Header from "@/components/inputModules/common/Header";
import Nav from "@/components/inputModules/common/Nav";
import TreeView from "@/components/inputModules/common/TreeView";
import { getContens } from "@/api/ajax";
import Cookies from "js-cookie";
// import Preview from '@/componentsAnswer/PreviewAnswer.vue'
import Preview from "@/components/Preview";
import { getStaticContent, getContent, LearnWebSI } from "@/api/ajax";
import { setToken } from "@/utils/auth";
export default {
  name: "CourseWare",
  directives: {
    move(el, bindings) {
      el.onmousedown = function (e) {
        var init = e.clientX;
        var parent = document.getElementById("content-tree");
        var initWidth = parent.offsetWidth;
        document.onmousemove = function (e) {
          var end = e.clientX;
          var newWidth = end - init + initWidth;
          if (newWidth >= 340 && newWidth <= 680) {
            parent.style.width = newWidth + "px";
          }
        };
        document.onmouseup = function () {
          document.onmousemove = document.onmouseup = null;
        };
      };
    },
  },
  components: {
    Header,
    Nav,
    TreeView,
    Preview,
  },
  data() {
    return {
      bookId: "",
      chapterId: "",
      fullscreen: false, // 控制全屏
      fullTree: false, // 全屏模式下树是否显示
      context: null,
      question: null, // 选择的模板题型
      treeFlag: true, // tree是否显示
      isAnswerShow: false, // 是否显示答案
      bookAnswerContent: "",
      TaskModel: "",
      category: "",
      FatherTreeData: null,
      themeColor: "",
      type: "",
      name: "",
      loading: false,
      bookFontSize: "",
      showContent: false,
      isAnswerItemShow: true,
      showSaveFlag: false,
      rightNumber: 0,
      errorNumber: 0,
      duration: 0,
      AppID: this.$route.query.AppID ? this.$route.query.AppID : "",
      AccessToken: this.$route.query.AccessToken
        ? this.$route.query.AccessToken
        : "",
      CoursewareID: this.$route.query.CoursewareID
        ? this.$route.query.CoursewareID
        : "",
      UserID: this.$route.query.UserID ? this.$route.query.UserID : "",
      ViewMode: this.$route.query.ViewMode ? this.$route.query.ViewMode : "",
      BusinessID: this.$route.query.BusinessID
        ? this.$route.query.BusinessID
        : "",
      previewType:
        this.$route.query.ViewMode && this.$route.query.ViewMode === "Select"
          ? "previewCheck"
          : "previewCheckShow",
      previewGroupId: this.$route.query.CoursewareGroupIDSelectedInfo
        ? this.$route.query.CoursewareGroupIDSelectedInfo
        : "[]",
    };
  },
  watch: {
    bookAnswerContent: {
      handler(newVal, oldVal) {
        if (newVal) {
          this.loading = false;
        }
      },
      deep: true,
    },
  },
  async created() {
    const _this = this;
    if (_this.AccessToken) {
      const Mname = "login_control-ParseAccessToken";
      await getStaticContent(Mname, {
        access_token: _this.AccessToken,
      }).then((res) => {
        setToken(res);
        sessionStorage.setItem("GCLS_Token_Book", JSON.stringify(res));
        if (_this.AppID === "Mobile_Task") {
          _this.UserID = res.user_code;
        }
      });
    }
    if (_this.ViewMode === "Answer") {
      // 答题模式下 显示提交按钮 隐藏查看答案按钮
      this.showSaveFlag = true;
      this.isAnswerItemShow = false;
    } else if (_this.ViewMode === "Result") {
      this.isAnswerItemShow = false;
      this.TaskModel = "ANSWER";
      this.getUserAnswer();
    }

    _this.changeId();
  },
  mounted() {
    const _this = this;
    window.addEventListener(
      "message",
      function (event) {
        if (event.data === "Selected") {
          _this.finishPreviewGroupIds();
        }
      },
      false
    );
  },
  methods: {
    back() {
      this.$router.go(-1);
    },
    changeTreeData(val) {
      this.FatherTreeData = JSON.parse(JSON.stringify(val));
    },
    changeId(id, name) {
      const _this = this;
      _this.chapterId = _this.CoursewareID;
      _this.isAnswerShow = false;
      _this.onGetData();
    },
    // 点击全屏展示 隐藏tree
    fullScreen() {
      this.treeFlag = false;
      this.fullscreen = true;
      document.getElementById("content-tree").style.display = "none";
    },
    treeShow() {
      this.treeFlag = true;
      this.fullTree = false;
      this.fullscreen = false;
      document.getElementById("content-tree").style.display = "block";
    },
    // 获取预览数据
    onGetData() {
      this.loading = true;
      const _this = this;
      const AppID = _this.AppID;
      const AccessToken = _this.AccessToken;
      const MethodName =
        "/TeachingServer/BookIntegrationManager/GetCoursewareContent_View";
      const data = {
        courseware_id: _this.CoursewareID,
        user_id: _this.UserID,
      };
      if (_this.AppID === "Mobile_Task") {
        const MethodName = "book-courseware_manager-GetCoursewareContent_View";
        const data = {
          id: _this.chapterId,
        };
        getContent(MethodName, data).then((res) => {
          this.category = res.category;
          this.themeColor = res.book_theme_color;
          this.bookFontSize = res.book_font_size;
          if (res.content) {
            const _this = this;
            if (!this.category || this.category == "OC") {
              _this.context = {
                id: _this.chapterId,
                ui_type: JSON.parse(res.content).question
                  ? JSON.parse(res.content).question.ui_type
                  : "",
                sort_number: 1,
                content: JSON.parse(res.content),
              };
            } else {
              _this.context = JSON.parse(res.content);
            }
            setTimeout(() => {
              if (_this.ViewMode === "Answer") {
                _this.$refs.previewBook.handleAnswerTimeStart();
              }
            }, 200);
          } else {
            const _this = this;
            _this.context = null;
          }
          if (_this.ViewMode !== "Result") {
            this.loading = false;
          }
        });
      } else {
        getContens(MethodName, data, AccessToken, AppID).then((res) => {
          this.category = res.category;
          this.themeColor = res.book_theme_color;
          this.bookFontSize = res.book_font_size;
          if (res.content) {
            const _this = this;
            if (!this.category || this.category == "OC") {
              _this.context = {
                id: _this.chapterId,
                ui_type: JSON.parse(res.content).question
                  ? JSON.parse(res.content).question.ui_type
                  : "",
                sort_number: 1,
                content: JSON.parse(res.content),
              };
            } else {
              _this.context = JSON.parse(res.content);
            }
            setTimeout(() => {
              if (_this.ViewMode === "Answer") {
                _this.$refs.previewBook.handleAnswerTimeStart();
              }
            }, 200);
          } else {
            const _this = this;
            _this.context = null;
          }
          if (_this.ViewMode !== "Result") {
            this.loading = false;
          }
        });
      }
    },
    // 跳转编辑页面
    handleEdit() {
      const index = this.$refs.treeView.handleParentIndex().split("###");
      if (index.length > 1) {
        Cookies.set("bookIndex", index[0]);
        Cookies.set("bookLevel", index[1]);
        Cookies.set("bookNodename", index[2]);
      }
      this.$router.push("/input?bookId=" + this.bookId);
    },
    // 显示或隐藏答案
    handleAnswerShow() {
      this.isAnswerShow = !this.isAnswerShow;
      this.$refs.previewAnswer.bookAnswerShow(this.isAnswerShow);
    },
    // 得到用户答题答案
    handleBookUserAnswer(data) {
      console.log(data);
    },
    // 悬浮树隐藏显示
    chooseCourseware() {
      this.fullTree = !this.fullTree;
      if (this.fullTree) {
        document.getElementById("content-tree").style.display = "block";
      } else {
        document.getElementById("content-tree").style.display = "none";
      }
    },
    finishTaskMaterial(data, time, rightNumber, errorNumber) {
      // sessionStorage.setItem("userAnswers", data);
      // console.log("用户提交的答案：" + data);
      // console.log("答题时间" + time);
      // console.log("答对个数" + rightNumber);
      // console.log("答错个数" + errorNumber);
      this.loading = true;
      if (this.AppID === "Mobile_Task") {
        const MethodName = "teaching-task_manager-FinishMyTaskMaterial_Student";
        const datas = {
          task_id: this.BusinessID,
          material_id: this.CoursewareID,
          material_type: "COURSEWARE",
          exam_answer: {
            duration: time,
            count_right: rightNumber,
            count_error: errorNumber,
            content: data,
          },
        };
        LearnWebSI(MethodName, datas)
          .then((res) => {
            this.loading = false;
            if (res.status === 1) {
              this.$message.success("提交成功");
            }
          })
          .catch(() => {
            this.loading = false;
          });
      } else {
        const AppID = this.AppID;
        const AccessToken = this.AccessToken;
        const MethodName =
          "/TeachingServer/BookIntegrationManager/SaveCoursewareExamAnswer";
        let datas = {
          courseware_id: this.CoursewareID,
          user_id: this.UserID,
          business_id: this.BusinessID,
          exam_answer: {
            duration: time,
            count_right: rightNumber,
            count_error: errorNumber,
            content: data,
          },
        };
        getContens(MethodName, datas, AccessToken, AppID)
          .then((res) => {
            this.loading = false;
            if (res.status === 1) {
              this.$message.success("提交成功");
            }
          })
          .catch(() => {
            this.loading = false;
          });
      }
    },
    finishPreviewGroupId() {
      this.$refs.previewBook.submitPreviewGroupId();
    },
    // 给父级返回选中课件内容id
    finishPreviewGroupIds() {
      let CoursewareGroupIDSelectedInfo =
        this.$refs.previewBook.submitPreviewGroupId();
      window.parent.postMessage(CoursewareGroupIDSelectedInfo, "*");
    },
    // 获取用户答题信息
    getUserAnswer() {
      this.loading = true;
      if (this.AppID === "Mobile_Task") {
        const MethodName =
          "teaching-task_manager-GetTaskMaterialStudentExamAnswer";
        let datas = {
          task_id: this.BusinessID,
          material_id: this.CoursewareID,
          material_type: "COURSEWARE",
          student_id: this.UserID,
        };
        LearnWebSI(MethodName, datas)
          .then((res) => {
            this.loading = false;
            if (res.status === 1) {
              this.bookAnswerContent = res.content;
              this.duration = res.duration;
              this.rightNumber = res.count_right;
              this.errorNumber = res.count_error;
            }
          })
          .catch(() => {
            this.loading = false;
          });
      } else {
        const AppID = this.AppID;
        const AccessToken = this.AccessToken;
        const MethodName =
          "/TeachingServer/BookIntegrationManager/GetCoursewareExamAnswer";
        let datas = {
          courseware_id: this.CoursewareID,
          user_id: this.UserID,
          business_id: this.BusinessID,
        };
        getContens(MethodName, datas, AccessToken, AppID)
          .then((res) => {
            if (res.status === 1) {
              let exam_answer = res.exam_answer
                ? JSON.parse(res.exam_answer)
                : null;
              if (!exam_answer) return;
              this.bookAnswerContent = exam_answer.content;
              this.duration = exam_answer.duration;
              this.rightNumber = exam_answer.count_right;
              this.errorNumber = exam_answer.count_error;
            } else {
              this.loading = false;
            }
          })
          .catch(() => {
            this.loading = false;
          });
      }
    },
    handleDateTime(time) {
      if (parseInt(time / 60) < 10) {
        time =
          ("0" + parseInt(time / 60)).substring(
            ("0" + parseInt(time / 60)).length - 2
          ) +
          ":" +
          ("0" + (time % 60)).substring(("0" + (time % 60)).length - 2);
      } else {
        time =
          parseInt(time / 60) +
          ":" +
          ("0" + (time % 60)).substring(("0" + (time % 60)).length - 2);
      }
      return time;
    },
  },
};
</script>
<style lang="scss" scoped>
.header-box {
  position: fixed;
  width: 100%;
  top: 0;
  left: 0;
  z-index: 999;
}
.container {
  width: 100%;
  height: auto;
  .bookname {
    width: 100%;
    height: 60px;
    display: flex;
    align-items: center;
    box-sizing: border-box;
    padding: 0 46px;
    background: #f3f7fa;
    position: relative;
    z-index: 999;
  }
  .content {
    width: 100%;
    display: flex;
    justify-content: flex-start;
    align-items: flex-start;
    height: 100vh;
    overflow: auto;
    padding-top: 24px;
    &-top {
      padding-top: 60px;
      .title-box {
        top: 66px !important;
      }
      .content-tree-full {
        top: 100px !important;
      }
    }
    &-tree {
      width: 340px;
      height: 85vh;
      overflow: auto;
      padding: 20px 0px;
      border-right: 1px solid #d9d9d9;
      background: #fff;
      position: fixed;
      left: 0;
      z-index: 2;
    }
    .content-tree-full {
      position: fixed !important;
      top: 170px;
      left: 152px;
      max-height: 588px;
      overflow: auto;
      z-index: 1000;
      background: #fff;
      box-shadow: 0px 2px 8px rgba(0, 0, 0, 0.25);
      border-radius: 4px;
    }
    #content-tree {
      //   position: relative;
    }
    .moveBtn-nnpe {
      position: absolute;
      height: 100%;
      width: 10px;
      right: 0;
      top: 0;
      cursor: col-resize;
    }
    .inner {
      // border-left: 1px solid #d9d9d9;
      width: 1000px;
      margin: 0 auto;
      flex: 1;
      box-sizing: border-box;
      padding: 20px;
      position: relative;
      background: #fff;
      &.inner-full {
        margin-left: 0;
      }
      .title-box {
        display: flex;
        align-items: center;
        margin-bottom: 12px;
        padding-right: 160px;
        position: fixed;
        top: 130px;
        left: 64px;
        z-index: 1;
        > img {
          width: 40px;
          margin-right: 16px;
          cursor: pointer;
        }
      }
      .title {
        font-size: 24px;
        margin-bottom: 20px;
        line-height: 40px;
        margin: 0;
      }
      .has-module {
        display: flex;
        justify-content: flex-start;
        align-items: flex-start;
        &-tree {
          width: 340px;
          height: 100%;
          overflow: auto;
          padding: 20px 0px;
          border-right: 1px solid #d9d9d9;
        }
        .inner {
          // border-left: 1px solid #d9d9d9;
          width: 1000px;
          flex: 1;
          margin: 0 auto;
          box-sizing: border-box;
          padding: 20px;
          position: relative;
          background: #fff;
          .title-box {
            display: flex;
            align-items: center;
            margin-bottom: 12px;
            padding-right: 160px;
            position: relative;
            > img {
              width: 40px;
              margin-right: 16px;
              cursor: pointer;
            }
          }
          .title {
            font-size: 24px;
            margin-bottom: 20px;
            line-height: 40px;
            margin: 0;
          }
          .has-module {
            display: flex;
            justify-content: flex-start;
            align-items: flex-start;
          }
          .edit-btn {
            display: inline-block;
            font-size: 14px;
            background: #ff9900;
            float: right;
            line-height: 36px;
            color: #fff;
            width: 60px;
            text-align: center;
            border-radius: 4px;
          }
        }
      }
    }

    .nav-list {
      width: 200px;
      height: 40px;
      background: rgba(49, 212, 134, 0.2);
      border-radius: 240px;
      display: flex;
      justify-content: flex-start;
      align-items: center;
      padding: 0;
      margin: 0;
      margin-bottom: 10px;
      list-style: none;
      > li {
        height: 40px;
        width: 100px;
        text-align: center;
        font-style: normal;
        font-weight: bold;
        font-size: 14px;
        line-height: 40px;
        color: #19b068;
        cursor: pointer;
        &.active {
          background: #19b068;
          border-radius: 240px;
          color: #ffffff;
        }
      }
    }
  }
  .answerShow {
    position: absolute;
    right: 20px;
    top: 20px;
    width: 112px;
    height: 40px;
    background: #ffffff url("../assets/common/icon-eye-close.png") 16px center
      no-repeat;
    background-size: 16px;
    border: 1px solid rgba(44, 44, 44, 0.15);
    box-sizing: border-box;
    border-radius: 4px;
    font-size: 14px;
    line-height: 150%;
    color: #000000;
    padding: 9px 16px 9px 36px;
    cursor: pointer;
    z-index: 2;
    &.answerShowTrue {
      background: #f5f5f5 url("../assets/common/icon-eye-open.png") 16px center
        no-repeat;
      background-size: 16px;
    }
  }
}
.resule-box {
  width: 860px;
  margin: 0 auto 20px auto;
  > span {
    margin-right: 24px;
  }
}
</style>
<style lang="scss">
.GCLS-BOOK-Container {
  .screen-full {
    position: fixed;
    right: 30px;
    bottom: 30px;
    width: 48px;
    height: 48px;
    background: rgba(0, 0, 0, 0.4) url("../assets/common/icon-screenFull.png")
      center no-repeat;
    background-size: 32px;
  }
}
.title-box {
  .el-switch {
    position: absolute;
    top: 0;
    right: 0px;
    border: 1px solid rgba(44, 44, 44, 0.15);
    border-radius: 40px;
    height: 40px;
    padding: 6px 6px 6px 16px;
  }
  .el-switch__label.is-active {
    color: #000000;
    font-size: 16px;
  }
}
</style>
