<template>
  <div class="common-preview">
    <div class="common-preview__header">
      <div class="courseware">
        <span class="flow-nodename">{{ courseware_info.cur_audit_flow_node_name }}</span>
        <slot name="middle" :courseware="courseware_info"></slot>
        <div class="group">
          <el-checkbox v-model="isShowGroup">显示分组</el-checkbox>
          <el-checkbox v-model="groupShowAll">分组显示全部</el-checkbox>
          <el-checkbox v-model="isJudgeCorrect">判断对错</el-checkbox>
          <el-checkbox v-model="isShowAnswer" :disabled="!isJudgeCorrect">显示答案</el-checkbox>
        </div>
        <span class="link">
          <el-select v-model="lang" placeholder="请选择语言" size="mini" class="lang-select">
            <el-option v-for="item in langList" :key="item.type" :label="item.name" :value="item.type" />
          </el-select>
        </span>
        <div class="operator">
          <slot name="operator" :courseware="courseware_info"></slot>
        </div>
      </div>
    </div>

    <div class="audit-content">
      <!-- 左侧菜单栏 - 收缩 -->
      <aside v-if="navigationShow" class="left-menu">
        <div class="courseware-info">
          <div class="cover-image"></div>
          <div class="info-content">
            <div class="catalogue-icon">
              <SvgIcon icon-class="catalogue" size="54" />
            </div>
            <div class="courseware">
              <div class="name nowrap-ellipsis" :title="courseware_info.book_name">
                {{ courseware_info.book_name }}
              </div>
            </div>
          </div>
        </div>
        <!-- 教材章节树 -->
        <div class="courseware-tree">
          <div
            v-for="{ id: nodeId, name, deep, is_leaf_chapter } in node_list"
            :key="nodeId"
            :class="['menu-item', { active: curSelectId === nodeId }, { courseware: isTrue(is_leaf_chapter) }]"
            :style="computedNameStyle(deep, isTrue(is_leaf_chapter))"
            @click="selectChapterNode(nodeId, isTrue(is_leaf_chapter))"
          >
            <span class="name nowrap-ellipsis" :title="name">
              {{ name }}
            </span>
          </div>
        </div>
      </aside>

      <div ref="previewMain" class="main-container">
        <div v-if="!navigationShow" class="catalogue-bar">
          <SvgIcon icon-class="catalogue" size="54" />
        </div>

        <main :class="['preview-main']">
          <div class="preview-left"></div>
          <CoursewarePreview
            v-if="courseware_info.book_name"
            ref="courserware"
            :is-show-group="isShowGroup"
            :group-show-all="groupShowAll"
            :group-row-list="content_group_row_list"
            :data="data"
            :component-list="component_list"
            :background="background"
            :can-remark="isTrue(courseware_info.is_my_audit_task) && isTrue(courseware_info.is_can_add_audit_remark)"
            :show-remark="false"
            :component-remark-obj="remark_list_obj"
            @computeScroll="computeScroll"
          />
          <div class="preview-right"></div>
        </main>
      </div>

      <div class="back-top" @click="backTop">
        <img :src="require(`@/assets/icon/back-top.png`)" alt="返回顶部" />
      </div>
    </div>
  </div>
</template>

<script>
import CoursewarePreview from '@/views/book/courseware/preview/CoursewarePreview.vue';
import { isTrue } from '@/utils/validate';
import * as OpenCC from 'opencc-js';

import { GetBookCoursewareInfo, GetCoursewareAuditRemarkList } from '@/api/project';
import {
  ContentGetCoursewareContent_View,
  ChapterGetBookChapterStructExpandList,
  GetBookBaseInfo,
  GetLanguageTypeList,
  GetBookUnifiedAttrib,
} from '@/api/book';

