<template>
  <div class="slider" @mouseenter="mouseEenter" @mouseleave="mouseLeave">
    <dot
      :itemLen="itemLength"
      :currentIndex="currentIndex"
      @dotClick="setCurrentIndex"
      v-if="hasDot"
    ></dot>
    <directive @dirClick="dirClick" v-if="hasDirector"></directive>
    <div class="inner">
      <slot></slot>
    </div>
  </div>
</template>

<script>
import Dot from "./Dot.vue";
import Directive from "./Directive.vue";
import {
  reactive,
  toRefs,
  onMounted,
  onBeforeUnmount,
  getCurrentInstance,
  watch,
} from "vue";
export default {
  name: "Slider",
  components: {
    Dot,
    Directive,
  },
  props: {
    autoplay: {
      type: Boolean,
      default: true,
    },
    duration: {
      type: Number,
      default: 3,
    },
    initial: {
      type: Number,
      default: 0,
    },
    hasDot: {
      type: Boolean,
      default: false,
    },
    hasDirector: {
      type: Boolean,
      default: false,
    },
    dir:{
      type:String,
      default:'X'
    }
  },
  setup(props,ctx) {
    const state = reactive({
      currentIndex: props.initial,
      itemLength: 0
    });
    const instance = getCurrentInstance();

    let t = null;
    /*
     *自动播放
     */
    const autoPlay = () => {
      if (props.autoplay) {
        t = setInterval(() => {
          setIndex("next");
        }, props.duration * 1000);
      }
    };
    /*
     *设置index
     */
    const setIndex = (dir) => {
      switch (dir) {
        case "next":
          state.currentIndex += 1;
          if (state.currentIndex === state.itemLength) {
            state.currentIndex = 0;
          }
          break;
        case "prev":
          state.currentIndex -= 1;
          if (state.currentIndex === -1) {
            state.currentIndex = state.itemLength - 1;
          }
          break;
        default:
          break;
      }
    };

    /*
     * 组件挂载
     */
    onMounted(() => {
      state.itemLength = instance.slots.default().length;
      autoPlay();
    });
    /*
     * 组件销毁前
     */
    onBeforeUnmount(() => {
      clearInterval(t);
      t = null;
    });
    /*
     *设置currentIndex
     */
    const setCurrentIndex = (index) => {
      state.currentIndex = index;
    };
    /*
     *鼠标移入
     */
    const mouseEenter = () => {
      clearInterval(t);
      t = null;
    };
    /*
     *鼠标移出
     */
    const mouseLeave = () => {
      autoPlay();
    };

    const dirClick = (dir) => {
      setIndex(dir);
    };

    return {
      ...toRefs(state),
      setCurrentIndex,
      mouseLeave,
      mouseEenter,
      dirClick,
    };
  },
};
</script>

<style lang="scss" scoped>
.slider {
  width: 100%;
  height: 100%;
  position: relative;
  .inner {
    position: relative;
    width: 100%;
    height: 100%;
    overflow: hidden;
  }
}
</style>