<template>
  <v-touch v-if="direction === 'horizontal'"
           class="x-reader-text x-reader-text--horizontal"
           :style="bgStyle"
           @pan="pan"
           @panstart="panstart"
           @panend="panend"
           @tap="tap"
           key="horizontal">
    <div :class="['x-reader-text-wrap',{'x-reader-text-transition': transition}]"
         :style="[posStyle,wrapStyle,fontStyle]"
         ref="wrap">
      <p class="x-reader-text-name"
         :style="nameStyle">{{text.name}}</p>
      <p class="x-reader-text-paragraph"
         v-for="(value,index) in content"
         :key="index">{{value}}</p>
      <div ref="slot">
        <slot></slot>
      </div>
    </div>
    <div class="x-reader-text-pageinfo">
      <div class="x-reader-text-title">{{text.name}}</div>
      <div class="x-reader-text-page">{{page.current + 1}}/{{page.total}}</div>
    </div>
  </v-touch>
  <v-touch v-else
           key="vertical"
           class="x-reader-text x-reader-text--vertical"
           ref="vertical"
           @tap="verticalTap"
           @touchend.native
           :style="[bgStyle,fontStyle]">
    <slot name="top"></slot>
    <div class="x-reader-text-name x-reader-text-name__new"
         :style="nameStyle">{{text.name}}
      <p class="name-right__box">
        <v-touch tag="span"
                 :class="['add-shelf',{'add-shelf-old':is_old}]"
                 :style="shelfStyle"
                 v-if="!shelf"
                 @tap="emit('addShelf')">加入书架</v-touch>
        <!-- <v-touch v-if="text.name"
                 tag="span"
                 class="complaints"
                 @tap="toReport">投诉</v-touch> -->
      </p>
    </div>
    <x-vertical-menu :gift="gift"
                     :is_old="is_old"></x-vertical-menu>

    <template v-for="(value,index) in content">
      <template v-if="index < 1">
        <div class="ad-wrap"
             v-if="adframe"
             :key="'ad6-'+ index">
          <div class="ad-wrapper">
            <div></div>
          </div>
        </div>
      </template>
      <template v-if="index === Math.floor(content.length / 2)">
        <div :key="'c-'+index"
             class="fans-banner"
             v-show="showFans && hasAccount">
          <v-touch tag="i"
                   class="close"
                   @tap="closeBanner"></v-touch>
          <v-touch class="fans-banner-wrap"
                   @tap="jumpLink">
            <img src="../../assets/fansbanner.jpg"
                 width="100%" />
          </v-touch>
        </div>
      </template>
      <template v-if="index === Math.floor(content.length / 2)">
        <div class="ad-wrap"
             v-if="adframe"
             :key="'ad-'+index">
          <div class="ad-wrapper">
            <div></div>
          </div>
        </div>
        <div class="ad-wrap"
             v-if="adframe"
             :key="'ad2-'+index">
          <div class="ad-wrapper">
            <div></div>
          </div>
        </div>
      </template>
      <p class="x-reader-text-paragraph"
         :key="index">{{value}}</p>
      <!-- 最后一个位置 -->
      <template v-if="index === content.length - 1">
        <div class="ad-wrap"
             v-if="adframe"
             :key="'ad3-'+index">
          <div class="ad-wrapper">
            <div></div>
          </div>
        </div>
        <div class="ad-wrap"
             v-if="adframe"
             :key="'ad4-'+index">
          <div class="ad-wrapper">
            <div></div>
          </div>
        </div>
      </template>
    </template>
    <div ref="slot">
      <slot></slot>
    </div>
    <!-- <div class="x-reader-text-share" v-show="text.is_show_share_button===1">
      <img src="../../assets/去分享.png" class="x-reader-text-share_span"/>
    </div> -->
    <p class="x-reader-text-footer"
       v-if="content.length">
      <span class="x-reader-text-footer__prev"
            :style="sysStyle">上一章</span>
      <span class="x-reader-text-footer__cate"
            :style="sysStyle">目录</span>
      <span class="x-reader-text-footer__next"
            :style="sysStyle">{{menuNextBtnText}}</span>
    </p>
    <slot name="underfooter"></slot>
  </v-touch>
