
import Vue from 'vue'
const toggleShake = (el, binding) => {
    if (binding.value) {
        Vue.nextTick(() => {
            const shakeTimes = binding.value.times || 1; // 震动次数
            const shakeDistance = binding.value.distance || 2; // 震动距离
            const shakeDuration = binding.value.duration || '0.5s'; // 震动持续时间
            el.style.animation = 'shake '+ shakeDuration
            el.style.animationIterationCount = shakeTimes 
            setTimeout(() => {
                el.style.animation = '';
                el.style.animationIterationCount=''
            }, 1000);
            // 使用定时器实现震动效果
            // let counter = 0;
        
            // const shake = () => {
            //     if (counter++ < shakeTimes) {
            //     const rand = Math.random() * shakeDistance;
            //     const x = el.offsetLeft + rand - rand;
            //     const y = el.offsetTop + rand;
            //     el.style.position = 'absolute';
            //     el.style.transform = `translate3d(${rand}px, ${rand}px, 0)`;
            //     setTimeout(() => {
            //         el.style.transform = '';
            //         shake();
            //     }, shakeDuration);
            //     }
            // };
 
            // shake();
        })
    }
}

export default{
    bind:function(el, binding, vnode){
        if(!binding.value){
            return
        }
        if(!binding.value.shake){
            return
        }
        toggleShake(el, binding)
    },
    update: function (el, binding) {
        if(!binding.value){
            return
        }
        if(!binding.value.shake){
            return
        }
        toggleShake(el, binding)
    },
    unbind: function (el, binding) {
        el.style.position='';
    }
}