"use strict";
import { util } from '../../util/util.js';
import { fullMap } from '../../fullMap.js';
import { form } from '../page/form/form.js';
import {config} from "../../config.js";
import {httpUtil} from "../../util/httpUtil.js";

class pageForm {
    constructor(data) {
        this.objID = util.getUUID() + 'div';
        this.code = '';
        this.pageCode=data.pageCode;
        this.formCode = {};
        this.formCode = data.formCode;
        this.formCode.pageID = this.objID
        this.pageType=data.pageType
        this.componentName=data.componentName
        this.componentInfo=data.componentInfo
        //todo 同级组件通信，后续采用PubSubJS方案，但是时间紧张，暂时滞后吧
        this.pageName = data.pageName;
        this.parentObjID = data.parentObjID;
        this.defalutComponent = 'form';
        this.parentFormObjID=data.parentFormObjID;//子表会传此参数，目的是为了让子表也可以控制父表
        this.isReadOnly=data.isReadOnly;
        this.timeoutRender=data.timeoutRender;
    }
    init() {
        let that=this;
        return new Promise((resolve, reject) => {
            that.componentMap = new Map();//存储组件信息
            let col=that.formCode.code.col;
            let componentHtmlTemplate= `<div class="d-none" id="${that.formCode.parentObjID}"></div>`
            if(that.pageType==undefined||that.pageType=='ordinary'){
                let componentHtmlTemplate= `<div class="d-none" id="${that.formCode.parentObjID}"></div>`
                let htmlTemplate=`
                <div id="${that.objID}" style="margin-bottom:20px;"
                class="col-${!util.isNull(col)?col*2:'12'} col-xl-${!util.isNull(col)?col:'12'}">${componentHtmlTemplate}</div>`;
                document.getElementById(that.parentObjID).insertAdjacentHTML("beforeEnd", htmlTemplate);
            }
            if(that.pageType=='pageTabsVertical'){
                let home=fullMap.getObj("home");
                let htmlTemplate=``;
                let componentCode=util.getUrlParam('component_code');
                if(!home.isPageTabs){
                    let actionShowClass='';
                    if(util.isNull(componentCode)||componentCode==that.componentInfo['component_code'])actionShowClass=' active show';
                    home.isPageTabs=true;
                    htmlTemplate=`
                    <div id="${that.parentObjID}tabs" style="margin-bottom:20px;" class="col-12">
                    <div class="row">
                        <div class="col-3 col-xl-2">
                            <div class="list-group" id="${that.parentObjID}_tabs_ul">
                                <a class="list-group-item list-group-item-action ${actionShowClass}" id="${that.objID}-list" data-toggle="list" href="#${that.objID}">${that.componentName}</a>
                            </div>
                        </div>
                        <div class="col-9 col-xl-10">
                            <div class="tab-content" id="${that.parentObjID}_tabs_div">
                                <div class="tab-pane fade ${actionShowClass} col-${!util.isNull(that.formCode.code.col)?that.formCode.code.col:'12'} " id="${that.objID}">${componentHtmlTemplate}</div>
                            </div>
                        </div>
                    </div>
                    </div>`;
                    document.getElementById(that.parentObjID).insertAdjacentHTML("beforeEnd", htmlTemplate);
                }else{
                    let actionShowClass='';
                    if(!util.isNull(componentCode)&&componentCode==that.componentInfo['component_code'])actionShowClass=' active show';
                    let tabsLiHtmlTemplate=`
                    <a class="list-group-item list-group-item-action ${actionShowClass}" id="${that.objID}-list" data-toggle="list" href="#${that.objID}">${that.componentName}</a>`;
                    document.getElementById(that.parentObjID+'_tabs_ul').insertAdjacentHTML("beforeEnd", tabsLiHtmlTemplate);
                    let tabsDivHtmlTemplate=`
                    <div class="tab-pane fade ${actionShowClass} col-${!util.isNull(that.formCode.code.col)?that.formCode.code.col:'12'} " id="${that.objID}">${componentHtmlTemplate}</div>`;
                    document.getElementById(that.parentObjID+'_tabs_div').insertAdjacentHTML("beforeEnd", tabsDivHtmlTemplate);
                }
            }
            resolve();
        })
    }

