<template>
  <swiper class="swiper-box" :style="{'height': height + 'rpx'}" :interval="2000"
    :disable-touch="!list || list.length <= 1" circular :indicator-dots="list && list.length > 1"
    indicator-active-color="#fff" @change="changeSwoper">
    <swiper-item class="swiper-item" v-for="(item , index) in list">
      <image @click.stop="$openPage(item)" :src="item.image" mode="scaleToFill"
        :style="{'border-radius':borderRadius + 'rpx'}"></image>
    </swiper-item>
  </swiper>

</template>

<script>
  import {
    getBannerList
  } from "@/api/government.js"
  export default {
    name: "zw-swiper",
    props: {
      borderRadius: {
        type: Number,
        default: 0
      },
      autoLoad: {
        type: Boolean,
        default: true
      },
      height: {
        type: Number,
        default: 200
      },
      StorageKey: {
        type: String,
        default: ""
      },
      keyword: {
        type: String,
        default: ""
      },
    },
    data() {
      return {
        list: []
      };
    },
    created() {

    },
    methods: {
      init() {
        this.getBanner(this.keyword)
      },
      // 获取 banner
      getBanner(keyword) {
        if (!keyword) return
        getBannerList(keyword).then(res => {
          const data = res.data || []
          this.list = data.map(el => {
            el.image = this.$getImgPath(el.image)
            return el
          });
          console.log()
          this.$emit('getBanner', data)
          if (this.StorageKey) {
            uni.setStorage({
              key: this.StorageKey,
              data: this.list,
              success: function() {
                console.log('success');
              }
            });
          }


        });
      },

      // 点击轮播图
      openSwiper(e) {
        this.$openPage(this.list[e])
      },

      changeSwoper(e) {
        if (e.detail.source == "touch") {
          this.$emit("disabledScoll")
        }
      }
    },
    watch: {
      keyword: {
        handler: function(newKwd, oldKod) {
          if (oldKod === undefined && this.StorageKey) {
            uni.getStorage({
              key: this.StorageKey,
              success: res => {
                this.list = res.data || []
              }
            });
          }
          if (this.autoLoad && newKwd && newKwd !== oldKod) this.getBanner(newKwd)
        },
        immediate: true,
        deep: true
      }
    }
  }
</script>

<style lang="scss" scoped>
  .swiper-box {
    width: 100%;

    .swiper-item {
      width: 100%;
      height: 100%;

      image {
        width: 100%;
        height: 100%;
      }
    }
  }
</style>