import { computed, ref } from 'vue'
import { mount } from '../../utils/componentHelper'
import { toRawType } from '../../utils/index'
import Message from './message.vue'

const types = ['success', 'warning', 'error']

Message.use = function use(app) {
    const indexs = ref([])
    Message.show = function (config) {
        if (toRawType(config) === 'String') {
            config = { msg: config }
        }

        config.time = config.time || 3000
        config.type = types.includes(config.type) ? config.type : types[0]

        const instance = ref(null)
        const index = computed(() => (instance.value ? indexs.value.indexOf(instance) : 0))
        const hide = () => {
            instance.value.destroy()
            indexs.value = indexs.value.filter(i => i !== instance.value)
        }

        instance.value = mount(Message, {
            app,
            props: {
                ...config,
                index,
                destroy: hide,
            },
        })
        indexs.value.push(instance)
    }

    for (const type of types) {
        Message[type] = config => {
            if (toRawType(config) === 'String') {
                config = {
                    msg: config,
                    type,
                }
            }
            return Message.show(config)
        }
    }
}

export default Message
