<script>
import {getBook, getBookContent, getBookListOfRecommend, setBookStatus} from '@/api/knowledge.js';
import {numberToChinese} from '@/utils/format';

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

      containerHeight: 0,
    };
  },
  computed: {
    collection() {
      return +this.book['isBookshelf'] === 1;
    },
  },
  created() {
    this.book.id = this.$route.query.id;
    this.onPreview();
  },
  mounted() {
    setTimeout(() => {
      try { this.containerHeight = `${this.$el.parentElement.getBoundingClientRect().height - 10}px`; } catch (e) { }
    }, 200);
  },
  methods: {
    async getBook() {
      this.book = await getBook(this.book.id);
      let index = 1;
      const section = [];
      for (const {catalogueName: name, catalogueId: id} of this.book.catalogueList) {
        section.push({
          id,
          name: name === '序' ? name : `第${numberToChinese(index)}章 ${name}`,
          content: '',
          dirty: false,
        });
        if (name !== '序') { index += 1;}
      }
      this.section = section;
    },
    async getRecommend() {
      try {
        this.recommend = await getBookListOfRecommend(this.book.id);
      } catch (e) {}
    },
    async getContent(data, index, section) {
      try {
        let content = await getBookContent({bookId: this.book.id, catalogueId: data.id});
        content = `&emsp;&emsp;${(content || '').replace(/\n|\r/g, '<br>&emsp;&emsp;')}`;
        this.$set(this.section, index, Object.assign(data, {dirty: true, error: '', content}));
      } catch (e) {
        this.$set(this.section, index, Object.assign(data, {dirty: true, error: `出错了(${e})`}));
      }
    },
    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) {

      }
    },
    load(ids) {
      if (ids && !Array.isArray(ids)) {ids = [ids];}
      for (const id of ids) {
        const index = this.section.findIndex(item => item.id === id);
        const data = this.section[index];
        if (data.dirty || data.content) continue;
        this.$set(this.section, index, Object.assign(data, {dirty: true, error: ''}));
        this.getContent(data, index, this.section);
      }
    },
    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) {

      }
    },
  },
};
</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>
      <el-collapse style="margin: 0 12px;" @change="load">
        <el-collapse-item v-for="item in section" :key="item.id" :title="item.name" :name="item.id">
          <div class="book-content-container" v-loading="!item.content">
            <div v-html="item.content"></div>
          </div>
        </el-collapse-item>
      </el-collapse>
      <el-backtop style="right: 300px;" target=".detail-wrapper"></el-backtop>
    </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;
    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 {
  min-height: 80px;
}

.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>