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

          <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" /><span>预览</span>
          <el-button type="primary"><SvgIcon icon-class="save" />保存</el-button>
        </el-button>
      </div>
    </div>

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

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

import CatalogueTree from './components/catalogueTree.vue';

export default {
  name: 'ChapterPage',
  components: {
    CatalogueTree,
  },
  provide() {
    return {
      selectNode: this.selectNode,
    };
  },
  data() {
    const { book_id, chapter_id } = this.$route.query;
    return {
      chapter_id,
      book_id,
      visibleStatus: false,
      curPosition: [],
      nodes: [],
      courseware_list: [],
    };
  },
  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}`);
    },
    enterCourseware(courseware_id) {
      this.$router.push({
        path: `/courseware/create/${courseware_id}`,
        query: { book_id: this.book_id, chapter_id: this.chapter_id },
      });
    },
    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 ?? [];
      });
    },
    /**
     * 根据节点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.visibleStatus = false;
    },
    addCoursewareToBook() {
      AddCoursewareToBook({ book_id: this.book_id, chapter_id: this.chapter_id, name: '教材内容' }).then(() => {
        this.getCoursewareList_Chapter(this.chapter_id);
        this.$message.success('添加成功');
      });
    },
    deleteCourseware(id) {
      this.$confirm('是否删除该教材内容？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          DeleteCourseware({ id })
            .then(() => {
              this.getCoursewareList_Chapter(id);
              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;
          }
        }
      }
    }
  }

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

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

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

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

    .tip {
      display: flex;
      align-items: center;
      justify-content: center;
      width: 100%;
      height: calc(100% - 42px);
      font-size: 14px;
      font-weight: bold;
      color: #000;
    }
  }
}
</style>
