import './style.scss';
import { JDTabTpls } from './tpl';
import BaseFormControl from "../../baseFormControl";
class JDTabComponent extends BaseFormControl {
    constructor(options) {
        super();
        
        this.radioData = null;
        this.setConfig(options);
        this.render();
    }
    
    setConfig(config) {
        this.config = $.extend(true, {}, {
            domData: {},
            defaultChecked: 0,
            disableInitChange: true,
            change: () => {
            },
            ready: () => {
            },
        }, config);
    }
    render() {
        let tabsOpts = this.config.domData.formType.option;
        let $Node = template.render(JDTabTpls, {
            options: tabsOpts,
            selected: this.config.defaultChecked,
        });
        this.appendFormControl($Node);
        this.addEvent();
        this.config.ready();
    }
    addEvent() {
        this.element.find('.J_tab_item').on('click', (evt) => {
            let $Node = $(evt.target);
            this.setData($Node.attr('value'));
        });
        if (!this.config.disableInitChange) {
            this.element.find('.J_tab_item').each((i, el) => {
                let $Node = $(el);
                if ($Node.hasClass('cd-icons-tab-selected')) {
                    $Node.trigger('click');
                }
            });
        }
    }
    setSelectedStyle() {
        this.element.find('.J_tab_item').each((i, el) => {
            let $Node = $(el);
            if (this.radioData && this.radioData[this.config.domData.name] == $Node.attr('value')) {
                $Node.siblings('.J_tab_item').removeClass('cd-icons');
                $Node.siblings('.J_tab_item').removeClass('cd-icons-tab-selected');
                $Node.addClass('cd-icons');
                $Node.addClass('cd-icons-tab-selected');
            }
        });
    }
    
    setData(value) {
        let Obj = {};
        let key = this.config.domData.name;
        if (key) {
            Obj[key] = value;
            this.radioData = Obj;
            this.setSelectedStyle(value);
            this.config.change(this.radioData[this.config.domData.name]);
        } else {
            throw new Error('this.config.domData.name is empty');
        }
    }
    
    getData() {
        if (this.radioData) {
            return this.radioData;
        } else {
            return null;
        }
    }
}
export default JDTabComponent;