"use strict";

import {util} from "../../../../util/util.js";

class componentForm {
    constructor(data) {
        this.data = data;
        //给当前对象创建一个id，同时该id也是对象的domid
        this.eleID = util.getUUID();
        this.objID = this.eleID + 'div';
    }
    remove() {
        $('#' + this.objID).remove();
    }
    getData() {
        return this.data;
    }
    getObjID() {
        return this.objID;
    }
    render(renderParentID) {
        //todo 待实现更多展示类型，暂时都默认只有文本
        let that=this;
        let html='<div class="py-3" id="'+that.objID+'">';
        html+='<ul class="sidenav-inner py-3 ps ps--active-y">'
        for(let j=0;j< that.data.dataList.length;j++){
            html+=`<div class="form-group row">
                       <label class="col-form-label text-sm-right" style="width: 100px">${that.data.dataList[j].label_name}</label>
                       <div class="col-sm-7">
                           <input type="text" name="${that.data.dataList[j].name}" class="form-control" placeholder="${that.data.dataList[j].placeholder}" value="${that.data.dataList[j].default_value}">
                       </div>
                   </div>`
        }
        html+='</ul>'
        html+='</div>'
        $('#' + renderParentID).html(html);
        that.addClickEvent();
    }
    addClickEvent(){
        let that=this;
        for(let j=0;j< that.data.dataList.length;j++){
            let ele=document.getElementById(that.getObjID()).querySelector('input[name="'+that.data.dataList[j].name+'"]');
            ele.addEventListener('input',function (){
                if(that.data.dataList[j].name=='form_name'){
                    $(`#${that.data.buildFormTitleID}`).html(ele.value);
                }
            })
        }
        let ele=document.getElementById(`${that.data.buildFormTitleID}`);
        ele.addEventListener('input',function (){
            document.getElementById(that.getObjID()).querySelector('input[name="form_name"]').value= ele.innerHTML
        })
    }
    setValue(newData){
        let that=this;
        for (let key in newData) {
            let inputElement = document.getElementById(that.getObjID()).querySelector('input[name="'+key+'"]');
            if (inputElement) {  // 判断元素是否存在
                inputElement.value = newData[key]; // 如果存在，设置其值
            } else {
                console.log('未找到元素，无法设置值，key:', key); // 打印出未找到的 key
            }
        }
    }
}
export { componentForm }