<!--
 * @Author: ZhengXiaowei
 * @Date: 2019-07-12 09:47:32
 * @LastEditors: 晓晓晓晓晓丶vv
 * @LastEditTime: 2020-09-14 17:37:28
 * @Description: file content
 -->
<template>
  <div class="book-catalog new-catalog">
    <div class="z-header">
      <x-header ref="header">
        <p class="open-header"
           @click="openDialog">
          {{ activeName }}<img src="../assets/open.png" />
        </p>
      </x-header>
    </div>
    <div class="abs-list">
      <div v-infinite-scroll="loadMore"
           infinite-scroll-disabled="loading"
           infinite-scroll-distance="10">
        <template v-for="v in catalogs">
          <div class="book-catalog-item"
               :key="v.chapter_id"
               ref="catalogs"
               @click="toReader(v)">
            <span class="book-catalog-item__name"
                  :class="{ 'is-active': sequence === v.chapter_sequence }">{{ v.chapter_name }}
              <span v-if="v.is_show_price && v.chapter_is_vip"
                    class="price-box">
                <img src="../assets/price.png"
                     class="price-icon" />{{ v.price }}
              </span>
            </span>
            <img v-if="v.chapter_is_vip"
                 src="../assets/书库-vip.png"
                 class="book-catalog-item__vip" />
          </div>
        </template>
        <mt-spinner v-if="!isLoadLast"
                    type="fading-circle"
                    color="#32a1ff"></mt-spinner>
      </div>
    </div>
    <mt-popup v-model="popupVisible"
              position="bottom">
      <mt-picker :slots="slots"
                 @change="onValuesChange"
                 ref="picker"
                 class="mybook-picker"
                 value-key="name"
                 showToolbar>
        <div class="picker-title">
          <div class="usi-btn-cancel"
               @click="cancelTar">
            取消
          </div>
          <div style="font-weight:bold">请选择章节</div>
          <div class="usi-btn-sure"
               @click="sureTar">
            确定
          </div>
        </div>
      </mt-picker>
    </mt-popup>
  </div>
</template>
<script>
import { BookCatalog, Reader, Pay } from "./namespace.js";
import catalogs from "../mock/catalogs.js";
import { getCatalog, getUserInfo } from "../api";
const pageSize = 100;

let catalog = null;

