<template>
  <div class="imgcon" @mousedown.stop @mousemove.stop @mouseup.stop>
    <div class="swiper-container" :class="keyid">
      <ul class="swiper-wrapper imgul">
        <li
          class="swiper-slide img"
          v-for="(pic, picii) in list"
          :key="picii"
          :style="{ backgroundImage: `url(${imageURL(pic.src)})` }"
        ></li>
      </ul>
      <ul class="pagination">
        <li
          :class="{ active: picii == current }"
          v-for="(pic, picii) in list"
          :key="picii"
        ></li>
      </ul>
    </div>
  </div>
</template>

<script setup>
import { useStore } from "vuex";
import {
  ref,
  watchEffect,
  defineEmits,
  computed,
  onMounted,
  onUnmounted,
  nextTick,
  defineProps,
} from "vue";
import { getApp } from "@/app";
let swiper = null;
const store = useStore();
const emit = defineEmits(["change"]);
const current = ref(0);
const props = defineProps({
  list: {
    type: Array,
    default: [],
  },
  keyid: {
    type: String,
    default: "keyid",
  },
  index: {
    type: Number,
    default: -1,
  },
});
const imageURL = (name) => {
  return getApp().resource.getUserResourceURL(name);
};
const initScroll = () => {
  nextTick(() => {
    let t = setTimeout(() => {
      clearTimeout(t);
      swiper = new Swiper(`.${props.keyid}`, {
        on: {
          touchMove(swiper, e) {
            e.stopPropagation();
            e.preventDefault();
          },
          slideChange() {
            current.value = this.activeIndex;
            emit("change", current.value);
          },
        },
      });
    }, 100);
  });
};
watchEffect(() => {
  if (props.index != -1 && props.index!=null) {
    if (swiper) {
      swiper.slideTo(props.index);
    } else {
      setTimeout(() => {
        swiper && swiper.slideTo(props.index);
      }, 200);
    }
  }
});
onMounted(() => {
  initScroll();
});
onUnmounted(()=>{
  swiper = null
})
</script>

<style lang="scss" scoped>
.imgcon {
  min-height: 34vh;
  overflow: hidden;

  .swiper-container {
    position: relative;
    .imgul {
      .img {
        height: 34vh;
        width: 100% !important;
        background: #000;
        background-size: contain;
        background-position: center center;
        background-repeat: no-repeat;
      }
    }

    .pagination {
      position: absolute;
      left: 50%;
      bottom: 10px;
      transform: translateX(-50%);
      z-index: 99;
      > li {
        width: 8px;
        height: 8px;
        margin: 0 4px;
        display: inline-block;
        border-radius: 50%;
        background-color: rgba(255, 255, 255, 0.5);
        &.active {
          background-color: var(--editor-main-color);
        }
      }
    }
  }
}
</style>
