'use strict';

Object.defineProperty(exports, "__esModule", {
    value: true
});

var _icon = require('../icon');

var _icon2 = _interopRequireDefault(_icon);

var _input = require('../mixins/input');

var _input2 = _interopRequireDefault(_input);

require('./index.less');

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }

var InputNumber = {
    name: 'SnInputNumber',

    mixins: [_input2['default']],

    props: {
        // 是否有小数
        decimal: Boolean,
        integerFigures: {
            type: Number,
            'default': 12
        },
        // 数值精度
        precision: {
            type: Number,
            'default': 2
        },
        percent: Boolean,
        thousandSeparator: {
            type: Boolean,
            'default': true
        },
        unit: String,
        allowMinus: Boolean
    },

    data: function data() {
        return {
            currentValue: '',
            displayValue: '',
            focused: false,
            lastKeyCode: null
        };
    },


    watch: {
        value: function value() {
            if (!this.focused) {
                this.check();
                this.formatter();
            }
        }
    },

    mounted: function mounted() {
        this.check();
        this.formatter();
    },


    methods: {
        check: function check() {
            var value = this.value,
                decimal = this.decimal,
                integerFigures = this.integerFigures,
                precision = this.precision;


            if (value === undefined || value === null || value === '') {
                this.currentValue = '';
            } else {
                var arrValue = ('' + value).split('.');
                var maxInteger = '',
                    maxDecimal = '';

                for (var i = 0; i < integerFigures || i < precision; i++) {
                    if (i < integerFigures) maxInteger += '9';
                    if (i < precision) maxDecimal += '9';
                }

                var maxIntegerValue = integerFigures < arrValue[0].length ? maxInteger : Number(arrValue[0]).toString();

                if (decimal) {
                    this.currentValue = '' + maxIntegerValue + (
                    // 如果整数位大于配置最大整数位，必须带上小数位，中间小数点要包含
                    integerFigures < arrValue[0].length || (arrValue[1] || '').length ? '.' : '') + (integerFigures < arrValue[0].length || precision < (arrValue[1] || '').length ? maxDecimal : arrValue[1] || '');
                } else {
                    this.currentValue = maxIntegerValue;
                }
            }
        },

        /**
         * input输入
         */
        onInput: function onInput(e) {
            e = e || { target: this.$refs.inputRef };
            var el = e.target;
            var val = el.value;
            var decimal = this.decimal,
                integerFigures = this.integerFigures,
                precision = this.precision,
                allowMinus = this.allowMinus;


            if (e.data === null && this.lastKeyCode !== 8 && this.lastKeyCode !== 46) {
                e.target.value = this.currentValue;
                return;
            }

            // 不允许数字开头连续输入0
            if (allowMinus) {
                if (val.indexOf('0') === 1 && val[2] !== undefined && val[2] !== '.') {
                    e.target.value = '-0';
                    return;
                }
            } else {
                if (val.indexOf('0') === 0 && val[1] !== undefined && val[1] !== '.') {
                    e.target.value = '0';
                    return;
                }
            }

            if (decimal) {
                var splitVal = val.split('.');

                // 如果小数点在首位则清空输入值
                if (val.indexOf('.') === 0) {
                    e.target.value = '';
                    return;
                }

                if ((allowMinus ? val.indexOf('-') !== 0 : true) && !this.isNumber(val) && val.indexOf('.') !== val.length - 1) {
                    e.target.value = this.currentValue;
                    return;
                }
                // 小数整数部分不能超过整数位数，小数部分不能超过精度位
                if (splitVal[0].length > integerFigures || splitVal.length > 1 && splitVal[1].length > precision) {
                    e.target.value = this.currentValue;
                    return;
                }
            } else {
                if ((allowMinus ? val.indexOf('-') !== 0 : true) && val !== '' && !this.isInteger(val)) {
                    e.target.value = this.currentValue;
                    return;
                }
                // 整数不能超过整数位数
                if (val.length > integerFigures) {
                    e.target.value = this.currentValue;
                    return;
                }
            }

            this.currentValue = val;
            this.$emit('input', this.currentValue);
        },
        onFocus: function onFocus(e) {
            if (this.editable) {
                if (this.$refs.inputRef) {
                    this.$refs.inputRef.focus();
                    this.focused = true;
                }

                this.$emit('focus', e);
            }
        },
        onBlur: function onBlur(e) {
            var _this = this;

            setTimeout(function () {
                if (_this.$refs.inputRef) {
                    if (document.activeElement !== _this.$refs.inputRef) {
                        _this.formatter();
                        _this.focused = false;
                        _this.$emit('blur', e);
                    }
                }
            }, 150);
        },
        formatter: function formatter() {
            var decimal = this.decimal,
                precision = this.precision,
                thousandSeparator = this.thousandSeparator,
                percent = this.percent,
                unit = this.unit;

            var _displayValue = this.currentValue;

            if (Number.isNaN(Number(_displayValue))) {
                this.currentValue = '';
                _displayValue = '';
            }

            if (percent) {
                Number(this.currentValue) > 100 && (this.currentValue = 100);
            }

            if (this.currentValue !== '') {
                if (thousandSeparator) {
                    _displayValue = this.transformThousandSeparator(this.currentValue, decimal ? precision : 0);
                }

                if (percent) {
                    _displayValue = _displayValue + '%';
                }
            }

            this.displayValue = percent ? _displayValue : '' + _displayValue + (this.currentValue !== '' ? unit !== '' && unit !== undefined ? unit : '' : '');
        },


        /**
         * 千分位转换以及小数点保留位数
         */
        transformThousandSeparator: function transformThousandSeparator(val, precision) {
            var arrVal = ('' + val).split('.');
            var integer = arrVal[0],
                decimal = arrVal[1] || '0';
            var formatInteger = integer.replace(/(\d{1,3})(?=(\d{3})+(?:$|\.))/g, '$1,');

            if (this.decimal) {
                return formatInteger + '.' + Number('0.' + decimal).toFixed(precision).split('.')[1];
            } else {
                return formatInteger;
            }
        },


        /**
         * 禁止输入非数字
         */
        onKeyDown: function onKeyDown(e) {
            var k = window.event ? e.keyCode : e.which;
            this.lastKeyCode = k;
            this.focused = true;
            /**
             * k === 109 || k === 189 减号
             * (k >= 48 && k <= 57) (k >= 96 && k <= 105) 主键盘和副键盘键入数字 0~9
             * k === 110 || k === 190 分别是主副小数点键
             * k === 46 删除键
             * k === 37 || k === 39 分别是左右键
             * k === 8 回退键
             * k === 0
             */
            var isMinus = this.allowMinus ? k === 189 || k === 109 : false;
            var isInteger = k >= 48 && k <= 57 || k >= 96 && k <= 105 || k === 46 || k === 39 || k === 37 || k === 8 || k === 0;
            var isNumber = isInteger || k === 190 || k === 110;
            var rule = (this.decimal ? isNumber : isInteger) || isMinus;

            if (rule) {
                return true;
            } else {
                if (window.event) {
                    window.event.returnValue = false;
                } else {
                    e.preventDefault();
                }

                return false;
            }
        },


        /**
         * change 事件
         */
        onChange: function onChange() {
            this.$emit('change', this.currentValue);
        },


        /**
         * 阻止在pc上焦点丢失
         */
        onClearMouseDown: function onClearMouseDown(e) {
            e.preventDefault();
        },


        /**
         * 清除输入框内容
         */
        onClear: function onClear() {
            this.displayValue = '';
            this.currentValue = '';
            this.$refs.inputRef.value = '';

            this.onFocus();
            this.$emit('input', '');
            this.$emit('clear');
        }
    },

    render: function render() {
        var h = arguments[0];
        var currentValue = this.currentValue,
            displayValue = this.displayValue,
            focused = this.focused,
            placeholder = this.placeholder,
            editable = this.editable,
            disabled = this.disabled,
            decimal = this.decimal,
            clear = this.clear,
            allowMinus = this.allowMinus;


        var _value = focused ? currentValue : displayValue;
        var inputType = decimal ? 'text' : allowMinus ? 'text' : 'tel';
        var inputMode = allowMinus ? 'text' : decimal ? 'decimal' : 'numeric';
        var renderClearIcon = focused && clear && editable && !disabled && currentValue && currentValue !== '' ? h(_icon2['default'], {
            attrs: {
                type: 'close-circle-fill'
            },
            'class': 'sn-input-number-clear',
            on: {
                'mousedown': this.onClearMouseDown,
                'click': this.onClear
            }
        }) : null;

        return h(
            'div',
            { 'class': 'sn-input-number' },
            [h('input', {
                ref: 'inputRef',
                attrs: { type: inputType,
                    inputmode: inputMode,

                    placeholder: placeholder,
                    disabled: disabled,
                    readonly: !editable
                },
                'class': 'sn-input-number-control',
                domProps: {
                    'value': _value
                },
                on: {
                    'keydown': this.onKeyDown,
                    'input': this.onInput,
                    'focus': this.onFocus,
                    'blur': this.onBlur,
                    'change': this.onChange
                }
            }), renderClearIcon]
        );
    }
};

InputNumber.install = function (Vue) {
    Vue.component(InputNumber.name, InputNumber);
};

exports['default'] = InputNumber;
module.exports = exports.default;