<template>
  <div class="paper-carousel">
    <div class="carousel-body image-view-contain">
      <img
        :src="curPaper.thumbSrc"
        :alt="curPaper.title"
        v-if="curPaper.thumbSrc"
        @click="clickHandle"
      />
      <div class="carousel-none" v-else>
        <Icon type="md-image" />
        <p>暂无数据</p>
      </div>
    </div>
    <div class="carousel-action">
      <div class="carousel-btn carousel-btn-left" @click="handleLeft">
        <Icon type="ios-arrow-dropleft-circle" />
      </div>
      <div class="carousel-btn carousel-btn-right" @click="handleRight">
        <Icon type="ios-arrow-dropright-circle" />
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: "paper-carousel",
  props: {
    papers: {
      type: Array,
      default() {
        return [];
      }
    },
    loop: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      curPaper: {},
      curIndex: 0
    };
  },
  computed: {
    isFirst() {
      return this.curIndex === 0;
    },
    isLast() {
      return this.lastIndex === this.curIndex;
    },
    lastIndex() {
      return this.papers.length ? this.papers.length - 1 : 0;
    }
  },
  methods: {
    initIndex() {
      this.curIndex = 0;
      if (this.papers.length) {
        this.setCurPaper(0);
      } else {
        this.curPaper = {};
      }
    },
    setCurPaper(index) {
      this.curPaper = this.papers[index];
      this.$emit("on-paper-change", this.curPaper);
    },
    handleLeft() {
      if (this.isFirst) {
        if (this.loop) {
          this.curIndex = this.lastIndex;
        } else {
          this.$emit("on-prev-end");
          return;
        }
      } else {
        this.curIndex -= 1;
      }
      this.$emit("on-prev", this.curIndex);
      this.setCurPaper(this.curIndex);
    },
    handleRight() {
      if (this.isLast) {
        if (this.loop) {
          this.curIndex = 0;
        } else {
          this.$emit("on-next-end");
          return;
        }
      } else {
        this.curIndex += 1;
      }
      this.$emit("on-next", this.curIndex);
      this.setCurPaper(this.curIndex);
    },
    clickHandle() {
      this.$emit("on-paper-click", this.curIndex, this.papers);
    }
  }
};
</script>