export default {
  name: 'CommonPreview',
  components: {
    CoursewarePreview,
  },
  provide() {
    return {
      getLang: () => this.lang,
      getChinese: () => this.chinese,
      getLangList: () => this.langList,
      convertText: this.convertText,
    };
  },
  data() {
    return {
      book_id: this.$route.query.book_id || '',
      select_node: '',
      courseware_info: {
        book_name: '',
        is_can_start_edit: 'false',
        is_can_submit_audit: 'false',
        is_can_audit_pass: 'false',
        is_can_audit_reject: 'false',
        is_can_add_audit_remark: 'false',
        is_can_finish_audit: 'false',
        is_can_request_shangjia_book: 'false',
        is_can_request_rollback_project: 'false',
        is_can_shangjia_book: 'false',
        is_can_rollback_project: 'false',
      },
      background: {
        background_image_url: '',
        background_position: {
          left: 0,
          top: 0,
        },
      },
      node_list: [],
      data: { row_list: [] },
      component_list: [],
      content_group_row_list: [],
      remark_list: [],
      remark_list_obj: {}, // 存放以组件为对象的数组
      visible: false,
      remark_content: '',
      submit_loading: false,
      isTrue,
      isShowGroup: false,
      groupShowAll: true,
      opencc: OpenCC.Converter({ from: 'cn', to: 'tw' }),
      langList: [],
      lang: 'ZH',
      chinese: 'zh-Hans',
      isJudgeCorrect: false,
      isShowAnswer: false,
      unified_attrib: {},
      curSelectId: this.id,
      navigationShow: true,
    };
  },
  watch: {
    isJudgeCorrect(newVal) {
      if (!newVal) {
        this.isShowAnswer = false;
      }
      this.simulateAnswer(newVal);
    },
    isShowAnswer() {
      this.simulateAnswer();
    },
  },
  created() {
    this.getBookBaseInfo();
    this.getBookChapterStructExpandList();
    this.getBookUnifiedAttr();
  },
  methods: {
    getBookBaseInfo() {
      GetBookBaseInfo({ id: this.book_id }).then(({ book_info }) => {
        this.courseware_info = { ...this.courseware_info, ...book_info, book_name: book_info.name };
      });
    },

    /**
     * 得到教材课件信息
     * @param {string} id - 课件ID
     */
    getBookCoursewareInfo(id) {
      GetBookCoursewareInfo({ id, is_contain_producer: 'true', is_contain_auditor: 'true' }).then(
        ({ courseware_info }) => {
          this.courseware_info = { ...this.courseware_info, ...courseware_info };
          this.getLangList();
        },
      );
    },
    /**
     * 得到课件内容（展示内容）
     * @param {string} id - 课件ID
     */
    getCoursewareComponentContent_View(id) {
      ContentGetCoursewareContent_View({ id }).then(({ content, component_list, content_group_row_list }) => {
        if (content) {
          const _content = JSON.parse(content);
          this.data = _content;
          this.background = {
            background_image_url: _content.background_image_url,
            background_position: _content.background_position,
          };
        } else {
          this.data = { row_list: [] };
        }

        if (component_list) this.component_list = component_list;
        if (content_group_row_list) this.content_group_row_list = JSON.parse(content_group_row_list) || [];
      });
    },

    getLangList() {
      GetLanguageTypeList({ book_id: this.courseware_info.book_id, is_contain_zh: 'true' }).then(
        ({ language_type_list }) => {
          this.langList = language_type_list;
        },
      );
    },

    /**
     * 得到教材章节结构展开列表
     */
    getBookChapterStructExpandList() {
      ChapterGetBookChapterStructExpandList({
        book_id: this.book_id,
        node_deep_mode: 0,
        is_contain_producer: 'true',
        is_contain_auditor: 'true',
      }).then(({ node_list }) => {
        this.node_list = node_list;
      });
    },

    getBookUnifiedAttr() {
      GetBookUnifiedAttrib({ book_id: this.book_id }).then(({ content }) => {
        if (content) {
          this.unified_attrib = JSON.parse(content);
        }
      });
    },

    /**
     * 选择节点
     * @param {string} nodeId - 节点ID
     */
    selectNode(nodeId) {
      this.getCoursewareComponentContent_View(nodeId);
      this.getBookCoursewareInfo(nodeId);
      this.getCoursewareAuditRemarkList(nodeId);
      this.select_node = nodeId;
    },
    // 审校批注列表
    getCoursewareAuditRemarkList(id) {
      this.remark_list = [];
      let remarkListObj = {};
      GetCoursewareAuditRemarkList({
        courseware_id: id,
      }).then(({ remark_list }) => {
        this.remark_list = remark_list;
        if (!remark_list) return;
        remarkListObj = remark_list.reduce((acc, item) => {
          if (!acc[item.component_id]) {
            acc[item.component_id] = [];
          }
          acc[item.component_id].push(item);
          return acc;
        }, {});

        this.remark_list_obj = remarkListObj;
      });
    },
    dialogClose(type) {
      this[`visible${type}`] = false;
    },
    // 计算previewMain滑动距离
    computeScroll() {
      this.$refs.courserware.handleResult(
        this.$refs.previewMain.scrollTop,
        this.$refs.previewMain.scrollLeft,
        this.select_node,
      );
    },

    /**
     * 文本转换
     * @param {string} text - 要转换的文本
     * @returns {string} - 转换后的文本
     */
    convertText(text) {
      if (this.chinese === 'zh-Hant' && this.opencc) {
        return this.opencc(text);
      }
      return text;
    },

    simulateAnswer(disabled = true) {
      this.$refs.courserware.simulateAnswer(this.isJudgeCorrect, this.isShowAnswer, disabled);
    },

    /**
     * 选择节点
     * @param {string} nodeId - 节点ID
     * @param {boolean} isLeaf - 是否是叶子节点
     */
    selectChapterNode(nodeId, isLeaf) {
      if (!isLeaf) return;
      if (this.curSelectId === nodeId) return;
      this.curSelectId = nodeId;
      this.selectNode(nodeId);
    },
    /**
     * 计算章节名称样式
     * @param {number} deep - 节点深度
     * @param {boolean} isLeaf - 是否是叶子节点
     * @returns {Object} - 样式对象
     */
    computedNameStyle(deep, isLeaf) {
      return {
        'padding-left': `${(deep - 1) * 8}px`,
        cursor: isLeaf ? 'pointer' : 'auto',
      };
    },
    /**
     * 切换左侧导航栏显示与隐藏
     */
    toggleNavigationShow() {
      this.navigationShow = !this.navigationShow;
    },

    backTop() {
      this.$refs.previewMain.scrollTo({
        top: 0,
        left: 0,
        behavior: 'smooth',
      });
    },
  },
};
</script>

