<template>
  <view class="banner-container">
    <!-- 添加一个默认插槽，用于在轮播图上方添加自定义内容 -->
    <view class="banner-slot-container" v-if="$slots.default">
      <slot></slot>
    </view>

    <swiper class="swiper-box" :style="{ height: height + 'rpx' }" :autoplay="true" :indicator-dots="false"
      :circular="true" :interval="3000" @change="swChange">
      <swiper-item v-for="(v, i) in advert" :key="i" @click="navTo(v)">
        <image class="yh_bg" :src="v.imgurl" :style="{ width: imgWidth + '%' }"></image>
      </swiper-item>
    </swiper>

    <!-- 指示器 (可选) -->
    <view class="sw-dot relative" v-if="showIndicator">
      <view class="sw-dot-item" v-for="(item, i) in advert" :key="i" :class="{ act: swCur == i }"></view>
    </view>
  </view>
</template>

<script>
import { getAdvert } from '@/common/server/config.js';

export default {
  name: 'banner',
  props: {
    // banner类型ID
    typeId: {
      type: [Number, String],
      default: 1
    },
    // 是否显示指示器
    showIndicator: {
      type: Boolean,
      default: false
    },
    // 轮播图高度
    height: {
      type: [Number, String],
      default: 465
    },
    // 图片自定义样式
    imgWidth: {
      type: Number,
      default: 92
    },
  },
  data() {
    return {
      advert: [], // 轮播图数据
      swCur: 0, // 当前轮播索引
    };
  },
  created() {
    this.getAdvertData();
  },
  methods: {
    // 获取轮播图数据
    async getAdvertData() {
      const data = await getAdvert(this.typeId);
      if (data) {
        this.advert = data;
      }
    },

    // 轮播切换事件
    swChange(e) {
      this.swCur = e.detail.current;
    },

    // 点击轮播图跳转
    navTo(item) {
      this.$c.navTo(item);


    }
  }
}
</script>

<style lang="scss">
.banner-container {
  position: relative;
  width: 100%;
}

.banner-slot-container {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  z-index: 10;
  pointer-events: none;
}

/* 允许插槽内的元素可以被点击 */
.banner-slot-container>* {
  pointer-events: auto;
}

.swiper-box {
  width: 100%;
  /* 默认高度已通过内联样式方式设置 */
}

.yh_bg {
  width: 90%;
  height: 100%;
  border-radius: 16rpx;
  margin: 0 auto;
  display: block;
}

/* 指示器样式 */
.sw-dot {
  display: flex;
  justify-content: center;
  position: absolute;
  bottom: 20rpx;
  width: 100%;

  &-item {
    width: 12rpx;
    height: 12rpx;
    border-radius: 50%;
    background-color: rgba(255, 255, 255, 0.5);
    margin: 0 5rpx;
    transition: all 0.3s;

    &.act {
      width: 24rpx;
      border-radius: 6rpx;
      background-color: #ffffff;
    }
  }
}
</style>