<template>
  <div class="chapter">
    <div class="chapter-top">
      <div class="catalogue">
        <i class="el-icon-arrow-left pointer" @click="goBack"></i>
        <div class="name">
          <span>{{ getCatalogueName() }}</span>
        </div>
        <el-popover v-model="visibleStatus" placement="bottom" trigger="click">
          <CatalogueTree :nodes="nodes" />

          <span slot="reference" class="pointer"><SvgIcon icon-class="menu" /> 目录</span>
        </el-popover>
      </div>
      <div class="operation">
        <el-button type="primary" class="add" @click="addCoursewareToBook">
          <SvgIcon icon-class="artboard" /> 添加教材内容
        </el-button>
        <el-button class="preview">
          <SvgIcon icon-class="browse" @click="enterPreview" /><span @click="enterPreview">预览</span>
          <el-button type="primary"><SvgIcon icon-class="save" />保存</el-button>
        </el-button>
      </div>
    </div>

    <div class="content-wrapper">
      <div
        v-for="(data, i) in coursewareDataList"
        :key="data.courseware_id"
        class="book-content"
        @dblclick="enterCourseware(data.courseware_id, i)"
      >
        <div class="book-content-top">
          <span class="book-content-title">教材内容 {{ i + 1 }}</span>
          <SvgIcon icon-class="delete" @click="deleteCourseware(data.courseware_id)" />
          <SvgIcon icon-class="setup" />
        </div>
        <div v-if="data.hasOwnProperty('row_list')" class="content">
          <CoursewarePreview :data="data" />
        </div>
        <div v-else class="tip">
          <span>双击开始编辑教材内容 {{ i + 1 }}</span>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import {
  GetBookChapterStruct,
  GetCoursewareList_Chapter,
  AddCoursewareToBook,
  DeleteCourseware,
  GetCoursewareContent,
} from '@/api/book';

import CatalogueTree from './components/catalogueTree.vue';
import CoursewarePreview from './courseware/preview/CoursewarePreview.vue';

