<template>
  <div class="book-stock">
    <x-header></x-header>
    <div class="book-stock-search">
      <div class="x-input--search2">
        <img class="x-input__icon"
             src="../assets/搜索.png">
        <input class="x-input__inner"
               placeholder="请输入书名/主角"
               v-model="selected.key"
               type="text">
      </div>
      <div class="book-stock-search__btn">
        <input class="x-input--button"
               @click="limitChange('key')"
               type="button"
               value="搜索">
      </div>
    </div>
    <div :class="['book-stock-limit',{'is-close': !limitStatus}]"
         ref="limit"
         v-show="books.length>0">
      <template v-for="(type,i) in limit">
        <dl v-if="type.children"
            class="book-stock-limit__type"
            :key="type.value">
          <dt class="book-stock-limit__label">{{type.label}}</dt>
          <dd class="book-stock-limit__values">
            <v-touch v-for="(v,i) in type.children"
                     :key="v.value"
                     class="book-stock-limit__value"
                     :class="{'is-active': i === selected[type.value] }"
                     @tap="limitChange(type.value,i)">
              {{v.label}}
            </v-touch>
          </dd>
        </dl>
      </template>
    </div>
    <div class="book-stock-switch"
         v-show="books.length>0">
      <div @click="limitStatus = !limitStatus"
           class="book-stock-switch__content">
        <template v-if="limitStatus">
          <span>收回筛选项</span>
          <img class="book-stock-switch__icon"
               src="../assets/书库-打开.png">
        </template>
        <template v-else>
          <span>展开筛选项</span>
          <img class="book-stock-switch__icon"
               src="../assets/书库-收回.png">
        </template>
      </div>
      <div class="book-stock-switch__shadow"></div>
    </div>
    <mt-spinner v-show="searching"
                type="fading-circle"
                color="#32a1ff"></mt-spinner>
    <img v-show="!searching&&!loading&&books.length<1"
         src="../assets/notfind.jpg"
         class="notfind">
    <div v-show="!searching&&!loading&&books.length<1"
         class="contact-customer-service"
         @click="Server">点击联系客服</div>
    <div v-show="!searching&&books.length>0"
         class="book-stock-list"
         v-infinite-scroll="loadMore"
         infinite-scroll-disabled="loading"
         infinite-scroll-distance="10">
      <x-book v-for="book in books"
              :key="book.book_id"
              class="book-stock-book"
              :book="book"
              width="1.8rem"
              multi>
        <x-book-info :book="book"></x-book-info>
      </x-book>
      <mt-spinner v-if="meta.next_page_url"
                  type="fading-circle"
                  color="#32a1ff"></mt-spinner>
    </div>
    <x-footer v-show="books.length>0"></x-footer>
  </div>
</template>
<script>
import { BookStock } from "./namespace.js";
import limit from "../mock/limit.js";
import { Server } from "../components/prompt";
// import books from "../mock/recommend.js";
import { getBook, getCategory } from "../api";
let o1 = null;
let o2 = null;
let o3 = null;
let o4 = null;
export default {
  name: BookStock.name,
  data() {
    return {
      books: [],
      meta: {},
      limit: limit(),
      category: [],
      selected: {
        channel: 0,
        category_id: 0,
        status: 0,
        key: ""
      },
      limitStatus: true,
      loading: true, //正在加载
      tid: null,
      searching: false //正在搜索
    };
  },
  methods: {
    Server,
    resize() {
      let h = 0;
      this.limit.forEach((v, i) => {
        if (v.children) h += Math.ceil(v.children.length / 4);
      });
      this.$refs.limit.style.height = h * 0.8 + "rem";
    },
    limitChange(type, i) {
      if (type !== "key" && this.selected[type] === i) return; //不改变值中断
      if (type === "channel") {
        //一级分类切换后，重置二级分类
        this.selected[type] = i;
        this.selected["category_id"] = 0;
        this.limit[1] = this.initChildCategory(i);
        this.resize();
      }
      if (type !== "key") this.selected[type] = i;
      if (this.selected.key && type !== "key") return; //在有搜索值的时候，切换分类中断
      this.searching = true;
      getBook.source.cancel();
      clearTimeout(this.tid);
      this.tid = setTimeout(() => {
        this.getBook(
          this.selected.key
            ? {
                key: this.selected.key
              }
            : {
                category_id:
                  this.limit[1].children &&
                  this.limit[1].children[this.selected.category_id].value,
                status: this.limit[2].children[this.selected.status].value
              },
          false
        );
      }, 300);
    },
    loadMore() {
      this.loading = true;
      if (this.meta.next_page_url) {
        this.getBook({
          page: this.meta.current_page + 1,
          category_id:
            this.limit[1].children &&
            this.limit[1].children[this.selected.category_id].value,
          status: this.limit[2].children[this.selected.status].value,
          key: this.selected.key
        });
      }
    },
    getBook(params, concat = true) {
      if (params && !params.key) delete params.key;
      if (params && !params.category_id) delete params.category_id;
      if (params && params.status === -1) delete params.status;
      return getBook(params).then(r => {
        if (!r) return;
        if (concat) this.books = this.books.concat(r.list);
        else this.books = r.list;
        this.meta = r.meta;
        this.$nextTick(() => {
          this.loading = false;
          this.searching = false;
        });
        return r;
      });
    },
    async initLimit() {
      const category = await getCategory();
      this.category = category;
      const sex = this.$route.query.sex;
      if (sex === "boy" || this.$parent.theme === "boy") {
        this.selected.channel = 1;
      } else {
        this.selected.channel = 2;
      }
      const channel = {
        label: "频道",
        value: "channel",
        children: category.map(v => {
          return {
            label: v.name,
            value: v.id
          };
        })
      };
      const category_id = this.initChildCategory(this.selected.channel);
      this.limit.unshift(channel, category_id);
      this.resize();
    },
    initChildCategory(index) {
      const category = this.category;
      if (!category[index].children)
        return {
          label: "分类",
          value: "category_id"
        };
      const child = {
        label: "分类",
        value: "category_id",
        children: category[index].children.map(v => {
          return {
            label: v.name,
            value: v.id
          };
        })
      };
      child.children.unshift({
        label: "不限",
        value: category[index].id
      });
      return child;
    }
  },
  created() {
    if (this.$route.meta.behavior === "browser" && o1 && o2 && o3) {
      getCategory().then(r => {
        this.category = r;
      });
      this.books = o1;
      this.limit = o2;
      this.meta = o3;
      this.selected = o4;
      this.$nextTick(() => {
        this.loading = false;
        this.resize();
      });
    } else {
      this.initLimit().then(() => {
        this.getBook({
          category_id:
            this.limit[1].children &&
            this.limit[1].children[this.selected.category_id].value
        });
      });
    }
  },
  destroyed() {
    o1 = this.books;
    o2 = this.limit;
    o3 = this.meta;
    o4 = this.selected;
  }
};
</script>
