import {ElMessage} from "element-plus";

let registerShortcuts = null
const direction = ['ArrowRight', 'ArrowLeft', 'ArrowDown', 'ArrowUp']
let disabled = false

export const xcHotKey = (keyList) => {
    console.log('快捷键')
    enableShortcutKeys()
    registerShortcuts = keyList
    document.onkeydown = function (event) {
        shortcutTrigger(event)
    }
}

export const logoutShortcut = () => {
    document.onkeydown = null
    registerShortcuts = null
}

export const disableShortcutKeys = () => {
    disabled = true
}

export const enableShortcutKeys = () => {
    disabled = false
}


/**
 * 快捷键触发事件
 * @param event
 */
const shortcutTrigger = (event) => {
    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()) return;
                data[key]()
                return
            }
            if (key === 'direction') {
                if ((event[pressSimultaneously] && direction.includes(event.code))) {
                    event.returnValue = false
                    event.preventDefault()
                    if (whetherToDisable()) return;
                    data['direction'](event.key)
                    return
                }
            }
            if (key === 'number') {
                if (event[pressSimultaneously] && event.code === ('Digit' + event.key)) {
                    event.returnValue = false
                    event.preventDefault()
                    if (whetherToDisable()) return;
                    data['number'](event.key)
                    return
                }
            }
        }
        if (listKey === event.key) {
            event.returnValue = false
            event.preventDefault()
            if (whetherToDisable()) return;
            registerShortcuts[listKey]()
            return
        }
    }
}

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