import InputMxin from '../mixins/input';
import './index.less';

var Textarea = {
    name: 'SnTextarea',

    mixins: [InputMxin],

    props: {
        rows: {
            type: [String, Number],
            'default': 1
        },
        autosize: {
            type: Boolean,
            'default': true
        },
        maxlength: {
            type: Number,
            'default': 200
        }
    },

    computed: {
        style: function style() {
            var style = {
                height: this.height || 'auto'
            };
            if (this.maxHeight) {
                style.maxHeight = this.maxHeight;
            }
            return style;
        }
    },

    watch: {
        value: function value() {
            var _this = this;

            this.$nextTick(function () {
                _this.adjustHeight();
            });
        }
    },

    mounted: function mounted() {
        if (this.value !== '' && this.$refs.textarea) {
            this.adjustHeight();
        }
    },


    methods: {
        setValue: function setValue(value) {
            this.$refs.textarea.value = value;
        },
        onInput: function onInput(event) {
            this.adjustHeight();
            this.$emit('input', event.target.value);
        },
        adjustHeight: function adjustHeight() {
            if (this.autosize) {
                this.$refs.textarea.style.height = 'auto';
                this.$refs.textarea.style.height = this.$refs.textarea.scrollHeight + 1 + 'px';
            }
        },
        onFocus: function onFocus(e) {
            this.$emit('focus', e);
        },
        onBlur: function onBlur(e) {
            this.$emit('blur', e);
        },
        onChange: function onChange(e) {
            this.$emit('change', e.target.value);
        }
    },
    render: function render() {
        var h = arguments[0];
        var value = this.value,
            rows = this.rows,
            placeholder = this.placeholder,
            maxlength = this.maxlength,
            editable = this.editable,
            disabled = this.disabled;


        return h('textarea', {
            ref: 'textarea',
            'class': 'sn-textarea',
            attrs: { rows: rows,

                placeholder: placeholder,
                maxlength: maxlength,
                readonly: !editable,

                disabled: disabled
            },
            style: this.style, domProps: {
                'value': value
            },
            on: {
                'input': this.onInput,
                'focus': this.onFocus,
                'blur': this.onBlur,
                'change': this.onChange
            }
        });
    }
};

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

export default Textarea;