import './style.scss';
import RadioButton, { RadioGroup }  from '../../../radioButton'
import BaseFormControl from '../../baseFormControl';
import { JDRadioTpl } from './tpl';
class JDRadio extends BaseFormControl {
    constructor(config) {
        super();
        this.name = 'JDRadio';
        
        this.radioData = null;
        this.eldUIGroupRadio;
        this.setConfig(config);
        this.render();
    }
    
    setConfig(config) {
        this.config = $.extend(true, {}, {
            disabled: false,
            domData: {},
            defaultChecked: '0',
            singleAutoHide: false,       
            change: () => {
            },
            onDomReady: () => {
            },
        }, config);
    }
    
    render() {
        let radioOpts = this.config.domData.formType.option;
        let eldUIRadioInstances = [];
        let $RadioButtonNode;
        if(this.config.singleAutoHide && this.config.domData.formType.option.length <= 1){
            this.element.hide();
        }
        this.appendFormControl(JDRadioTpl);
        $RadioButtonNode = this.element.find('.J_JDRadio_content');
        
        if (this.config.domData) {
            $RadioButtonNode.attr('radioType', this.config.domData.dataType);
        }
        if (radioOpts.length && $RadioButtonNode.length) {
            for (let i = 0, Ln = radioOpts.length; i < Ln; i++) {
                let item = radioOpts[i];
                eldUIRadioInstances.push(new RadioButton({
                    node: $RadioButtonNode,
                    className: "cd-radio1",
                    groupName: "grup1",
                    label: item.text,
                    value: item.value,
                    disabled: this.config.disabled,
                    onDomReady: () => {
                        this.config.onDomReady($RadioButtonNode);
                    },
                }));
            }
        }
        if (!(this.eldUIGroupRadio instanceof RadioGroup) && eldUIRadioInstances.length) {
            this.eldUIGroupRadio = new RadioGroup({
                group: eldUIRadioInstances,
                selectedValue: this.config.defaultChecked, 
                onChange: (value) => {
                    this.config.change(value);
                    this.setData(value);
                },
            });
        }
    }
    
    setData(value) {
        let Obj = {};
        let key = this.config.domData.name;
        if (key) {
            Obj[key] = value;
            this.radioData = Obj;
        } else {
            throw new Error('this.config.domData.name is empty');
        }
    }
    
    getData() {
        if (this.radioData) {
            return this.radioData;
        } else {
            return null;
        }
    }
}
export default JDRadio;