</template>

<script>
import bus from "./bus.js";
import XVerticalMenu from "./vertical-menu";
export default {
  name: "XReaderText",
  props: ["text", "gift", "shelf", "ad", "adframe", "showFans"],
  components: {
    XVerticalMenu
  },
  data() {
    return {
      preset: bus.preset,
      startPosition: {
        box: 0, //交互开始时盒子的偏移
        gesture: 0 //交互开始时手指的坐标
      },
      slide: [
        {
          //最后几次滑动的信息
          time: 0,
          pos: 0
        }
      ],
      offsetBox: 0, //盒偏移
      transition: true,
      page: {
        width: bus.preset.w,
        scrollWidth: 0,
        current: 0,
        total: 0
      },
      font: bus.font, //字体大小
      bg: bus.bg, //背景色
      night: bus.night, //夜间模式
      direction: bus.direction,
      bgList: bus.bgList,
      tapCount: 0,
      is_old: window.options.isOld || 0
    };
  },
  computed: {
    posStyle() {
      return {
        transform: `translate3d(${this.offsetBox}px, 0, 0)`
      };
    },
    hasAccount() {
      return (
        !!window.options.guidepersonalaccount &&
        window.options.guidepersonalaccount.is_self
      );
    },
    wrapStyle() {
      return {
        height: this.preset.h + "px",
        width: this.preset.w + "px"
      };
    },
    bgStyle() {
      return this.night ? this.preset.nightStyle2 : this.bgList[this.bg];
    },
    fontStyle() {
      return {
        fontSize: this.font + "px"
      };
    },
    sysStyle() {
      let bgItem = this.bgList[this.bg];
      let night = this.night;
      let nightStyle = this.preset.nightStyle2;
      if (bgItem !== "undefined") {
        return night
          ? {
              color: nightStyle.color || "#666",
              background: nightStyle.background || "#262626",
              borderColor: nightStyle.btnSysBorder || "#666"
            }
          : {
              color: bgItem.color || "#1a1a1a",
              background: bgItem.background || "#e6e6e6",
              borderColor: bgItem.btnSysBorder || "#666"
            };
      }
    },
    shelfStyle() {
      let bgItem = this.bgList[this.bg];
      let night = this.night;
      let nightStyle = this.preset.nightStyle2;
      if (bgItem !== "undefined") {
        return night
          ? {
              color: nightStyle.color || "#666",
              background: nightStyle.btnBg || "#333",
              borderColor: nightStyle.btnBorder || "#0d0d0d"
            }
          : {
              color: bgItem.color || "#1a1a1a",
              background: bgItem.btnBg || "#e6e6e6",
              borderColor: bgItem.btnBorder || "#ccc"
            };
      }
    },
    nameStyle() {
      //标题样式
      let bgItem = this.bgList[this.bg];
      let night = this.night;
      let nightStyle = this.preset.nightStyle2;
      if (bgItem !== "undefined") {
        return night
          ? {
              // fontSize: ((this.font * 1.3) >> 0) + "px",
              fontSize: "19px",
              fontWeight: "normal",
              borderColor: nightStyle.btnSysBorder || "#666"
            }
          : {
              fontSize: "19px",
              fontWeight: "normal",
              borderColor: bgItem.btnBorder || "#ccc"
            };
      }
    },
    content() {
      if (!this.text.content) return [];
      this.$nextTick(() => {
        if (this.direction === "horizontal") {
          this.countPages();
          bus.$emit("horizontal-mounted", this.page);
          if (this.text.jump) this.jump(this.text.jump);
          else this.jump(1);
        } else if (this.direction === "vertical") {
          this.$refs.vertical.$el.scrollTop = 0;
          bus.$emit("vertical-mounted");
        }
      });
      return this.text.content.trim().split(/\n/);
    },
    menuNextBtnText() {
      let show_ad_status = this.ad;
      return show_ad_status ? "点击广告解锁" : "下一章";
    }
  },
  methods: {
    jumpLink() {
      location.href =
        window.options.guidepersonalaccount.link + "&p_src=middle_reader";
    },
    pan(e) {
      let offsetBox =
        e.center.x - this.startPosition.gesture + this.startPosition.box;
      let max = this.page.scrollWidth;
      let min = 0;
      let sin = pos => {
        return (
          Math.sin(((pos / this.preset.w) * Math.PI) / 2) *
          this.preset.border *
          this.preset.w
        );
      };
      if (offsetBox > min) {
        //极限处理，第一页再往左
        offsetBox = sin(offsetBox);
      }
      if (offsetBox < -max) {
        //极限处理，最后一页再往右
        offsetBox = sin(offsetBox - max) + max;
      }
      this.offsetBox = offsetBox;
      this.addSlideInfo(e.center.x);
    },
    panstart(e) {
      this.startPosition.gesture = e.center.x;
      this.startPosition.box = this.offsetBox;
      this.slide = [];
      this.transition = false;
      bus.$emit("menu", false);
    },
    panend(e) {
      this.transition = true;
      let page = this.page.current;
      let slide = this.isFastSlide();
      const offset = (e.center.x - this.startPosition.gesture) / this.preset.w;
      if (offset > this.preset.offset || slide === "prev") page--; //向右移动超过预设值
      if (offset < -this.preset.offset || slide === "next") page++; //向左移动超过预设值
      this.flip(page);
    },
    tap(e) {
      if (this.$refs.slot.contains(e.target)) return;
      this.transition = true;
      const x1 = this.preset.w * this.preset.offset; //x轴左界限
      const x2 = this.preset.w - x1; //x轴右界限
      const y1 = this.preset.h * this.preset.offset; //y轴上界限
      const y2 = this.preset.h - y1; //y轴下界限
      const x = e.center.x; //手指X坐标
      const y = e.center.y; //手指y坐标
      if (x < x1 || (x < x2 && y < y1)) {
        //左边或者左上
        this.flip(this.page.current - 1);
        bus.$emit("menu", false);
      }
      if (x > x1 && x < x2 && y > y1 && y < y2) {
        //中心区
        bus.$emit("menu");
      }
      if (x > x2 || (x > x1 && y > y2)) {
        //右边或者右上
        this.flip(this.page.current + 1);
        bus.$emit("menu", false);
      }
    },
    verticalTap(e) {
      if (this.$refs.slot.contains(e.target)) return;
      switch (e.target.className) {
        case "x-reader-text-footer__prev":
          bus.$emit("prev");
          break;

        case "x-reader-text-footer__cate":
          bus.$emit("route", "catalog");
          break;

        case "x-reader-text-footer__catalog":
          bus.$emit("route", "catalog");
          break;

        case "x-reader-text-footer__menu":
          bus.$emit("menu", true);
          break;

        case "x-reader-text-footer__next":
          bus.$emit("next");
          break;

        case "x-reader-text-share_span":
          bus.$emit("share");
          break;

        default:
          // const x1 = this.preset.w * this.preset.offset; //x轴左界限
          // const x2 = this.preset.w - x1; //x轴右界限
          // const y1 = this.preset.h * this.preset.offset; //y轴上界限
          // const y2 = this.preset.h - y1; //y轴下界限
          // const x = e.center.x; //手指X坐标
          // const y = e.center.y; //手指y坐标
          // if (x > x1 && x < x2 && y > y1 && y < y2) {
          //   bus.$emit("menu",fasle);
          // }
          bus.$emit("menu", false);
          // 控制背景的显示隐藏
          this.tapCount++;
          if (
            e.target.className !== "operator-item" &&
            e.target.className !== "bg-item"
          ) {
            if (this.tapCount >= 2) {
              this.tapCount = 0;
              bus.bgMenu = false;
            }
          }
          break;
      }
    },
    flip(page = this.page.current) {
      // 翻页有动画，0为第一页
      if (page < 0) {
        bus.$emit("prev");
        page = 0;
      }
      if (page >= this.page.total) {
        bus.$emit("next");
        page = this.page.total - 1;
      }
      if (page > this.page.current) console.log("下一页");
      if (page < this.page.current) console.log("上一页");
      this.offsetBox = page * this.preset.w * -1;
      this.page.current = page;
    },
    jump(page) {
      // 翻页无动画,不考虑换章，-1为最后一页，1为第一页
      this.transition = false;
      if (page <= 0 || page >= this.page.total) {
        this.offsetBox = (this.page.total - 1) * this.preset.w * -1;
        this.page.current = this.page.total - 1;
      } else {
        this.offsetBox = (page - 1) * this.preset.w * -1;
        this.page.current = page - 1;
      }

      this.offsetBox -= 0.01;

      this.$nextTick().then(() => {
        getComputedStyle(this.$refs.wrap, null).transform; //获取一下样式，强制刷新dom
        this.offsetBox += 0.01; //ios会有渲染问题，不能正确显示
        this.transition = true;
      });
    },
    countPages() {
      const scrollWidth = this.$refs.wrap.scrollWidth;
      const total = scrollWidth / this.preset.w;
      this.page.total = total;
      this.page.scrollWidth = scrollWidth;
      if (process.env.NODE_ENV === "development") {
        console.log({
          页宽: this.page.width,
          总宽: scrollWidth,
          总页数: total
        });
      }
    },
    closeBanner() {
      bus.$emit("closeBanner", true);
    },
    addSlideInfo(pos) {
      this.slide.push({
        time: new Date(),
        pos: pos
      });
      if (this.slide.length > this.preset.slide.count) {
        this.slide = this.slide.slice(-this.preset.slide.count);
      }
    },
    isFastSlide() {
      //快速滑动判断
      let interval = [];
      let distance = [];
      let intervalT = 0; //总和
      let distanceT = 0; //总和
      let speed = 0;
      this.slide.forEach((v, i) => {
        if (i === 0) return;
        interval.push(this.slide[i].time - this.slide[i - 1].time);
        distance.push(this.slide[i].pos - this.slide[i - 1].pos);
        intervalT += this.slide[i].time - this.slide[i - 1].time;
        distanceT += this.slide[i].pos - this.slide[i - 1].pos;
      });

      speed = distanceT / intervalT;
      // console.log(speed,interval,distance)
      if (Math.max(...interval) > this.preset.slide.interval) return false; //判断是否停留
      if (Math.min(...distance) < 0 && Math.max(...distance) > 0) return false; //判断方向

      if (speed > this.preset.slide.speed) {
        //速度判断
        return "prev";
      } else if (speed < -this.preset.slide.speed) {
        return "next";
      } else {
        return false;
      }
    },
    emit(type, params) {
      bus.$emit(type, params);
    },
    toReport() {
      this.$router.push({
        path: "/report",
        query: {
          bid: this.$route.query.bid,
          cid: this.$route.query.cid
        }
      });
    }
  },
  mounted() {
    bus.$on("font", font => {
      if (font === this.font) return;
      this.font = font;
      if (this.direction === "horizontal") {
        this.$nextTick(() => {
          this.countPages();
          this.jump(this.page.current + 1);
        });
      }
    });
    bus.$on("bg", bg => {
      if (bg === this.bg) return;
      this.bg = bg;
    });
    bus.$on("night", night => {
      if (night === this.night) return;
      this.night = night;
    });
    bus.$on("direction", direction => {
      if (direction === this.direction) return;
      this.direction = direction;
      if (direction === "horizontal") {
        this.$nextTick().then(() => {
          this.countPages();
          this.jump(1);
          bus.$emit("horizontal-mounted", this.page);
        });
      } else if (this.direction === "vertical") {
        bus.$emit("vertical-mounted");
      }
    });
    bus.$on("show-gift", () => {
      bus.$emit("show-gift-popup");
    });
  }
};
</script>
