'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);

var _raf = require('../_utils/dom/raf');

require('./index.less');

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

var Input = {
    name: 'SnInput',

    mixins: [_input2['default']],

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


    watch: {
        value: function value(val) {
            !this.focused && this.update(val);
        }
    },

    mounted: function mounted() {
        var value = this.value;


        if (value === undefined || value === null) {
            this.defaultValue = '';
        } else {
            this.defaultValue = '' + value;
        }

        this.update(this.defaultValue);
    },


    methods: {
        /**
         * 更新外部传入value值
         */
        update: function update(val) {
            this.currentValue = val;
            this.displayValue = val;

            if (this.$refs.inputRef) {
                this.$refs.inputRef.value = val;

                this.onInput();
            }
        },


        /**
         * input输入
         */
        onInput: function onInput(e) {
            var _this = this;

            e = e || { target: this.$refs.inputRef };
            var el = e.target;
            var val = el.value;
            var pos = el.selectionStart;
            var _maxLength = void 0,
                _val = void 0,
                _chunkSize = void 0;
            var type = this.type,
                maxlength = this.maxlength,
                chunkSize = this.chunkSize,
                focused = this.focused;

            var emoji = /[^\u0020-\u007E\u00A0-\u00BE\u2E80-\uA4CF\uF900-\uFAFF\uFE30-\uFE4F\uFF00-\uFFEF\u0080-\u009F\u2000-\u201f\u2026\u2022\u20ac\r\n]/g;

            // 阻止ios九宫格软键盘重复键入
            if (type !== 'text' && e.data === null && e.inputType === 'insertText' && this.lastKeyCode !== 8 && this.lastKeyCode !== 46 && !this.ctrlKey) {
                e.target.value = this.displayValue;
                return;
            }

            switch (type) {
                case 'phone':
                    _maxLength = 11;
                    _val = val.replace(/\D/g, '').substring(0, _maxLength);

                    if (_val.length && _val[0] !== '1') {
                        _val = '';
                        this.displayValue = '';
                    } else if (_val.length > 3 && _val.length < 8) {
                        this.displayValue = _val.substr(0, 3) + ' ' + _val.substr(3);
                    } else if (_val.length >= 8) {
                        this.displayValue = _val.substr(0, 3) + ' ' + _val.substr(3, 4) + ' ' + _val.substr(7);
                    } else {
                        this.displayValue = _val;
                    }

                    this.currentValue = _val;
                    el.value = this.displayValue;

                    if (focused) {
                        setTimeout(function () {
                            if (_this.lastKeyCode === 8 || _this.lastKeyCode === 46) {
                                // 如果当前按键是删除键并且下一个字符为空格时，则向后退一格
                                if (_this.lastKeyCode === 46 && _this.displayValue[pos] === ' ') {
                                    pos += 1;
                                }
                                el.selectionStart = el.selectionEnd = pos;
                            } else {
                                if (pos === 4 || pos === 9) {
                                    pos += 1;
                                }
                                if (pos < val.length) {
                                    el.selectionStart = el.selectionEnd = pos;
                                } else {
                                    el.selectionStart = el.selectionEnd = el.value.length;
                                }
                            }
                        });
                    }

                    break;
                case 'conference':
                case 'bankCard':
                    if (type === 'conference') {
                        _maxLength = maxlength || 9;
                        _chunkSize = chunkSize || 3;
                    }
                    if (type === 'bankCard') {
                        _maxLength = maxlength || 16;
                        _chunkSize = chunkSize || 4;
                    }

                    _val = val.replace(/\D/g, '').substring(0, _maxLength);
                    this.displayValue = _val.replace(new RegExp('(.{' + _chunkSize + '})', 'g'), '$1 ').trim();

                    this.currentValue = _val;
                    el.value = this.displayValue;

                    if (focused) {
                        setTimeout(function () {
                            if (_this.lastKeyCode === 8 || _this.lastKeyCode === 46) {
                                // 如果当前按键是删除键并且下一个字符为空格时，则向后退一格
                                if (_this.lastKeyCode === 46 && _this.displayValue[pos] === ' ') {
                                    pos += 1;
                                }
                                el.selectionStart = el.selectionEnd = pos;
                            } else {
                                if (_this.displayValue[pos - 1] === ' ') {
                                    pos += 1;
                                }
                                if (pos < val.length) {
                                    el.selectionStart = el.selectionEnd = pos;
                                } else {
                                    el.selectionStart = el.selectionEnd = el.value.length;
                                }
                            }
                        });
                    }

                    break;
                default:
                    _maxLength = maxlength || 50;
                    _val = val.replace(emoji, '').substring(0, _maxLength);

                    this.currentValue = _val;
                    this.displayValue = _val;

                    break;
            }

            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 _this2 = this;

            (0, _raf.raf)(function () {
                if (_this2.$refs.inputRef) {
                    if (document.activeElement !== _this2.$refs.inputRef) {
                        _this2.focused = false;
                        _this2.$emit('blur', e);
                    }
                }
            });
        },


        /**
         * 禁止输入非数字
         */
        onKeyDown: function onKeyDown(e) {
            var k = window.event ? e.keyCode : e.which;
            var ctrlKey = e.ctrlKey;
            this.lastKeyCode = k;
            this.ctrlKey = ctrlKey;
            this.focused = true;

            /**
             * 组合键
             * (ctrlKey && k === 65) Ctrl键和a键-全选功能
             * (ctrlKey && k === 67) Ctrl键和c键-复制功能
             * (ctrlKey && k === 86) Ctrl键和v键-粘贴功能
             * (ctrlKey && k === 90) Ctrl键和z键-撤销功能
             */
            var combinationKey = ctrlKey && k === 65 || ctrlKey && k === 67 || ctrlKey && k === 86 || ctrlKey && k === 90;

            /**
             * (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 isDigit = k >= 48 && k <= 57 || k >= 96 && k <= 105 || k === 46 || k === 39 || k === 37 || k === 8 || k === 0 || combinationKey;

            var rule = void 0;

            switch (this.type) {
                case 'text':
                case 'password':
                    rule = 1;
                    break;
                case 'phone':
                case 'conference':
                case 'bankCard':
                    rule = isDigit;
                    break;
                default:
                    rule = 1;
                    break;
            }

            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,
            type = this.type,
            focused = this.focused,
            placeholder = this.placeholder,
            editable = this.editable,
            disabled = this.disabled,
            maxlength = this.maxlength,
            clear = this.clear;


        var inputType = 'text',
            inputMode = 'text';

        if (type === 'phone' || type === 'conference' || type === 'bankCard') {
            inputType = 'tel';
            inputMode = 'numeric';
        } else if (type === 'password') {
            inputType = 'password';
        } else {
            inputType = type;
        }

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

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

                    maxlength: type === 'text' || type === 'password' ? maxlength : undefined,
                    placeholder: placeholder,
                    disabled: disabled,
                    readonly: !editable
                },
                'class': 'sn-input-control',
                domProps: {
                    'value': displayValue
                },
                on: {
                    'keydown': this.onKeyDown,
                    'input': this.onInput,
                    'focus': this.onFocus,
                    'blur': this.onBlur,
                    'change': this.onChange
                }
            }), renderClearIcon]
        );
    }
};

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

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