<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="index < menuList.length - 1" :key="`separator-${m}`" class="separator">/</span>
            </template>
          </span>
          <!-- 课件 -->
          <div
            class="courserware"
            :style="[
              {
                backgroundImage: data.background_image_url ? `url(${data.background_image_url})` : '',
                backgroundSize: data.background_image_url
                  ? `${data.background_position.width}% ${data.background_position.height}%`
                  : '',
                backgroundPosition: data.background_image_url
                  ? `${data.background_position.left}% ${data.background_position.top}%`
                  : '',
              },
            ]"
          >
            <template v-for="(row, i) in data.row_list">
              <div :key="i" class="row" :style="getMultipleColStyle(index, i)">
                <!-- 列 -->
                <template v-for="(col, j) in row.col_list">
                  <div :key="j" :class="['col', `col-${i}-${j}`]" :style="computedColStyle(col)">
                    <!-- 网格 -->
                    <template v-for="(grid, k) in col.grid_list">
                      <component
                        :is="previewComponentMap[grid.type]"
                        :id="grid.id"
                        ref="preview"
                        :key="k"
                        :courseware_id="data.courseware_id"
                        :class="[grid.id]"
                        :style="{
                          gridArea: grid.grid_area,
                          height: grid.height,
                        }"
                      />
                    </template>
                  </div>
                </template>
              </div>
            </template>
          </div>
        </div>
      </template>
    </div>
  </div>
</template>

<script>
import { GetCoursewareContent, GetBookChapterStruct, GetCoursewareList_Chapter } from '@/api/book';
import { previewComponentMap } from './components/common/data';

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

export default {
  name: 'PreviewPage',
  components: {
    CatalogueTree,
  },
  provide() {
    return {
      selectNode: this.selectNode,
      getCurChaterId: () => this.curChapterId,
    };
  },
  data() {
    const { chapter_id } = this.$route.query;
    return {
      book_id: this.$route.params.book_id,
      chapter_id,
      curChapterId: chapter_id,
      previewComponentMap,
      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() {
      this.$router.push(`/chapter?chapter_id=${this.chapter_id}&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;
    },
    getCatalogueName() {
      return this.curPosition.map((item, index) => this.getNodeName(index)).join(' / ');
    },
    getMultipleColStyle(index, i) {
      let row = this.coursewareDataList[index].row_list[i];
      let col = row.col_list;
      if (col.length <= 1) {
        return {
          gridTemplateColumns: '100%',
        };
      }
      let str = row.width_list
        .map((item) => {
          return `calc(${item} - ${(16 * (row.width_list.length - 1)) / row.width_list.length}px)`;
        })
        .join(' 16px ');
      let gridTemplateColumns = `${str}`;

      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) * 3; // 需要的数量

          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 rowOneNum = grid.filter((item) => item.row === 1).length;
      grid.forEach((item) => {
        if (item.row === 1) {
          gridTemplateColumns += `calc(${item.width} - ${((rowOneNum - 1) * 16) / rowOneNum}px) `;
        }
      });

      return {
        width: col.width,
        gridTemplateAreas,
        gridTemplateColumns,
        gridTemplateRows: `${grid.map(({ height }) => height).join(' ')}`,
      };
    },
  },
};
</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 {
      margin-top: 24px;
      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;
      }

      .courserware {
        display: flex;
        flex-direction: column;
        row-gap: 6px;
        width: 100%;
        min-height: 500px;
        padding: 24px;
        background-color: #fff;
        background-repeat: no-repeat;
        border-bottom-right-radius: 12px;
        border-bottom-left-radius: 12px;

        .row {
          display: grid;
          row-gap: 16px;

          .col {
            display: grid;
            gap: 16px;
          }
        }
      }
    }
  }
}
</style>