    render() {
        let that=this;
        return new Promise((resolve, reject) => {
            that.init().then(() => {
                setTimeout(function (){
                    that.renderComponent().then(() => {
                        that.showComponent(that.defalutComponent)
                        resolve();
                    });
                },that.timeoutRender);
            })
        })

    }
    renderComponent() {
        let that=this;
        return new Promise((resolve, reject) => {
            let componentInfo=that.formCode;
            let componentParentObjID = componentInfo.parentObjID;
            if (componentInfo.type == 'form') {
                let formData = { parentObjID: componentParentObjID, code: componentInfo.code, pageID: componentInfo.pageID}
                let formComponent = new form(formData);
                if(componentInfo.code.formViewMode=='create'){
                    formComponent.render().then(()=> {
                        formComponent.formCreate();
                    });
                }
                if(componentInfo.code.formViewMode=='edit'){
                    that.renderThenFunc=()=>{
                        let params=util.clone(componentInfo.code);
                        params.methodName=componentInfo.code.formFindOneMethodName;
                        let obj={url:config.getConfigJson().myActionUrl,params:params}
                        httpUtil.post(obj,(response)=>{
                            let eleMap = formComponent.getFormMap();
                            let content=response.data.data.data;
                            for (let key in content) {
                                eleMap.get(key).setValue(content[key])
                            }
                        })
                        formComponent.formEdit();
                    }
                    formComponent.render().then(()=>{
                        that.renderThenFunc()
                    });
                    //同理可以实现saveBefore
                    formComponent.setSaveAfter( ()=> {
                        let pageFormMap=fullMap.getObj('home').pageFormMap;
                        for (let key of pageFormMap.keys()) {
                            let pageFormObj = pageFormMap.get(key)
                            pageFormObj.refreshPageFormValue();
                        }
                    })
                }
                if(componentInfo.code.formViewMode=='detail'||componentInfo.code.formViewMode=='text_detail'){
                    formComponent.closeButton();
                    if(componentInfo.code.formViewMode=='text_detail'){
                        formComponent.kind='text_detail'
                    }
                    that.renderThenFunc=()=>{
                        let params=util.clone(componentInfo.code);
                        params.methodName=componentInfo.code.formFindOneMethodName;
                        let obj={url:config.getConfigJson().myActionUrl,params:params}
                        httpUtil.post(obj,(response)=>{
                            let eleMap = formComponent.getFormMap();
                            let content=response.data.data.data;
                            eleMap.forEach( (obj,key)=>{//在赋值之前，先全部置空，因为Mongo建表和MySQL不一样
                                obj.data.is_read_only='Y';//强制修改为只读
                                obj.setDisabled();
                                obj.setValue('');
                            })
                            for (let key in content) {
                                if(util.isNull(eleMap.get(key))){
                                    if(config.getConfigJson().logLevel=='debug') console.log('（警告）字段名：'+key+' 未在表单组件同步配置，如buildSql查询出来的可忽略')
                                    continue
                                }
                                eleMap.get(key).data.is_read_only='Y';//强制修改为只读
                                eleMap.get(key).setValue(content[key])
                                eleMap.get(key).setDisabled();
                            }
                        })
                        formComponent.formDetail();
                    }
                    formComponent.render().then(()=>{
                        that.renderThenFunc()
                    });
                }
                this.formComponent = formComponent;
                fullMap.push(formComponent.getObjID(), formComponent)
            }
            resolve();
        })
    }
    refreshPageFormValue(){
        let that=this;
        if(that.renderThenFunc!=undefined){
            that.renderThenFunc();
        }
    }
    showComponent(componentCode) {
        let that=this;
        let componentInfo=that.formCode;
        if (componentCode == componentInfo.type) {
            document.getElementById(componentInfo.parentObjID).setAttribute('class', '');
        } else {
            if (document.getElementById(componentInfo.parentObjID).getAttribute('class') != 'd-none') {
                document.getElementById(componentInfo.parentObjID).setAttribute('class', 'd-none');
            }
        }
    }
}
export { pageForm };