"use strict";
import { util } from '../../util/util.js';
import { fullMap } from '../../fullMap.js';
import { form } from './form/form.js';
import { query } from './query/query.js'

class page {
    constructor(data) {
        this.objID = util.getUUID() + 'div';
        this.code = '';
        this.pageCode=data.pageCode;
        this.formCode = {};
        this.queryCode = {};
        this.queryCode = data.queryCode;//
        this.queryCode.pageID = this.objID;
        this.formCode = data.formCode;
        this.formCode.pageID = this.objID
        this.pageType=data.pageType
        this.componentName=data.componentName
        this.componentInfo=data.componentInfo
        //这里其实涉及到一个组件通信的问题，query下的table，需要和form通信
        //因为table里涉及新增、编辑、详情都是用form组件的
        //todo 同级组件通信，后续采用PubSubJS方案，但是时间紧张，暂时滞后吧
        //这个是为一个页面有多个组件设计   
        this.componentArray = [];
        this.pageName = data.pageName;
        this.parentObjID = data.parentObjID;
        this.defalutComponent = 'query';
        this.parentFormObjID=data.parentFormObjID;//子表会传此参数，目的是为了让子表也可以控制父表
        this.isReadOnly=data.isReadOnly;
        this.timeoutRender=data.timeoutRender;
        this.parentContent=data.parentContent;
    }
    getComponentArray() {
        return this.componentArray;
    }
    init() {
        let that=this;
        return new Promise((resolve, reject) => {
            that.componentMap = new Map();//存储组件信息
            that.componentArray.push(that.formCode);
            that.componentArray.push(that.queryCode);
            let componentHtmlTemplate=``;
            for (let i = 0; i < that.componentArray.length; i++) {
                componentHtmlTemplate += `<div class="d-none" id="${that.componentArray[i].parentObjID}"></div>`
            }
            if(that.pageType==undefined||that.pageType=='ordinary'){
                let htmlTemplate=`
                <div id="${that.objID}" style="margin-bottom:20px;"
                class="col-${!util.isNull(that.queryCode.code.col)?that.queryCode.code.col:'12'} ">${componentHtmlTemplate}</div>`;
                document.getElementById(that.parentObjID).insertAdjacentHTML("beforeEnd", htmlTemplate);
            }
            if(that.pageType=='pageTabs'){
                let home=fullMap.getObj("home");
                let htmlTemplate=``;
                if(!home.isPageTabs){
                    home.isPageTabs=true;
                    htmlTemplate=`
                    <div id="${that.parentObjID}tabs" style="margin-bottom:20px;"
                    class="col-${!util.isNull(that.queryCode.code.col)?that.queryCode.code.col:'12'} ">
                    <div class="nav-tabs-top mb-4">
                    <ul class="nav nav-tabs" id="${that.parentObjID}_tabs_ul">
                    <li class="nav-item">
                        <a class="nav-link active" data-toggle="tab" href="#${that.objID}">${that.componentName}</a>
                    </li>
                    </ul>
                    <div class="tab-content" id="${that.parentObjID}_tabs_div">
                    <div id="${that.objID}" class="tab-pane fade show active">${componentHtmlTemplate}</div>
                    </div>
                    </div></div>`;
                    document.getElementById(that.parentObjID).insertAdjacentHTML("beforeEnd", htmlTemplate);
                }else{
                    let tabsLiHtmlTemplate=`
                    <li class="nav-item">
                        <a class="nav-link" data-toggle="tab" href="#${that.objID}">${that.componentName}</a>
                    </li>`;
                    document.getElementById(that.parentObjID+'_tabs_ul').insertAdjacentHTML("beforeEnd", tabsLiHtmlTemplate);
                    let tabsDivHtmlTemplate=`
                    <div id="${that.objID}" class="tab-pane fade">${componentHtmlTemplate}</div>`;
                    document.getElementById(that.parentObjID+'_tabs_div').insertAdjacentHTML("beforeEnd", tabsDivHtmlTemplate);
                }
            }
            if(this.pageType=='pageTabsVertical'){
                let home=fullMap.getObj("home");
                let htmlTemplate=``;
                let componentCode=util.getUrlParam('component_code');
                let badgeClass=' d-flex justify-content-between align-items-center ';
                let badgeHtmlTemplate=``;
                if(that.componentInfo['is_show_num']=='Y'){//是否组件num数量展示
                    if(that.componentInfo['show_num_data_type']=='1'){//todo 这里后续有时间调整一下，代码冗余了
                        let cJson=JSON.parse(that.componentInfo['c_json'])
                        let backgroundColor=util.getColorByName(that.componentInfo['show_num_color']);
                        let title='';
                        if(!util.isNull(that.componentInfo['show_num_template'])){
                            title=that.componentInfo['show_num_template'].replace('${data}',cJson.data);
                        }else{
                            title=cJson.data
                        }
                        badgeHtmlTemplate=`<div class="badge badge-primary" style="background-color: ${backgroundColor};" title="${title}">${cJson.data}</div>`;
                    }
                    if(that.componentInfo['show_num_data_type']=='2'){
                        let dataValue=that.componentInfo['sql_value'];
                        if(dataValue!=0){
                            let backgroundColor=util.getColorByName(that.componentInfo['show_num_color']);
                            let title='';
                            if(!util.isNull(that.componentInfo['show_num_template'])){
                                title=that.componentInfo['show_num_template'].replace('${data}',dataValue);
                            }else{
                                title=dataValue
                            }
                            badgeHtmlTemplate=`<div class="badge badge-primary" style="background-color: ${backgroundColor};" title="${title}">${dataValue}</div>`;
                        }

                    }
                }
                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-${!util.isNull(that.queryCode.code.col)?that.queryCode.code.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} ${badgeClass}" id="${that.objID}-list" data-toggle="list" href="#${that.objID}">${that.componentName}${badgeHtmlTemplate}</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}" 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} ${badgeClass}" id="${that.objID}-list" data-toggle="list" href="#${that.objID}">${that.componentName}${badgeHtmlTemplate}</a>`;
                    document.getElementById(that.parentObjID+'_tabs_ul').insertAdjacentHTML("beforeEnd", tabsLiHtmlTemplate);
                    let tabsDivHtmlTemplate=`
                    <div class="tab-pane fade ${actionShowClass}" 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() {
        return new Promise((resolve, reject) => {
            for (let i = 0; i < this.componentArray.length; i++) {
                let componentParentObjID = this.componentArray[i].parentObjID;

                if (this.componentArray[i].type == 'form') {
                    //不再主动渲染编辑表单，缺点，遇到复杂表单第一次渲染较慢
                    /*let formData = { parentObjID: componentParentObjID, code: this.componentArray[i].code, pageID: this.componentArray[i].pageID}
                    let formView = new form(formData);
                    formView.render();
                    this.formComponent = formView;
                    fullMap.push(formView.getObjID(), formView)*/
                } else if (this.componentArray[i].type == 'query') {
                    let queryData = { parentObjID: componentParentObjID, code: this.componentArray[i].code, pageID: this.componentArray[i].pageID,pageType:this.pageType }
                    let queryView = new query(queryData);
                    queryView.render();
                    this.queryComponent = queryView
                    fullMap.push(queryView.getObjID(), queryView)
                }

            }
            resolve();
        })
    }
    showComponent(componentCode) {
        if(componentCode=='query'&&typeof this.queryComponent.scrollIntoRowView ==='function'){
            this.queryComponent.scrollIntoRowView();
            this.queryComponent.scrollIntoRowView=null;//重置
        }

        for (let i = 0; i < this.componentArray.length; i++) {
            if (componentCode == this.componentArray[i].type) {
                document.getElementById(this.componentArray[i].parentObjID).setAttribute('class', '');
            } else {
                if (document.getElementById(this.componentArray[i].parentObjID).getAttribute('class') != 'd-none') {
                    document.getElementById(this.componentArray[i].parentObjID).setAttribute('class', 'd-none');
                }
            }
        }
    }

    setParentContent(content) {
        this.parentContent=content;
    }

    /**
     * 渲染填写意见（是否通过）
     */
    renderOpinion() {
        let eleMap = this.formComponent.getFormMap();
        eleMap.forEach((obj,key)=>{
            if(obj.type=='opinion'){
                obj.page_parent_uuid=eleMap.get('uuid').getValue();
                obj.opinion_show='Y';//默认只有查看意见，没有填写意见权限（opinion_add）
                obj.refreshOpinion();
            }
        })
    }
}
export { page };