export default {
  name: 'ChapterPage',
  components: {
    CatalogueTree,
    CoursewarePreview,
  },
  provide() {
    return {
      selectNode: this.selectNode,
      getCurChapterId: () => this.curChapterId,
    };
  },
  data() {
    const { book_id, chapter_id } = this.$route.query;
    return {
      chapter_id,
      curChapterId: chapter_id, // 当前章节id
      book_id,
      visibleStatus: false,
      curPosition: [], // 当前位置
      nodes: [],
      courseware_list: [],
      coursewareDataList: [],
    };
  },
  created() {
    GetBookChapterStruct({ book_id: this.book_id, node_deep_mode: 0 }).then(({ nodes }) => {
      this.nodes = nodes ?? [];
      this.setCurPosition(this.chapter_id);
    });
    this.getCoursewareList_Chapter(this.chapter_id);
  },
  methods: {
    goBack() {
      this.$router.push(`/book/setting/${this.book_id}`);
    },
    enterPreview() {
      this.$router.push(`/preview/courseware/${this.book_id}?chapter_id=${this.curChapterId}`);
    },
    /**
     * 进入教材内容编辑页
     * @param {string} courseware_id 教材内容id
     * @param {number} index 教材内容索引
     */
    enterCourseware(courseware_id, index) {
      this.$router.push({
        path: `/courseware/create/${courseware_id}`,
        query: { book_id: this.book_id, chapter_id: this.chapter_id, index },
      });
    },
    getNodeName(index) {
      let node = this.nodes;
      for (let i = 0; i <= index; i++) {
        node = i === 0 ? node[this.curPosition[i]] : node.nodes[this.curPosition[i]];
      }
      return node?.name;
    },
    getCatalogueName() {
      return this.curPosition.map((item, index) => this.getNodeName(index)).join(' / ');
    },
    getCoursewareList_Chapter(chapter_id) {
      GetCoursewareList_Chapter({ chapter_id }).then(({ courseware_list }) => {
        this.courseware_list = courseware_list ?? [];
        this.getCoursewareContent();
      });
    },
    async getCoursewareContent() {
      this.coursewareDataList = await Promise.all(
        this.courseware_list.map(async ({ courseware_id }) => {
          const { content } = await GetCoursewareContent({ id: courseware_id });
          if (content) {
            let _content = JSON.parse(content);
            _content.courseware_id = courseware_id;
            return _content;
          }
          return {
            courseware_id,
          };
        }),
      );
    },
    /**
     * 根据节点id查找节点在nodes中的位置
     * @param {array} nodes 节点数组
     * @param {string} id 节点id
     * @param {array} position 节点位置
     */
    findNodeIndexById(nodes, id, position = []) {
      for (let i = 0; i < nodes.length; i++) {
        const node = nodes[i];
        if (node.id === id) {
          position.push(i);
          return position;
        }
        if (node.nodes && node.nodes.length > 0) {
          const childPosition = this.findNodeIndexById(node.nodes, id, [...position, i]);
          if (childPosition.length > 0) {
            return childPosition;
          }
        }
      }
      return [];
    },
    setCurPosition(id) {
      this.curPosition = this.findNodeIndexById(this.nodes, id);
    },
    selectNode(id) {
      this.setCurPosition(id);
      this.getCoursewareList_Chapter(id);
      this.curChapterId = id;
      this.visibleStatus = false;
    },
    addCoursewareToBook() {
      AddCoursewareToBook({
        book_id: this.book_id,
        chapter_id: this.curChapterId,
        name: `教材内容${this.coursewareDataList.length + 1}`,
      }).then(() => {
        this.getCoursewareList_Chapter(this.curChapterId);
        this.$message.success('添加成功');
      });
    },
    deleteCourseware(id) {
      this.$confirm('是否删除该教材内容？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          DeleteCourseware({ id })
            .then(() => {
              this.getCoursewareList_Chapter(this.curChapterId);
              this.$message.success('删除成功');
            })
            .catch(() => {
              this.$message.error('删除失败');
            });
        })
        .catch(() => {});
    },
  },
};
</script>

<style lang="scss" scoped>
.chapter {
  display: flex;
  flex-direction: column;
  row-gap: 16px;
  width: 100%;
  height: 100%;
  padding: 24px;
  background: url('~@/assets/mask_group.png') repeat 0 0;

  &-top {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 8px;

    .catalogue {
      display: flex;
      column-gap: 8px;
      align-items: center;
      min-width: 240px;
      height: 40px;
      padding: 8px 16px;
      font-size: 14px;
      font-weight: bold;
      background-color: #fff;
      border-radius: 4px;
      box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 8%);

      .name {
        flex: 1;
        margin-right: 6px;
      }
    }

    .operation {
      display: flex;

      .el-button {
        height: 40px;
        font-size: 16px;
        font-weight: bold;

        :deep > span {
          display: flex;
          column-gap: 4px;
          align-items: center;
        }
      }

      .preview {
        padding: 3px;

        :deep > span {
          padding-left: 12px;

          > .el-button {
            height: 32px;
            margin-left: 12px;
          }
        }
      }
    }
  }

  .content-wrapper {
    overflow: auto;

    .book-content {
      display: flex;
      flex-direction: column;
      min-height: 550px;
      padding: 8px 12px;
      cursor: pointer;
      background: rgba(241, 246, 255, 44%);
      border: 1px solid #005aff;
      border-radius: 4px;

      & + .book-content {
        margin-top: 16px;
      }

      &-top {
        display: flex;
        column-gap: 8px;
        align-items: center;

        .book-content-title {
          font-size: 14px;
          font-weight: bold;
          color: #1c6cff;
        }

        .svg-icon {
          color: #babbbe;
        }
      }

      .content {
        display: flex;
        justify-content: center;
        margin: 24px;
      }

      .tip {
        display: flex;
        flex: 1;
        align-items: center;
        justify-content: center;
        font-size: 14px;
        font-weight: bold;
        color: #000;
      }
    }
  }
}
</style>
