import { Directive } from 'vue'

// 文本框回车切换
export const enterfocus: Directive = {
    mounted(el, binding) {
        // 获取input列表
        const inputs = el.getElementsByTagName('input');
        const inputList = [...inputs];
        const { value } = binding;
        el.value = value

        el.handler = (params: { keyCode: number }) => {
            // 按回车键处理
            if (params.keyCode === 13 && inputList.length > 0) {
                const isFlag = inputList.every((itemEle) => {
                    // 判断文本框为空自动对焦
                    if (itemEle.value === '') {
                        itemEle.focus();
                    }
                    return itemEle.value !== "";
                })

                // 判断是函数才可以进入
                if (el.value && el.value instanceof Function && isFlag) {
                    el.value()
                }
            }
        }

        // 监听回车事件
        el.addEventListener("keyup", el.handler)
    },
    beforeUnmount(el) {
        // 销毁回车事件
        el.value = null
        el.removeEventListener("keyup", el.handler)
    }
}