<script lang="ts" setup>
import { onMounted, ref } from 'vue'
import { CMessageType, CMessageOptions } from './message'

interface MessageIconItem {
  color: string
  icon: string
}

interface Props {
  config: CMessageOptions
  remove: () => void
}

const visible = ref(false)

const props = defineProps<Props>()

const messageIconList: { [k in CMessageType]: MessageIconItem } = {
  text: {
    icon: '',
    color: '#333333',
  },
  warning: {
    icon: 'icon-warning',
    color: '#F0A020',
  },
  info: {
    icon: 'icon-info',
    color: '#2080F0',
  },
  error: {
    icon: 'icon-error',
    color: '#D03050',
  },
  success: {
    icon: 'icon-success',
    color: '#18A058',
  },
}

onMounted(() => {
  handleOpen()
})

function handleOpen() {
  visible.value = true

  if (props.config.duration !== 0) {
    setTimeout(() => {
      handleClose()
    }, props.config.duration)
  }
}

function handleClose() {
  visible.value = false
  props.remove()
}
</script>

<template>
  <transition name="slide-fade">
    <div v-show="visible" class="message-container">
      <div class="message-content flex items-center">
        <div v-if="messageIconList[config.type].icon" class="mr-2.5 h-5 w-5">
          <i
            class="iconfont flex h-[22px] items-center justify-center text-[20px]"
            :class="[messageIconList[config.type].icon]"
            :style="{ color: messageIconList[config.type].color }"
          />
        </div>

        <span class="break-all" v-text="config.content" />

        <div
          v-if="config.close"
          class="hover:bg-background-color rounded-theme ml-2.5 flex h-6 w-6 cursor-pointer items-center justify-center"
          @click="handleClose"
        >
          <i class="iconfont icon-close text-font-color text-sm" />
        </div>
      </div>
    </div>
  </transition>
</template>
