import {Ref, ref} from 'vue'
import {ElMessage} from "element-plus";


const direction: string[] = ['ArrowRight', 'ArrowLeft', 'ArrowDown', 'ArrowUp']
export const xcEvent: Ref<Event | null> = ref(null)

document.onkeydown = function (event: KeyboardEvent): void {
    xcEvent.value = event
}

export const shortcutTrigger = (event, registerShortcuts, disabled = false) => {
    for (let listKey in registerShortcuts) {
        let data = registerShortcuts[listKey]
        for (let key in data) {
            // 同时按下
            let pressSimultaneously = listKey + 'Key'
            if (event[pressSimultaneously] && event.key === key) {
                event.returnValue = false
                event.preventDefault()
                if (whetherToDisable(disabled)) return;
                data[key]()
                return
            }
            if (key === 'direction') {
                if ((event[pressSimultaneously] && direction.includes(event.code))) {
                    event.returnValue = false
                    event.preventDefault()
                    if (whetherToDisable(disabled)) return;
                    data['direction'](event.key)
                    return
                }
            }
            if (key === 'number') {
                if (event[pressSimultaneously] && event.code === ('Digit' + event.key)) {
                    event.returnValue = false
                    event.preventDefault()
                    if (whetherToDisable(disabled)) return;
                    data['number'](event.key)
                    return
                }
            }
        }
        if (listKey === event.key) {
            event.returnValue = false
            event.preventDefault()
            if (whetherToDisable()) return;
            registerShortcuts[listKey]()
            return
        }
    }
}

function whetherToDisable(disabled = false) {
    // 这个打开是时候是不触发
    if (disabled) {
        ElMessage({
            message: '当前快捷键无法使用',
            type: 'warning',
            showClose: true,
            grouping: true,
        })
    }
    return disabled
}