export default {
  name: BookCatalog.name,
  data() {
    return {
      Reader: Reader.name,
      catalogs: [],
      inLoadData: false,
      isLoadLast: false,
      popupVisible: false,
      balance: 0,
      activeName: "",
      is_vip: false,
      sequence: +this.$route.query.sequence,
      active: (((+this.$route.query.sequence || 1) / 100) >> 0) + 1,
      slots: [
        {
          flex: 1,
          values: [],
          className: "slot1",
          defaultIndex: 0,
        },
      ],
      meta: {},
      tempPage: 1,
      handler: function (e) {
        e.preventDefault();
      },
    };
  },
  watch: {
    popupVisible(val) {
      if (val) {
        this.closeTouch();
      } else {
        this.openTouch();
      }
    },
  },
  methods: {
    openDialog() {
      this.popupVisible = true;
    },
    closeTouch() {
      document
        .getElementsByTagName("body")[0]
        .addEventListener("touchmove", this.handler, { passive: false });
    },
    openTouch() {
      document
        .getElementsByTagName("body")[0]
        .removeEventListener("touchmove", this.handler, { passive: false });
    },
    onValuesChange(picker, values) {
      if (values[0]) {
        this.tempPage = values[0].value;
      }
    },
    cancelTar() {
      this.popupVisible = false;
    },
    sureTar() {
      this.isLoadLast = false;
      getCatalog(this.$route.query.id, this.tempPage).then((r) => {
        let catalog = r;
        this.meta = catalog.meta;
        this.catalogs = catalog.data;
        this.active = catalog.meta.current_page;
        this.isLoadLast = r.meta.current_page === r.meta.last_page;
        let total = catalog.meta.total;
        if (this.active == 1 && this.active != catalog.meta.last_page) {
          this.activeName = "1-100章";
        } else if (this.active == catalog.meta.last_page) {
          this.activeName = `${(this.active - 1) * 100 + 1}-${total}章`;
        } else {
          this.activeName = `${(this.active - 1) * 100 + 1}-${
            this.active * 100
          }章`;
        }
        window.scrollTo(0, 0);
        document.documentElement.scrollTop = document.body.scrollTop = 0;

        this.popupVisible = false;
      });
    },
    reset() {
      //位置重置
      if (!isNaN(this.sequence)) {
        let currentNext = this.$refs.catalogs[(this.sequence % pageSize) - 2];
        let timer = null;
        let height = (currentNext.$el || currentNext).offsetTop;
        let h =
          window.innerHeight ||
          document.documentElement.clientHeight ||
          document.body.clientHeight;
        let h1 =
          document.body.clientHeight || document.documentElement.clientHeight;
        let h2 = h1 - h;
        height > h2 ? (height = h2) : (height = height);

        let reset = () => {
          window.scrollTo(0, height);
          document.documentElement.scrollTop = document.body.scrollTop = height;
          clearTimeout(timer);
        };
        timer = setTimeout(function () {
          reset();
        }, 50);
      }
    },
    adjustBalance() {
      getUserInfo().then((r) => {
        this.balance = r.reward_balance;
        this.is_vip = r.is_vip;
      });
    },
    toReader(chapter) {
      const bid = this.$route.query.id;
      const {
        chapter_id: cid,
        price: chapter_cost,
        chapter_is_vip: vip,
      } = chapter;
      if (!this.is_vip && !!vip && chapter_cost > this.balance) {
        // vip章节 且章节价格>余额
        this.$router.push({
          name: Pay.name,
          query: {
            book_id: bid,
            chapter_id: cid,
            fee: chapter_cost,
            code: 10021,
          },
        });
      } else {
        this.$router.push({
          name: this.Reader,
          query: {
            bid,
            cid,
          },
        });
      }
    },
    loadMore() {
      if (this.inLoadData) return;
      this.inLoadData = true;
      if (this.isLoadLast) return;
      let page = this.meta.current_page;
      getCatalog(this.$route.query.id, page + 1).then((r) => {
        this.catalogs.push(...r.data);
        this.meta = r.meta;
        this.isLoadLast = r.meta.current_page === r.meta.last_page;
        this.inLoadData = false;
      });
    },
  },
  created() {
    if (catalog) {
      this.catalogs = catalog.data;
      this.meta = catalog.meta;
      if (this.catalogs.length > catalog.meta.per_page) {
        this.meta.current_page = Math.ceil(
          this.catalogs.length / catalog.meta.per_page
        );
      }
      this.active = catalog.meta.current_page;
      let end = catalog.meta.last_page;
      let total = catalog.meta.total;
      for (let i = 1; i <= Math.ceil(total / 100); i++) {
        if (i == 1) {
          let s;
          if (total >= 100) {
            s = `${i}-${i * 100}章`;
          } else {
            s = `${i}-${total}章`;
          }
          this.slots[0].values.push({ name: s, value: i });
        } else if (i == Math.ceil(total / 100)) {
          let s = `${(i - 1) * 100 + 1}-${total}章`;
          this.slots[0].values.push({ name: s, value: i });
        } else {
          let s = `${(i - 1) * 100 + 1}-${i * 100}章`;
          this.slots[0].values.push({ name: s, value: i });
        }
      }
      this.slots[0].defaultIndex = this.active - 1;
      if (this.active == 1 && this.active != catalog.meta.last_page) {
        this.activeName = "1-100章";
      } else if (this.active == catalog.meta.last_page) {
        this.activeName = `${(this.active - 1) * 100 + 1}-${total}章`;
      } else {
        this.activeName = `${(this.active - 1) * 100 + 1}-${
          this.active * 100
        }章`;
      }
      this.$nextTick(this.reset);
    } else {
      this.activeName = "1-100章";
      this.$router.replace("/");
    }
    this.adjustBalance();
  },
  beforeRouteEnter(to, from, next) {
    let id = to.query.id;
    let start = (((+to.query.sequence || 1) / 100) >> 0) + 1;
    getCatalog(id, start, "catalog")
      .catch((e) => {
        let replace_url = e.data.data.url + location.pathname + location.search;
        location.replace(replace_url);
      })
      .then((r) => {
        catalog = r;
        next();
      });
  },
};
</script>

<style lang="scss">
.usi-btn-cancel {
  color: #666;
}
.usi-btn-sure {
  color: #1296db;
}
.picker-title {
  display: flex;
  justify-content: space-around;
  height: 40px;
  line-height: 40px;
  font-size: 0.28rem;
}
.mybook-picker {
  width: 100vw;
  height: 4rem;
  .picker-item.picker-selected {
    color: #1296db;
  }
}

.price-box {
  margin-left: 20px;
  color: #999;
  font-size: 0.24rem;
  .price-icon {
    width: 0.32rem;
    height: 0.32rem;
    vertical-align: sub;
    margin-right: 5px;
  }
}
.open-header {
  font-size: 0.24rem;
  color: #1296db;
  img {
    background: url(../assets/open.png) no-repeat;
    display: inline-block;
    vertical-align: sub;
    width: 0.34rem;
    height: 0.34rem;
  }
}
.new-catalog {
  .book-catalog-item {
    padding: 0 0.3rem;
  }
  .z-header {
    height: 1rem;
  }
  .x-header {
    position: fixed;
    height: 1rem;
    top: 0;
    left: 0;
    right: 0;
    background: #fff;
  }
}
</style>