<style lang="scss" scoped>
@use '@/styles/mixin.scss' as *;

$total-width: $courseware-width + $courseware-left-margin + $courseware-right-margin;

.common-preview {
  &__header {
    position: sticky;
    top: 0;
    left: 0;
    z-index: 9;
    display: flex;
    align-items: center;
    height: 40px;
    padding: 6px 4px;
    margin-bottom: 5px;
    background-color: #fff;
    border-top: $border;
    border-bottom: $border;

    > .courseware {
      display: flex;
      flex-grow: 1;
      column-gap: 16px;
      align-items: center;
      justify-content: space-between;
      height: 40px;

      .lang-select {
        :deep .el-input {
          width: 100px;
        }

        :deep .el-input__inner {
          height: 24px;
          line-height: 24px;
          background-color: #fff;
        }

        :deep .el-input__icon {
          line-height: 24px;
        }
      }

      .flow-nodename {
        flex: 1;
      }

      .group {
        display: flex;
        align-items: center;
      }

      .operator {
        display: flex;
        column-gap: 8px;
        align-items: center;

        .link {
          + .link {
            margin-left: 0;

            &::before {
              margin-right: 8px;
              color: #999;
              content: '|';
            }
          }
        }
      }
    }
  }

  .main-container {
    position: relative;
    flex: 1;
    min-width: 1110px;
    padding: 15px 0;
    overflow: auto;
    background: url('@/assets/preview-bg.png') repeat;

    .catalogue-bar {
      display: flex;
      align-items: center;
      justify-content: center;
      width: 54px;
      height: 54px;
      margin: -9px 6px 0 240px;
      cursor: pointer;
      background-color: #fff;
      border-radius: 2px;
      box-shadow: 0 2px 6px 0 rgba(0, 0, 0, 40%);
    }
  }

  .back-top {
    position: absolute;
    right: 24px;
    bottom: 0;
    display: flex;
    place-content: center center;
    align-items: center;
    width: 60px;
    height: 60px;
    cursor: pointer;
    background-color: #fff;
  }

  main.preview-main {
    display: flex;
    flex: 1;
    width: calc($total-width);
    min-width: calc($total-width);
    max-width: calc($total-width);
    min-height: 100%;
    margin: 0 auto;
    background-color: #fff;
    border-radius: 4px;
    box-shadow: 0 2px 6px 0 rgba(0, 0, 0, 40%);

    .preview-left {
      width: $courseware-left-margin;
      min-width: $courseware-left-margin;
      max-width: $courseware-left-margin;
      background-color: #f9f9f9;
    }

    .preview-right {
      width: $courseware-right-margin;
      min-width: $courseware-right-margin;
      max-width: $courseware-right-margin;
      background-color: #f9f9f9;
    }

    &.no-audit {
      margin: 0 auto;
    }
  }

  .audit-content {
    display: flex;
    min-width: 1400px;
    height: calc(100vh - 46px);

    .left-menu {
      display: flex;
      flex-direction: column;
      width: $catalogue-width;
      font-family: 'Microsoft YaHei', 'Arial', sans-serif;
      background-color: #fff;

      .courseware-info {
        display: flex;
        column-gap: 18px;
        width: 100%;
        height: 186px;
        padding: 6px 6px 24px;
        border-bottom: $border;

        .cover-image {
          width: 111px;
          height: 157px;
          background-color: rgba(229, 229, 229, 100%);
        }

        .info-content {
          display: flex;
          flex-direction: column;
          justify-content: space-between;

          .catalogue-icon {
            text-align: right;

            .svg-icon {
              cursor: pointer;
            }
          }

          .courseware {
            width: 159px;
            height: 64px;
            font-size: 16px;

            .name {
              font-weight: bold;
            }
          }
        }
      }

      .courseware-tree {
        display: flex;
        flex: 1;
        flex-direction: column;
        row-gap: 8px;
        padding: 12px;
        margin-top: 12px;
        overflow: auto;

        .menu-item {
          display: flex;
          align-items: center;

          &:not(.courseware) {
            font-weight: bold;
          }

          &.courseware {
            &:hover {
              .name {
                background-color: #f3f3f3;
              }
            }
          }

          .svg-icon {
            margin-left: 4px;

            &.my-edit-task {
              color: $right-color;
            }
          }

          .name {
            flex: 1;
            padding: 4px 8px 4px 4px;
            border-radius: 4px;
          }

          &.active {
            .name {
              font-weight: bold;
              color: #4095e5;
            }
          }
        }
      }
    }
  }
}
</style>

<style lang="scss">
.tox-tinymce-aux {
  z-index: 9999 !important;
}
</style>
