"use strict";

import { util } from '../../../../util/util.js'
import {fullMap} from "../../../../fullMap.js";
import {config} from "../../../../config.js";
import {khcModal} from "../../../alert/khcModal.js";
import {form} from "../../form/form.js";
import {pageInfoMap} from "../../../../pageInfoMap.js";
import {khcAlert} from "../../../alert/khcAlert.js";
class tableButtons {
    constructor(data) {

        this.data = data;
        this.parentObjID = data.parentObjID;
        this.eleID = util.getUUID();
        this.objID = this.eleID + 'div';
        this.tableID = '';
    }
    getObjID() {
        return this.objID;
    }
    render(tableId) {
        let that=this;
        return new Promise((resolve, reject) => {
            that.tableID = tableId;
            that.renderHtml().then(() => {
                that.addEventListener();
                if(that.tableView.queryInfo.is_show_select_table=='Y'){
                    that.renderSelectHtml().then(() => {
                        that.addSelectEventListener();
                    })
                }
                resolve();
            })
        })
    }
    renderHtml() {
        let that=this;
        return new Promise((resolve, reject) => {
            let tableId = that.tableID
            let tableButtonHtml = '';
            let tableButtonArray = that.data.tableButtonArray;
            that.isSelectShow=false;
            let tableView=fullMap.getObj(that.data.queryComponentObjID).tableView
            that.tableView=tableView;
            for (let tableButton of tableButtonArray) {
                if(tableButton.button_show_query_type!=undefined&&tableButton.button_show_query_type=='2'){
                    continue;
                }
                if(!util.isNull(tableButton.row_button_show_func)){
                    let myselfFuncStr=util.toOldChar(tableButton.row_button_show_func);
                    tableView.queryInfo.util=util;
                    if(pageInfoMap.getObj(that.tableView.code['queryCode'])==undefined||
                        pageInfoMap.getObj(that.tableView.code['queryCode']).page_parent_uuid==undefined){
                    }else{
                        let pageObj=fullMap.getObj(fullMap.getObj(that.tableView.queryObjID).pageID)
                        if(pageObj['parentFormObjID']!=undefined){
                            let formObj=fullMap.getObj(pageObj['parentFormObjID']);
                            tableView.queryInfo.parentContent=formObj.getFormValue()
                        }else{
                            tableView.queryInfo.parentContent=pageObj['parentContent'];
                        }
                    }
                    if (!util.executeDynamicCode(myselfFuncStr,tableView.queryInfo)){//自定义校验不通过，不渲染按钮
                        continue;
                    }
                }
                if(tableButton.is_select_show=='Y'){
                    that.isSelectShow=true;
                }else {
                    let buttonCss='';
                    let colorClassName=config.getConfigJson().defaultColorClassJson[tableButton.button_class];
                    if(colorClassName){
                        colorClassName=colorClassName['bfColor']
                    }else{
                        let backgroundColor=util.getColorByName(tableButton.button_class);
                        let color=util.dynamicColor(backgroundColor);
                        buttonCss+=`background:${backgroundColor};color:${color}`;
                    }
                    tableButtonHtml += `<label class="mr-2">
                        <button type="button" name="${tableButton.button_name}" class="btn btn- ladda-button ${colorClassName}" id="${tableId+tableButton.uuid}"
                        data-style="slide-down" style="${buttonCss}" 
                        title="${tableButton.button_title.includes('#')>0?`${tableButton.button_title.replace(/#/g, "")}`:`${tableButton.button_title}`}">
                        <span class="${tableButton.button_icon}"></span>
                        ${tableButton.button_title.includes('#')>0?``:`${tableButton.button_title}`}</button>
                        </label>`
                }
            }
            let buttonHtmlTemplate=``;
            for (let i = 0; i < tableButtonArray.length; i++) {//渲染在更多操作的按钮
                let button = tableButtonArray[i];
                let buttonCss='';
                if(button.button_show_query_type!=undefined&&button.button_show_query_type=='2'){
                    buttonCss='display: none;'
                }
                buttonHtmlTemplate+=`${button.is_select_show=='Y'?`<a class="dropdown-item" name="${button.button_name}" style="${buttonCss} cursor:pointer;">${button.button_title}</a>`:''}`;
            }
            if(that.isSelectShow&&buttonHtmlTemplate!=''){
                tableButtonHtml+=`<label class="mr-2" style="z-index: 1001;">
                    <button class="btn btn-secondary dropdown-toggle" type="button" 
                            id="${that.objID}_dropdown_button" data-toggle="dropdown" aria-expanded="false">
                    ${that.tableView.queryInfo['table_select_button_label']?that.tableView.queryInfo['table_select_button_label']:config.getConfigJson().tableSelectButtonLabel}</button>
                    <div class="dropdown-menu" style="">${buttonHtmlTemplate}</div></label>`;
            }
            let isEditComponent=util.getSessionStorageItem('isEditComponent');
            if(isEditComponent=='S'||isEditComponent=='P'){
                let html=that.getQueryHtml();
                tableButtonHtml+=html;
            }
            document.getElementById(tableId + 'tableAreaButton').innerHTML = '';
            document.getElementById(tableId + 'tableAreaButton').insertAdjacentHTML("beforeEnd", tableButtonHtml);

            let showTableDivEle=document.getElementById(tableId+'_show_table_div')
            let minHeight=that.tableView.queryInfo['table_min_height'];
            if(util.isNull(minHeight)){
                minHeight=400;
            }
            let screenWidth=Math.max(window.screen.width,window.innerWidth);
            showTableDivEle.style.maxHeight=screenWidth>1920?'80vh':'75vh';
            showTableDivEle.style.minHeight=minHeight+'px';
            resolve();
        })




    }
    addEventListener() {
        let that = this;
        let tableObjID = that.tableID;
        //表格按钮
        let tableButtonArray = that.data.tableButtonArray;
        let tableView=fullMap.getObj(that.data.queryComponentObjID).tableView
        that.tableView=tableView;
        for (let i = 0; i < tableButtonArray.length; i++) {
            let tableButton = tableButtonArray[i];
            if(tableButton.button_show_query_type!=undefined&&tableButton.button_show_query_type=='2'){
                continue;
            }
            if(!util.isNull(tableButton.row_button_show_func)){
                let myselfFuncStr=util.toOldChar(tableButton.row_button_show_func);
                if(pageInfoMap.getObj(that.tableView.code['queryCode'])==undefined||
                    pageInfoMap.getObj(that.tableView.code['queryCode']).page_parent_uuid==undefined){
                }else{
                    let pageObj=fullMap.getObj(fullMap.getObj(that.tableView.queryObjID).pageID)
                    if(pageObj['parentFormObjID']!=undefined){
                        let formObj=fullMap.getObj(pageObj['parentFormObjID']);
                        tableView.queryInfo.parentContent=formObj.getFormValue()
                    }else{
                        tableView.queryInfo.parentContent=pageObj['parentContent'];
                    }
                }
                tableView.queryInfo.util=util;
                if (!util.executeDynamicCode(myselfFuncStr,tableView.queryInfo)){//自定义校验不通过，不渲染按钮
                    continue;
                }
            }
            if (!util.isNull(tableButton.button_method)) {
                let buttonEle = document.getElementById(tableObjID + 'tableAreaButton').querySelector('button[name="' + tableButton.button_name + '"]');
                if(buttonEle==null){
                    buttonEle=document.getElementById(tableObjID + 'tableAreaButton').querySelector('a[name="' + tableButton.button_name + '"]');
                }else{
                    Ladda.bind( buttonEle, { timeout: 1000 } );//按钮loading动画效果
                }
                buttonEle.addEventListener(tableButton.button_event,  ()=> {
                    let jsonConfig={objID:that.data.queryComponentObjID,button_method:tableButton.button_method}
                    let buttonParams={buttonUuid:tableButton.uuid}
                    jsonConfig.buttonParams=buttonParams;
                    if(!util.isNull(tableButton.js_path)){//配置扩展js优先执行(优先级1)
                        util.import2023(tableButton.js_path,jsonConfig);
                    }else if (!util.isNull(tableButton['button_click_json_config'])) {//配置 button_click_json_config 则执行(优先级2)
                        jsonConfig['button_method']='tableButtonClickFunc'
                        jsonConfig['old_button_method']=tableButton.button_method
                        jsonConfig['button_click_json_config']=JSON.parse(tableButton['button_click_json_config'])
                        util.import2023(config.getConfigJson().tableActionPath,jsonConfig);
                    }else{//没有配置扩展js，也没配置自定义js(优先级3)
                        util.import2023(config.getConfigJson().tableActionPath,jsonConfig);
                    }
                })
                if(tableButton.is_render_trigger=='Y'){
                    let jsonConfig={objID:that.data.queryComponentObjID,button_method:tableButton.button_method}
                    let buttonParams={buttonUuid:tableButton.uuid}
                    buttonParams.renderTrigger=true;
                    jsonConfig.buttonParams=buttonParams;
                    if(!util.isNull(tableButton.js_path)){//配置扩展js优先执行(优先级1)
                        util.import2023(tableButton.js_path,jsonConfig);
                    }else if (!util.isNull(tableButton['button_click_json_config'])) {//配置 button_click_json_config 则执行(优先级2)
                        jsonConfig['button_method']='tableButtonClickFunc'
                        jsonConfig['old_button_method']=tableButton.button_method
                        jsonConfig['button_click_json_config']=JSON.parse(tableButton['button_click_json_config'])
                        util.import2023(config.getConfigJson().tableActionPath,jsonConfig);
                    }else{//没有配置扩展js，也没配置自定义js(优先级3)
                        util.import2023(config.getConfigJson().tableActionPath,jsonConfig);
                    }
                }
            }
        }
        let isEditComponent=util.getSessionStorageItem('isEditComponent');
        if(isEditComponent=='S'||isEditComponent=='P'){
            that.queryAddEventListener();
        }
    }
    //获取查询组件管理配置Html
    getQueryHtml(){
        let that=this;
        let html=``
        let table=fullMap.getObj(that.data.queryComponentObjID).tableView
        let queryInfo=fullMap.getObj(that.data.queryComponentObjID).queryInfo;
        if(queryInfo['query_code']=='query_info'){
            return '';
        }
        let objID=table.getObjID();
        html+=`<div class="mr-2 mb-2" style="z-index: 1001;">
                 <div class="project-task-actions btn-group" title="${queryInfo.query_name}">
                   <button type="button" class="btn md-btn-flat dropdown-toggle" data-toggle="dropdown">
                     查询组件维护
                   </button>
                   <div class="dropdown-menu dropdown-menu-right">
                     <a class="dropdown-item" href="javascript:void(0)" id="${objID}_query_edit${queryInfo.id}">编辑</a>
                     <a class="dropdown-item" href="javascript:void(0)" id="${objID}_query_to_field${queryInfo.id}">字段维护</a>
                     <a class="dropdown-item" href="javascript:void(0)" id="${objID}_query_to_button${queryInfo.id}">按钮维护</a>
                     <a class="dropdown-item" href="javascript:void(0)" id="${objID}_query_to_simple_card${queryInfo.id}">SimpleCard维护</a>
                     <a class="dropdown-item" href="javascript:void(0)" id="${objID}_query_role${queryInfo.id}">查看数据全部角色</a>
                   </div>
                 </div>
               </div>`;
        return html;
    }
    //给query的配置绑定事件 todo 这块代码以后迁移出单独文件
    queryAddEventListener(){
        let that=this;
        let table=fullMap.getObj(that.data.queryComponentObjID).tableView
        let content=fullMap.getObj(that.data.queryComponentObjID).queryInfo;
        if(content['query_code']=='query_info'){
            return '';
        }
        document.getElementById(table.getObjID()+'_query_edit'+content.id).addEventListener('click',  ()=>{
            let params = {};
            params.dsCode='ds_query';
            params.formCode='form_query';
            params.queryCode='query';
            let khcModalForForm = new khcModal({ modalAreaID: config.getConfigJson().modalAreaID });
            khcModalForForm.render().then(() => {
                let formComponent = new form({ parentObjID: khcModalForForm.getEleID(), code: params });
                khcModalForForm.formObjID=formComponent.getObjID()
                let khcModalForFormKey='khcModalForForm#'+formComponent.getObjID();
                pageInfoMap.push(khcModalForFormKey,khcModalForForm);
                formComponent.setFormShowType('modals')
                formComponent.render().then(() => {
                    formComponent.renderThenFunc=(content)=>{
                        formComponent.renderValue(content).then(()=>{
                            let eleMap = formComponent.getFormMap();
                            let read=pageInfoMap.getObj('readOnly#'+params.formCode)
                            if(read!=undefined){
                                for (let i = 0; i < read.length; i++) {
                                    eleMap.get(read[i]).setDisabled();
                                }
                            }
                            let canNull=pageInfoMap.getObj('canNull#'+params.formCode)
                            formComponent.setSaveAfter( ()=> {
                                khcModalForForm.hide();
                                setTimeout(function (){
                                    let alertData = {};
                                    alertData.title = '是否重新加载';
                                    alertData.text = '变更配置需要重新加载页面生效';
                                    alertData.preConfirm = () => {
                                        window.location.reload()
                                    }
                                    khcAlert.showConfirm(alertData, () => {})
                                },1500)
                            })
                            if(canNull!=undefined){
                                for (let i = 0; i < canNull.length; i++) {
                                    eleMap.get(canNull[i]).data.can_null='Y';
                                    eleMap.get(canNull[i]).refreshCanNull();
                                }
                            }
                            formComponent.formEdit();//一些高级属性在新增时大部分是不需要设置所以隐藏，在编辑时再展示
                            khcModalForForm.show();
                        })
                    };
                    formComponent.renderThenFunc(content);
                });

            })
        })
        document.getElementById(table.getObjID()+'_query_to_field'+content.id).addEventListener('click',  ()=>{
            let queryInfo={"page_parent_uuid":content.uuid};
            let pageCode='page_ds_query_info';
            let url=config.getIndexUrl()+'?pageCode='+pageCode+'&queryInfo='+encodeURIComponent(JSON.stringify(queryInfo))
            window.open(url);
        })
        document.getElementById(table.getObjID()+'_query_to_button'+content.id).addEventListener('click',  ()=>{
            let queryInfo={"page_parent_uuid":content.uuid};
            let pageCode='page_ds_button';
            let url=config.getIndexUrl()+'?pageCode='+pageCode+'&queryInfo='+encodeURIComponent(JSON.stringify(queryInfo))
            window.open(url);
        })
        document.getElementById(table.getObjID()+'_query_to_simple_card'+content.id).addEventListener('click',  ()=>{
            let queryInfo={"page_parent_uuid":content.uuid};
            let pageCode='page_query_simple_card';
            let url=config.getIndexUrl()+'?pageCode='+pageCode+'&queryInfo='+encodeURIComponent(JSON.stringify(queryInfo))
            window.open(url);
        })
        document.getElementById(table.getObjID()+'_query_role'+content.id).addEventListener('click',  ()=>{
            let params = {};
            params.dsCode='ds_query';
            params.formCode='form_query_role';
            params.queryCode='query';
            let khcModalForForm = new khcModal({ modalAreaID: config.getConfigJson().modalAreaID });
            khcModalForForm.render().then(() => {
                let formComponent = new form({ parentObjID: khcModalForForm.getEleID(), code: params });
                khcModalForForm.formObjID=formComponent.getObjID()
                let khcModalForFormKey='khcModalForForm#'+formComponent.getObjID();
                pageInfoMap.push(khcModalForFormKey,khcModalForForm);
                formComponent.setFormShowType('modals')
                formComponent.render().then(() => {
                    formComponent.renderThenFunc=(content)=>{
                        formComponent.renderValue(content).then(()=>{
                            let eleMap = formComponent.getFormMap();
                            let read=pageInfoMap.getObj('readOnly#'+params.formCode)
                            if(read!=undefined){
                                for (let i = 0; i < read.length; i++) {
                                    eleMap.get(read[i]).setDisabled();
                                }
                            }
                            let canNull=pageInfoMap.getObj('canNull#'+params.formCode)
                            formComponent.setSaveAfter( ()=> {
                                khcModalForForm.hide();
                                setTimeout(function (){
                                    let alertData = {};
                                    alertData.title = '是否重新加载';
                                    alertData.text = '变更配置需要重新加载页面生效';
                                    alertData.preConfirm = () => {
                                        window.location.reload()
                                    }
                                    khcAlert.showConfirm(alertData, () => {})
                                },1500)
                            })
                            if(canNull!=undefined){
                                for (let i = 0; i < canNull.length; i++) {
                                    eleMap.get(canNull[i]).data.can_null='Y';
                                    eleMap.get(canNull[i]).refreshCanNull();
                                }
                            }
                            formComponent.formEdit();//一些高级属性在新增时大部分是不需要设置所以隐藏，在编辑时再展示
                            khcModalForForm.show();
                        })
                    };
                    formComponent.renderThenFunc(content);
                });
            })
        })
    }
}
export { tableButtons }



