<script>
import useScroll from '@/mixins/useScroll';
import {getBookCategories, getBookList, getBookListOfMy} from '@/api/knowledge';

export default {
  name: 'KnowledgeBook',
  mixins: [useScroll],
  data() {
    return {
      categories: [],
      books: [],
      query: {
        index: '',
        keyWord: '',
        page: 1,
      },

      keyword: '',
      loading: false,
      searched: false,
      containerHeight: 0,
    };
  },
  created() {
    this.list();
    this.getCategories();
  },
  mounted() {
    setTimeout(() => {
      try { this.containerHeight = `${this.$el.parentElement.getBoundingClientRect().height - 10}px`; } catch (e) { }
    }, 500);
    this.onActivated();
  },
  methods: {
    onActivated() {
      this.__activated__ = true;
      const menus = this.$refs.menus.$el;
      if (menus) {
        menus.querySelector('.el-menu-item.is-active').scrollIntoView({behavior: 'smooth', block: 'center'});
      }
    },
    async getCategories() {
      const categories = await getBookCategories().catch(() => []);
      this.categories = [{label: '我的书架', value: -1}, ...categories];
    },
    async list() {
      let loading;
      if (this.query.page === 1) {
        this.loading = true;
        loading = this.$loading({
          lock: true,
          text: '拼命加载中',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)',
        });
      }
      try {
        const {index, ...query} = this.query;
        const classifyId = (this.categories[index] || {value: ''}).value;
        const result = classifyId === -1 ? await getBookListOfMy() : await getBookList({
          ...query,
          classifyId,
        });
        this.query.page = result.page;
        this.query.total = result.total;
        const books = this.query.page === 1 ? [] : this.books;
        this.books = [...books, ...result.data];
      } catch (error) {}
      this.loading = false;
      if (loading) loading.close();
      if (this.query.page === 1) { setTimeout(() => { this.scroll(0); }, 200); }
    },
    load() {
      if (this.books.length >= this.query.total) return;
      this.query.page += 1;
      this.list();
    },
    onSearch() {
      try {if (this.categories[this.query.index].value === -1) {this.query.index = '';}} catch (e) { }
      this.query.keyWord = this.keyword;
      this.query.page = 1;
      this.list();
      this.searched = !!this.query.keyWord;
    },
    onselect(index) {
      index = index.toString();
      this.query.index = index === this.query.index ? '' : index;
      this.query.page = 1;
      this.list();
    },
    onPreview(book) {
      this.$router.push({path: `/index/knowledge/book/detail?id=${book.id}`});
    },
  },
};
</script>

<template>
  <div class="knowledge-book-list" :style="{height: containerHeight}">
    <el-row style="height: 100%;overflow: hidden;">
      <el-col style="height: 100%;overflow: hidden;" :sm="4" :xl="3">
        <el-menu ref="menus" style="height: 100%;overflow-y: auto" :default-active="query.index">
          <el-menu-item v-for="(item, index) in categories" :key="item.value" :index="index + ''"
                        style="font-size: 18px;"
                        @click="onselect(index)">
            <span slot="title">{{ item.label }}</span>
          </el-menu-item>
        </el-menu>
      </el-col>
      <el-col style="height: 100%;overflow: hidden;display: flex;flex-direction: column;" :sm="20" :xl="21">
        <div class="search-wrapper" style="flex: none;">
          <el-input clearable placeholder="输入书名、作者、朝代" v-model="keyword"
                    @clear="searched && onSearch()"
                    @keyup.enter.native="onSearch()"></el-input>
          <el-button type="primary" @click="onSearch()">查询</el-button>
        </div>
        <el-row ref="scrollableElement" class="books-wrapper" style="flex: auto;" v-infinite-scroll="load">
          <el-empty v-if="!books.length" description="暂无数据"></el-empty>
          <el-col v-for="(book, index) in books" :key="book.id" :sm="8" :xl="6">
            <div class="book-wrapper" @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 style="min-height: 32px;">
                <el-tag v-if="book.readProgress">已读 {{ book.readProgress }}%</el-tag>
              </div>
            </div>
          </el-col>
        </el-row>
      </el-col>
    </el-row>
  </div>
</template>

<style scoped lang="scss">
.knowledge-book-list {
  overflow: hidden;
}

.search-wrapper {
  display: flex;
  justify-content: center;
  padding: 12px 0;

  .el-input {
    max-width: 300px;

    &::v-deep .el-input__inner {
      border-top-right-radius: 0;
      border-bottom-right-radius: 0;
    }

    + .el-button {
      border-top-left-radius: 0;
      border-bottom-left-radius: 0;
    }
  }
}

.books-wrapper {
  height: 100%;
  overflow-y: auto;
  .book-wrapper {
    padding: 24px;
  }
}

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