<template>
  <div :style="{ width, height }" class="lottie__container">
    <div
      ref="lottieRef"
      class="canvasId"
      canvas-id="canvasId"
      type="2d"
      style="width: 100%; height: 100%"
    ></div>
  </div>
</template>

<script setup lang="ts" scoped>
import { onMounted, ref, watch } from 'vue'
import lottie from 'lottie-web'
import type { LottieEvent } from '@/components/ShowLottie/type'
import { onUnmounted } from 'vue'
const props = withDefaults(
  defineProps<{
    isPlay?: boolean
    delay?: number
    width?: string
    height?: string
    renderer?: 'svg' | 'canvas' | 'html'
    name?: string
    autoplay?: boolean
    loop?: boolean
    rendererSettings?: {
      preserveAspectRatio?: string
    }
    urlName2?: string
  }>(),
  {
    delay: 0,
    renderer: 'svg',
    loop: true,
    autoplay: true,
  },
)
// 创建事件返回初始化lottie对象
const emits = defineEmits<{
  (e: 'getAnimation', value: LottieEvent): void
  (e: 'getDom', value: Element): void
}>()

const OSS_URL = import.meta.env.VITE_OSS_URL

const animation = ref<LottieEvent>()
const lottieRef = ref()
const getJSON = (name: string | any) => {
  return `${OSS_URL}/xuexiaole_clinet/lottieJSON/${name}.json` // 文件路径
}

function init() {
  // lottie.loadAnimation
  if (lottieRef.value) {
    const config = {
      container: lottieRef.value, // the dom element that will contain the animation
      renderer: props.renderer,
      loop: props.loop,
      autoplay: false,
      path: getJSON(props.name), // the path to the animation json
    }
    if (props.rendererSettings) {
      config.rendererSettings = props.rendererSettings
    }
    animation.value = lottie.loadAnimation(config)
    if (props.autoplay) {
      setTimeout(() => {
        animation.value?.play()
      }, props.delay)
    }
    emits('getAnimation', animation.value)
    emits('getDom', lottieRef.value)
  }
}

defineExpose({
  animation,
})

onMounted(() => {
  init()
})
onUnmounted(() => {
  animation.value?.destroy()
})
watch(
  () => props.isPlay,
  () => {
    if (props.isPlay && lottieRef.value) {
      setTimeout(() => {
        animation.value!.play()
      }, props.delay)
    } else if (!props.isPlay && lottieRef.value) {
      // console.log('props.isPlay',props.isPlay)
      animation.value!.stop()
    }
  },
  { deep: true, immediate: true },
)
</script>

<style lang="scss" scoped>
.lottie__container {
  pointer-events: none;
}
</style>
