<template>
  <transition name="fade">
    <div v-if="visible" class="my-toast" :class="type">
      <div class="toast-content">
        <iconpark-icon v-if="type !== 'default'" :name="iconName" size="16px" :class="['toast-icon', type]" />
        <span>{{ message }}</span>
      </div>
    </div>
  </transition>
</template>
<script setup>
import { nextTick, onMounted, ref, watch, computed, onBeforeUnmount, defineEmits } from "vue";
// 组件逻辑实现
const props = defineProps({
  message: String,
  type: String,
  duration: {
    type: Number,
    default: 2000,
  },
});
const emits = defineEmits(["closeToast"]);
const visible = ref(false);
let timer = null;
// 显示方法
const show = () => {
  if (timer) {
    clearTimeout(timer);
    timer = null;
  }
  visible.value = true;
  if (props.duration > 0) {
    timer = setTimeout(() => {
      visible.value = false;
      timer = null;
      emits("closeToast");
    }, props.duration);
  }
};
onMounted(() => {
  show();
});
// 资源清理
onBeforeUnmount(() => {
  if (timer) {
    clearTimeout(timer);
    timer = null;
  }
});
</script>
<style lang="scss" scoped>
.my-toast {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  z-index: 100001;
  padding: 8px;
  border-radius: 4px;
  background: rgba(0, 0, 0, 0.7);
  color: #fff;
  font-size: 14px;
  line-height: 20px;
  max-width: 80%;

  .toast-content {
    display: flex;
    align-items: center;
    gap: 4px;
  }

  .success {
    color: #52c41a;
  }

  .error {
    color: #ff4d4f;
  }

  .warning {
    color: #faad14;
  }
}

// 动画效果
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.3s ease;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}
</style>
