<template>
    <div>
        <div class="content-loading-overlay" v-show="isLoading">
            <div class="loading-content">
                <div ref="animationContainer" class="animation-container"></div>
            </div>
        </div>
        <div  v-show="!isLoading">
            <slot></slot>
        </div>
    </div>
</template>
<script>
import lottie from 'lottie-web'
import { mapState } from 'vuex'
import defaultAnimation from '@/assets/loadingAni.json'

export default {
  name: 'Loading',
  data() {
    return {
      anim: null
    }
  },
  computed: {
    ...mapState(['isLoading', 'loadingText'])
  },
  watch: {
    isLoading(newVal) {
      this.$nextTick(() => {
        if (newVal) {
          this.playAnimation()
        } else {
          this.stopAnimation()
        }
      })
    }
  },
  methods: {
    playAnimation() {
      // 销毁旧实例（可选，根据需求）
      if (this.anim) {
        this.anim.destroy()
        this.anim = null
      }
      
      console.log('执行动画')
      this.anim = lottie.loadAnimation({
        container: this.$refs.animationContainer,
        renderer: 'svg',
        loop: true,
        autoplay: true,
        animationData: defaultAnimation
      })
    },
    stopAnimation() {
      if (this.anim) {
        this.anim.stop()
      }
    }
  },
  beforeDestroy() {
    if (this.anim) {
      this.anim.destroy() // 组件销毁时彻底清理
    }
  }
}
</script>

<style scoped>
.content-loading-overlay {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(255, 255, 255, 0.8);
    z-index: 1000;
    /* 确保高于内容 */
    display: flex;
    justify-content: center;
    align-items: center;
}

.loading-content {
    text-align: center;
}

.animation-container {
    width: 180px;
    height: 180px;
    margin: 0 auto;
}

.loading-text {
    margin-top: 20px;
    font-size: 16px;
    color: #333;
}
</style>