<script>
import {getBook, getBookContent, getBookListOfRecommend, setBookStatus} from '@/api/knowledge.js';
import {getDataByKey} from '@/api/system';
import {mapGetters} from 'vuex';
import printJS from 'print-js';


export default {
  name: 'KnowledgeBookDetail',
  data() {
    return {
      showPrintHTML: false,
      book: {id: '', catalogueList: []},
      section: [],
      recommend: [],

      containerHeight: 0,

      selected: {},
    };
  },
  computed: {
    collection() {
      return +this.book['isBookshelf'] === 1;
    },
    ...mapGetters(["getuserinfo"]),
  },
  created() {
    this.book.id = this.$route.query.id;
    this.onPreview();
    getDataByKey({
      key: "showPrintHTML",
      organizationid: this.getuserinfo.organizationid,
    }).then(data => { this.showPrintHTML = data.enabled; });
  },
  mounted() {
    setTimeout(() => {
      try { this.containerHeight = `${this.$el.parentElement.getBoundingClientRect().height - 10}px`; } catch (e) { }
    }, 200);
  },
  methods: {
    async getRecommend() {
      try {
        this.recommend = await getBookListOfRecommend(this.book.id);
      } catch (e) {}
    },
    async getBook() {
      this.book = await getBook(this.book.id);
      let selected;
      const get = (list, level = 1) => list.map(item => {
        const children = Array.isArray(item.children) ? get(item.children, level + 1) : [];
        const isLeaf = !children.length;
        const section = {
          id: item.catalogueId,
          name: item.catalogueName,
          children, isLeaf, level,
          content: isLeaf ? '' : void 0,
          dirty: !isLeaf,
        }
        if (section.isLeaf && !selected) selected = section;
        return section;
      });
      this.section = get(this.book.catalogueList);
      await this.load(selected);
    },
    async load(section) {
      if (!section.isLeaf) return;

      this.selected = {...section};
      if (!section.dirty) {
        try {
          section.content = await getBookContent({bookId: this.book.id, catalogueId: section.id});
          section.dirty = true;
          this.$set(this.selected, 'content', section.content);
          this.$set(this.selected, 'dirty', section.dirty);
        } catch (e) {}
      }
      this.$nextTick(() => {
        document.querySelector(`#scrolling`).scrollTo({top: 0, behavior: 'smooth'});
      });
    },
    async collected() {
      try {
        const isBookshelf = this.collection ? '0' : '1';
        await setBookStatus(this.book.id, {isBookshelf});
        this.$set(this.book, 'isBookshelf', isBookshelf);
        this.$message.success('操作成功');
      } catch (e) {

      }
    },
    async onPreview(book) {
      if (book) {
        await this.$router.push({path: `/index/knowledge/book/detail?id=${book.id}`});
        this.book = book;
      }
      try {
        await this.getBook();
        await this.getRecommend();
      } catch (e) {

      }
    },
    async print(object) {
      console.log(object);
      printJS({
        printable: this.$refs.print,
        type: 'html',
        header: object.name,
        documentTitle: `名医名方 - 经典医书`,
        scanStyles: false,
        css: ['print/containers.css'],
        style: `.text { line-height: 2.5; }`
      })
    }
  },
};
</script>

