import Icon from '../icon';
import InputMixin from '../mixins/input';
import { raf } from '../_utils/dom/raf';
import './index.less';

var Search = {
    name: 'SnSearch',

    mixins: [InputMixin],

    props: {
        maxlength: {
            type: [Number, String],
            'default': 50
        },
        placeholder: {
            type: String,
            'default': '搜索'
        },
        cancelText: {
            type: String,
            'default': '取消'
        },
        cancelColor: String,
        inputBgColor: String,
        bgColor: String
    },

    data: function data() {
        return {
            defaultValue: '',
            currentValue: '',
            focused: false,
            firstFocus: false,
            blurFromOnClear: false
        };
    },


    watch: {
        value: function value(newVal) {
            this.currentValue = newVal;

            if (!this.focused) {
                this.init();
            }
        }
    },

    mounted: function mounted() {
        if (this.$refs.cancelRef) {
            var width = this.getWidthByRef('cancelRef');
            this.cancelWidth = width;
            this.$refs['cancelRef'].style.marginRight = '-' + width + 'px';
        }
    },


    methods: {
        getWidthByRef: function getWidthByRef(ref) {
            if (this.$refs[ref]) {
                var rect = this.$refs[ref].getBoundingClientRect();
                return rect.width;
            }

            return 0;
        },
        init: function init() {
            if (this.currentValue === '') {
                this.$refs['placeholderRef'] && (this.$refs['placeholderRef'].style.width = '100%');
                this.$refs['cancelRef'] && (this.$refs['cancelRef'].style.marginRight = '-' + this.cancelWidth + 'px');
            }
        },

        /**
         * 获取焦点
         */
        onFocus: function onFocus(e) {
            var _this = this;

            if (!this.disabled) {
                if (this.$refs.inputRef) {
                    this.$refs.inputRef.focus();
                    this.focused = true;
                    this.firstFocus = true;

                    this.$nextTick(function () {
                        var placeholderWidth = _this.getWidthByRef('containerRef');
                        _this.$refs['placeholderRef'].style.width = placeholderWidth + 'px';
                        _this.$refs['cancelRef'].style.marginRight = '0';
                    });
                }

                this.$emit('focus', e);
            }
        },


        /**
         * 丢失焦点
         */
        onBlur: function onBlur(e) {
            var _this2 = this;

            raf(function () {
                if (!_this2.blurFromOnClear) {
                    _this2.focused = false;

                    _this2.$emit('blur', e);
                }

                _this2.init();
                _this2.blurFromOnClear = false;
            });
        },
        onClearMouseDown: function onClearMouseDown(e) {
            e.preventDefault();
        },

        /**
         * 清除搜索内容
         */
        onClear: function onClear() {
            this.doClear();
        },
        doClear: function doClear() {
            var blurFromOnClear = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;

            this.blurFromOnClear = blurFromOnClear;
            this.currentValue = '';

            this.$emit('clear');
            this.$emit('change');

            if (blurFromOnClear) {
                this.onFocus();
            }
        },

        /**
         * 取消按钮
         */
        onCancel: function onCancel() {
            this.currentValue = '';
            this.onBlur();
            this.$emit('cancel');
            this.$emit('submit', '');

            this.doClear(false);
        },

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

            this.$emit('input', this.currentValue);
        },

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

        /**
         * 提交搜索
         */
        onSubmit: function onSubmit(e) {
            e.preventDefault();
            this.$emit('submit', this.currentValue);

            if (this.$refs.inputRef) {
                this.$refs.inputRef.blur();
            }
        }
    },

    render: function render() {
        var h = arguments[0];
        var currentValue = this.currentValue,
            focused = this.focused,
            placeholder = this.placeholder,
            disabled = this.disabled,
            maxlength = this.maxlength,
            clear = this.clear,
            cancelText = this.cancelText,
            cancelColor = this.cancelColor,
            bgColor = this.bgColor,
            inputBgColor = this.inputBgColor;


        var renderClearIcon = focused && clear && !disabled && currentValue && currentValue !== '' ? h(Icon, {
            attrs: {
                role: 'button',
                type: 'close-circle-fill'
            },
            'class': 'sn-search-clear',
            on: {
                'mousedown': this.onClearMouseDown,
                'click': this.onClear
            }
        }) : null;

        var renderCancel = h(
            'div',
            {
                'class': {
                    'sn-search-cancel': true,
                    'sn-search-cancel-anim': this.firstFocus
                },
                style: {
                    paddingLeft: cancelText === '' ? 0 : undefined,
                    color: cancelColor
                },
                on: {
                    'click': this.onCancel
                },

                ref: 'cancelRef'
            },
            [cancelText]
        );

        return h(
            'form',
            {
                'class': 'sn-search',
                style: { backgroundColor: bgColor },
                attrs: { action: ''
                },
                on: {
                    'submit': this.onSubmit
                }
            },
            [h(
                'div',
                {
                    'class': {
                        'sn-search-input': true,
                        'sn-search-input-progressing': focused || currentValue,
                        'sn-search-input-clear': focused && clear && !disabled && currentValue && currentValue !== ''
                    },
                    style: { backgroundColor: inputBgColor }
                },
                [h(
                    'div',
                    { 'class': 'sn-search-placeholder', ref: 'placeholderRef' },
                    [h(
                        'span',
                        {
                            'class': 'sn-search-placeholder-container',
                            ref: 'containerRef'
                        },
                        [h(Icon, {
                            attrs: {
                                type: 'search'
                            },
                            'class': 'sn-search-placeholder-icon'
                        }), h(
                            'span',
                            {
                                'class': 'sn-search-placeholder-text',
                                style: {
                                    visibility: placeholder && !currentValue ? 'visible' : 'hidden'
                                }
                            },
                            [placeholder]
                        )]
                    )]
                ), h('input', {
                    'class': 'sn-search-control',
                    ref: 'inputRef',
                    attrs: { type: 'search',

                        maxlength: maxlength,
                        disabled: disabled,
                        placeholder: placeholder
                    },
                    domProps: {
                        'value': currentValue
                    },
                    on: {
                        'focus': this.onFocus,
                        'blur': this.onBlur,
                        'change': this.onChange,
                        'input': this.onInput
                    }
                }), renderClearIcon]
            ), renderCancel]
        );
    }
};

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

export default Search;