import Vue from 'vue'
//input 限制输入正整数以及自定义小数位数
//v-price
//v-price="{digit:小数位数，maxNum：最大值}"
Vue.directive('price', {
    inserted: function (el, binding, vnode) {
        let dom = null
        if (el.tagName == 'INPUT') {
            dom = el
        } else {
            dom = el.querySelector('input')
        }
        dom.addEventListener('input', function () {
            if (binding.value) {
                checkValue(dom, binding.value.digit,binding.value.maxNum)
            } else {
                checkValue(dom, 3, null)
            }
        })

        function checkValue(el, defu, maxNum) {
            if (maxNum && el.value > maxNum) {
                el.value = maxNum
                el.dispatchEvent(new Event("input"));//调用input事件使vue v-model绑定更新
            }
            let num = new RegExp(`(^[\\-0-9][0-9]*(.[0-9]+)?)$`) // 是否为数字
            let reg = new RegExp("^[0-9]*$");//正整数
            let littleNum = new RegExp(`^(0|[1-9]\\d{0,${defu}})(\\.\\d{1,${defu}})?$`)//自定义小数位数
            if (el.value &&!num.test(+el.value)) {
                el.value = el.value.replace(/[^\d.]/g, "");  //清除“数字”和“.”以外的字符
                el.dispatchEvent(new Event("input"));//调用input事件使vue v-model绑定更新
            }
            if (el.value && !littleNum.test(+el.value) && !reg.test(+el.value)) {
                el.value = el.value.replace(/\.{2,}/g, "."); //只保留第一个. 清除多余的
                el.value = el.value.replace(".", "$#$").replace(/\./g, "").replace("$#$", ".");
                el.value = el.value.replace(new RegExp(`^(.*\\..{${defu}}).*$`), "$1");//只能输入自定义个小数
                el.dispatchEvent(new Event("input"));//调用input事件使vue v-model绑定更新
            }
        }
    }
})