<template>
  <div class="knowledge-book-detail" :style="{height: containerHeight}">
    <div class="detail-wrapper">
      <div class="header">
        <div class="book-wrapper">
          <div class="cover">
            <div class="name">{{ book.bookName }}</div>
          </div>
        </div>
        <div class="description-wrapper">
          <div>
            <div style="margin-bottom: 6px;font-size: 18px;font-weight: 700;">{{ book.bookName }}</div>
            <div class="content">
              <span v-if="book.dynasty">{{ book.dynasty }} · </span>
              <span>{{ book.author || '佚名' }}</span>
            </div>
          </div>
          <div style="text-indent: 2em;">{{ book.briefIntroduction }}</div>
          <el-button type="primary" plain round size="small" :icon="collection ? 'el-icon-remove-outline' : 'el-icon-circle-plus-outline'" @click="collected()">
            {{ collection ? '移出' : '加入' }}书架
          </el-button>
        </div>
      </div>
      <el-divider content-position="left">阅读<span v-if="book.readProgress">：{{ book.readProgress }}%</span>
      </el-divider>
      <div class="book-content-container" :style="{maxHeight: containerHeight}" :class="{scrollable: true}">
        <div class="catalogue">
          <div v-for="item in section" :key="item.id"
               :class="['level-' + item.level, item.isLeaf ? 'section' : 'title']">
            <span :class="{active: item.id === selected.id}" @click="load(item)">{{ item.name }}</span>
            <div v-for="item in item.children" :key="item.id"
                 :class="['level-' + item.level, item.isLeaf ? 'section' : 'title']">
              <span :class="{active: item.id === selected.id}" @click="load(item)">{{ item.name }}</span>
            </div>
          </div>
        </div>
        <div class="content" id="scrolling" :style="{height: containerHeight}" v-loading="!selected.dirty">
          <el-tooltip content="下载打印">
            <el-button class="print-btn" size="small" v-if="showPrintHTML" type="primary" circle icon="el-icon-download" :disabled="!selected.dirty" @click="print(selected)"></el-button>
          </el-tooltip>
          <div class="text print-containers" ref="print" v-html="selected.content"></div>
          <el-backtop style="right: 300px;" target="#scrolling"></el-backtop>
        </div>
      </div>
    </div>
    <el-card header="相关医书">
      <div class="book-wrapper" style="margin-bottom: 24px;" v-for="book in recommend" :key="book.id"
           @click="onPreview(book)">
        <div class="cover">
          <div class="name">{{ book.bookName }}</div>
        </div>
        <div class="content" style="font-weight: 700;">{{ book.bookName }}</div>
        <div class="content">
          <span v-if="book.dynasty">{{ book.dynasty }}</span>
          <span>{{ book.author || '佚名' }}</span>
        </div>
      </div>
    </el-card>
  </div>
</template>

<style lang="scss" scoped>
.knowledge-book-detail {
  display: flex;
  overflow: hidden;

  .detail-wrapper {
    flex: auto;
    overflow-y: auto;
    height: 100%;
    padding: 0 24px;

    .header {
      display: flex;
    }

    .description-wrapper {
      display: flex;
      flex-direction: column;
      justify-content: space-evenly;
      margin-left: 24px;

      .el-button {
        max-width: 120px;
      }
    }
  }

  .el-card {
    flex: none;
    display: flex;
    flex-direction: column;
    width: 262px;
    overflow: hidden;

    &::v-deep {
      .el-card__header {
        flex: none;
      }

      .el-card__body {
        flex: auto;
        overflow-y: auto;
      }
    }
  }

  .el-divider {
    &::v-deep {
      .el-divider__text {
        background-color: #f5f7f9;
      }
    }
  }
}

.knowledge-book-detail {
  &::v-deep {
    .el-collapse-item__header {
      padding-left: 12px;
    }

    .el-collapse-item__content {
      padding-bottom: 6px;
    }

    .el-collapse-item__wrap {
      padding: 6px 12px;
    }
  }
}

.book-content-container {
  display: flex;

  &.scrollable > div {
    overflow-y: auto;
  }

  .catalogue {
    flex: 1 0;
    user-select: none;


    .title {
      margin: 24px 0;
      color: #213547;
      > span {
        pointer-events: none;
      }
    }

    .section {
      margin: 6px 0;
      color: #3c3c3cb3;

      &:hover, .active {
        cursor: pointer;
        color: #5386f6;
      }
    }
  }

  .content {
    position: relative;
    flex: 4 4;

    > .text {
      padding: 24px;
      line-height: 2.5;
      white-space: pre-wrap;
    }

    .print-btn {
      position: absolute;
      top: 0;
      right: 0;
    }
  }

  ::v-deep.el-loading-mask {
    background-color: transparent;
  }
}

.book-wrapper {
  $zoom: 0.6;
  cursor: pointer;

  .cover {
    position: relative;
    width: 272px * $zoom;
    height: 400px * $zoom;
    background: url("../../assets/book-cover.png") no-repeat center / 100%;
  }

  .name {
    position: absolute;
    top: 30px * $zoom;
    right: 40px * $zoom;
    display: flex;
    justify-content: center;
    align-items: center;
    width: 48px * $zoom;
    height: 234px * $zoom;
    font-size: max(24px * $zoom, 12px);
    font-weight: 700;
    letter-spacing: 0.3em;
    -ms-writing-mode: tb-rl;
    writing-mode: vertical-rl;
  }

  .content {
    margin: 8px 0;
    font-size: 16px;
    span + span::before {
      content: '·';
      margin: 0 3px;
    }
  }
}
</style>