<template>
  <div class="trifle-carousel">
    <div class="trifle-content" :style="{'width': `${width}px`}">
      <ul class="trifle-list"
        :style="{
          width: `${width * childrenLength}px`,
          transform: `translate3d(-${activeIndex * width}px, 0px, 0px)`,
          transition: '-webkit-transform 500ms ease'
        }"
      >
        <slot></slot>
      </ul>
    </div>
    <ul class="trifle-dots">
      <li
        :style="dotStyle"
        v-for="(i, index) in childrenLength"
        :class="{'active': activeIndex === index}"
        @click.stop="dotClickHandler(index)"
        :key="index"
      />
    </ul>
  </div>
</template>

<script>
export default {
  name: 'Carousel',
  props: {
    dotStyle: {
      type: String,
      default: ''
    },
    isAuto: {
      type: Boolean,
      default: false
    },
    intervalTime: {
      type: Number,
      default: 5000,
    }
  },
  data () {
    return {
      width: 0,
      childrenLength: 0,
      activeIndex: 0
    }
  },
  mounted () {
    this.width = this.$el.offsetWidth
    this.childrenLength = this.$children.length
    this.$children.forEach((ele, index) => {
      ele.$el.style.width = this.width + 'px'
    })
    // auto play
    if (this.isAuto) {
      setInterval(() => {
        if (this.childrenLength - 1 === this.activeIndex) {
          this.activeIndex = 0
        } else {
          ++this.activeIndex
        }
      }, this.intervalTime)
    }
  },
  methods: {
    dotClickHandler (index) {
      this.activeIndex = index
    }
  }
}
</script>

<style lang="scss" scoped>
.trifle-carousel {
  position: relative;
  display: block;
  box-sizing: border-box;
  -webkit-touch-callout: none;
  -ms-touch-action: pan-y;
  touch-action: pan-y;
  -webkit-tap-highlight-color: transparent;

  .trifle-content {
    position: relative;
    overflow: hidden;
    display: block;
    margin: 0;
    padding: 0;

    .trifle-list {
      position: relative;
      left: 0;
      top: 0;
      display: block;
      list-style: none;
      margin: 0;
      padding: 0;

      .trifle-item {
        float: left;
        height: 100%;
        min-height: 1px;
        display: block;
      }
    }
  }

  .trifle-dots {
    position: absolute;
    bottom: 20px;
    list-style: none;
    display: block;
    text-align: center;
    padding: 0;
    margin: 0;
    width: 100%;
    height: 3px;

    li {
      position: relative;
      display: inline-block;
      vertical-align: top;
      text-align: center;
      margin: 0 8px;
      padding: 0;
      background: #fff;
      width: 6px;
      height: 6px;
      cursor: pointer;
      border-radius: 6px;
      opacity: 0.3;
      transition: all 0.5s;

      &.active {
        opacity: 1;
        width: 16px;
        height: 16px;
        border-radius: 16px;
        margin-top: -4px;
      }
    }
  }
}
</style>
