import './style.scss'
import ColorPicker from '../../../colorPicker'
import BaseFormControl from "../../baseFormControl";
import {JDColorTpl} from "./tpl";
const COLOR_REG = /^#([a-fA-F0-9]{6}|[a-fA-F0-9]{3})$/
class JDInputColor extends BaseFormControl {
    constructor(config) {
        super(config);
        this.setConfig(config);
        this.render();
    }
    
    setConfig(config) {
        this.config = $.extend(true, {}, {
            domData: {},
            value: null
        }, config);
    }
    
    setColorValue(value) {
        if (value) {
            this.config.value = value;
        } else {
            if (this.config.moduleData) {
                this.config.value = this.config.moduleData;
            }
        }
    }
    
    render() {
        this.setColorValue();
        let colorTpl = template.render(JDColorTpl, {...this.config});
        this.appendFormControl(colorTpl);
        this.addEvent();
    }
    
    addEvent() {
        const _this = this;
        this.element.find('.J_color_node').colorpicker({
            onColorChange: (rgb, hex) => {
                this.setColorValue(hex);
                _this.element.find('.J_bgColor').val(hex)
            },
            onOK: (rgb, hex) => {
                this.setColorValue(hex);
                return true;
            },
            onCancel: (rgb, hex) => {
                this.setColorValue(hex);
                return true;
            }
        });
        this.element.find('.J_bgColor').on('change', function () {
            let color = $(this).val()
            if (color === '' || COLOR_REG.test(color)) {
                _this.element.find('.J_color_node').css({
                    backgroundColor: color,
                })
            }
        })
    }
    getData() {
        let colorData = {};
            colorData[this.config.domData.name] = this.element.find('.J_bgColor').val() ? this.config.value : '';
            return colorData;
    }
}
export default JDInputColor;