<template>
  <div class="preview">
    <div class="menu">
      <div class="title">目录</div>
      <CatalogueTree :nodes="nodes" />
    </div>

    <div class="content-wrapper">
      <div class="exit">
        <el-button icon="el-icon-close" @click="goBack">退出预览</el-button>
      </div>
      <template v-for="(data, index) in coursewareDataList">
        <div v-if="data.hasOwnProperty('row_list')" :key="`data-${index}`" class="content">
          <span class="content-title">
            <SvgIcon icon-class="menu-2" size="24" />
            <template v-for="(item, m) in menuList">
              <span :key="m">{{ item }}</span>
              <span v-if="m < menuList.length - 1" :key="`separator-${m}`" class="separator">/</span>
            </template>
          </span>
          <CoursewarePreview :data="data" />
        </div>
      </template>
    </div>
  </div>
</template>

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

import CatalogueTree from '@/views/book/components/catalogueTree.vue';
import CoursewarePreview from './CoursewarePreview.vue';

export default {
  name: 'PreviewPage',
  components: {
    CatalogueTree,
    CoursewarePreview,
  },
  provide() {
    return {
      selectNode: this.selectNode,
      getCurChapterId: () => this.curChapterId,
    };
  },
  data() {
    const { chapter_id } = this.$route.query;
    return {
      book_id: this.$route.params.book_id,
      chapter_id,
      curChapterId: chapter_id,
      nodes: [],
      curPosition: [],
      courseware_list: [],
      coursewareDataList: [],
    };
  },
  computed: {
    menuList() {
      return this.curPosition.map((item, index) => this.getNodeName(index));
    },
  },
  created() {
    GetBookChapterStruct({ book_id: this.book_id, node_deep_mode: 0 }).then(({ nodes }) => {
      this.nodes = nodes ?? [];
      if (this.chapter_id) this.setCurPosition(this.chapter_id);
    });
    if (this.chapter_id) this.getCoursewareList_Chapter(this.chapter_id);
  },
  methods: {
    goBack() {
      let chapterId = this.chapter_id || this.curChapterId;
      this.$router.push(`/chapter?chapter_id=${chapterId}&book_id=${this.book_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;
    },
    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 {};
        }),
      );
    },
    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;
    },
    getMultipleColStyle(index, i) {
      let row = this.coursewareDataList[index].row_list[i];
      let col = row.col_list;
      if (col.length <= 1) {
        return {
          gridTemplateColumns: '100fr',
        };
      }
      let gridTemplateColumns = row.width_list.join(' ');

      return {
        gridAutoFlow: 'column',
        gridTemplateColumns,
        gridTemplateRows: 'auto',
      };
    },
    /**
     * 分割整数为多个 1的倍数
     * @param {number} num
     * @param {number} parts
     */
    splitInteger(num, parts) {
      let base = Math.floor(num / parts);
      let arr = Array(parts).fill(base);
      let remainder = num - base * parts;
      for (let i = 0; remainder > 0; i = (i + 1) % parts) {
        arr[i] += 1;
        remainder -= 1;
      }
      return arr;
    },
    computedColStyle(col) {
      const grid = col.grid_list;

      let maxCol = 0; // 最大列数
      let rowList = new Map();
      grid.forEach(({ row }) => {
        rowList.set(row, (rowList.get(row) || 0) + 1);
      });
      let curMaxRow = 0; // 当前数量最大 row 的值
      rowList.forEach((value, key) => {
        if (value > maxCol) {
          maxCol = value;
          curMaxRow = key;
        }
      });
      // 计算 grid_template_areas
      let gridTemplateAreas = '';
      let gridArr = [];
      grid.forEach(({ grid_area, row }) => {
        if (!gridArr[row - 1]) {
          gridArr[row - 1] = [];
        }
        if (curMaxRow === row) {
          gridArr[row - 1].push(`${grid_area}`);
        } else {
          let filter = grid.filter((item) => item.row === row);
          let find = filter.findIndex((item) => item.grid_area === grid_area);
          let needNum = maxCol - filter.length; // 需要的数量

          let str = '';
          if (filter.length === 1) {
            str = ` ${grid_area} `.repeat(needNum + 1);
          } else {
            let arr = this.splitInteger(needNum, filter.length);
            str = arr[find] === 0 ? ` ${grid_area} ` : ` ${grid_area} `.repeat(arr[find] + 1);
          }
          gridArr[row - 1].push(`${str}`);
        }
      });
      gridArr.forEach((item) => {
        gridTemplateAreas += `'${item.join(' ')}' `;
      });

      // 计算 grid_template_columns
      let gridTemplateColumns = '';
      let max = { row: 0, num: 0 };
      grid.forEach(({ row }) => {
        // 计算出 row 的哪个值最多
        let len = grid.filter((item) => item.row === row).length;
        if (max.num < len) {
          max.num = len;
          max.row = row;
        }
      });
      grid.forEach((item) => {
        if (item.row === max.row) {
          gridTemplateColumns += `${item.width} `;
        }
      });

      // 计算 grid_template_rows
      let gridTemplateRows = '';
      // 将 grid 按照 row 分组
      let gridMap = new Map();
      grid.forEach((item) => {
        if (!gridMap.has(item.row)) {
          gridMap.set(item.row, []);
        }
        gridMap.get(item.row).push(item.height);
      });
      gridMap.forEach((value) => {
        if (value.length === 1) {
          gridTemplateRows += `${value[0]} `;
        } else {
          let isAllAuto = value.every((item) => item === 'auto'); // 是否全是 auto
          gridTemplateRows += isAllAuto ? 'auto ' : `max(${value.join(', ')}) `;
        }
      });

      return {
        width: col.width,
        gridTemplateAreas,
        gridTemplateColumns,
        gridTemplateRows,
      };
    },
  },
};
</script>

<style lang="scss" scoped>
.preview {
  display: flex;
  height: 100%;

  .menu {
    width: 240px;
    padding: 24px;
    overflow: auto;
    background-color: #fff;

    .title {
      margin-bottom: 16px;
      font-weight: bold;
    }

    :deep .node {
      &-name {
        height: 38px;
        line-height: 38px;

        &.content {
          padding-left: 16px;
          font-size: 14px;
          border-bottom: 1px solid $border-color;
        }
      }

      .node {
        padding-left: 20px;
        margin-left: 0;
      }
    }
  }

  .content-wrapper {
    flex: 1;
    padding: 24px 60px;
    overflow: auto;
    background: url('~@/assets/mask_group.png') repeat 0 0;

    .exit {
      position: sticky;
      top: 0;
      display: flex;
      justify-content: flex-end;

      .el-button {
        height: 40px;
        font-size: 16px;
        font-weight: bold;
        border-width: 0;
        box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 8%);
      }
    }

    .content {
      width: calc($courseware-width + 6px);
      margin: 24px auto 0;
      background-color: #fff;
      border: 3px solid #f44444;
      border-radius: 16px;

      &-title {
        display: inline-flex;
        column-gap: 24px;
        align-items: center;
        min-width: 280px;
        height: 64px;
        padding: 18px 24px;
        font-size: 20px;
        color: #fff;
        background-color: #f44444;
        border-top-left-radius: 12px;
        border-bottom-right-radius: 16px;
      }
    }
  }
}
</style>
