import './style.scss';
import BaseFormControl from '../../baseFormControl';
import { JDTextAreaTpl } from './tpl';
class JDTextArea extends BaseFormControl {
    constructor(config) {
        super(config);
        this.setConfig(config);
        this.render();
    }
    
    setConfig(config) {
        this.config = $.extend(true, {}, {
            domData: {
                formType: {
                    placeholder: '文本输入',
                },
            },
            value: '',
            autofocus: false,
            cols: 3,
            rows: 5,
            disabled: '',
            maxlength: 1000000000,
            name: 'JDTextArea',
            readonly: '',
            required: true,
            change: (text) => {
            },
            blur: (text) => {
            },
            focus: (text) => {
            },
            select: (text) => {
            },
        }, config);
    }
    
    render() {
        this.setValue();
        let textAreaNode = template.render(JDTextAreaTpl, { ...this.config });
        this.appendFormControl(textAreaNode);
        this.addEvent();
    }
    
    setValue(value) {
        if (typeof value === 'string') {
            this.config.value = value;
        } else if (this.config.moduleData) {
            this.config.value = this.config.moduleData;
        }
    }
    
    addEvent() {
        this.element.find('.J_textArea').on('change', (evt) => {
            let textAreaValue = $(evt.target).val();
            if (this.validate(textAreaValue)) {
                this.setValue(textAreaValue);
                this.config.change(this.config.value);
            }
        }).on('focus', (evt) => {
            let textAreaValue = $(evt.target).val();
            if (this.validate(textAreaValue)) {
                this.setValue(textAreaValue);
                this.config.focus(this.config.value);
            }
        }).on('blur', (evt) => {
            let textAreaValue = $(evt.target).val();
            if (this.validate(textAreaValue)) {
                this.setValue(textAreaValue);
                this.config.blur(this.config.value);
            }
        }).on('select', (evt) => {
            this.config.select(this.getSelectedValue(evt.target));
        });
    }
    
    getSelectedValue(node) {
        if (document.selection) {
            return document.selection.createRange().text;
        } else {
            return node.value.substring(node.selectionStart, node.selectionEnd);
        }
    }
    
    validate(value) {
        return true;
    }
    
    getData() {
        this.element.find('.J_textArea').trigger('change');
        return {
            [this.config.domData.name]: this.config.value,
        };
    }
}
export default JDTextArea;