"use strict";/*通用按钮方法*/
import { fullMap } from '../../fullMap.js';
import { khcAlert } from '../../component/alert/khcAlert.js'
import { form } from '../../component/page/form/form.js';
import { util } from '../../util/util.js'
import { khcModal } from '../../component/alert/khcModal.js'
import {pageInfoMap} from "../../pageInfoMap.js";
import {config} from "../../config.js";
import {khcToastr} from "../../component/alert/khcToastr.js";
import {bpm} from "../../component/bpm/bpm.js";
import {httpUtil} from "../../util/httpUtil.js";
import {khcModalSlide} from "../../component/alert/khcModalSlide.js";
let functionMap=new Map();// 使用 Map 来存储多个函数。每个函数都通过 set 方法添加到 Map 中，键是函数名，值是对应的函数。
export function main(jsonConfig) {
    try {
        functionMap.get(jsonConfig.button_method).apply(jsonConfig);
    } catch (error) {
        khcAlert.showSystemError(error.message);
        console.log(error);
    }
    
}
let khcModalForForm=null;
//通用的copy
function copy(){
    let jsonConfig=this;
    let queryViewComponent = fullMap.getObj(jsonConfig.objID);
    let tableViewComponent = queryViewComponent.getTableObj();
    let content = tableViewComponent.getContentMap().get(jsonConfig.pkCode.toString());
    let params = {};
    let componentArray = fullMap.getObj(queryViewComponent.pageID).componentArray;
    for (let i = 0; i < componentArray.length; i++) {
        if (componentArray[i].type == 'form') {
            params = componentArray[i].code;
        }
    }
    khcModalForForm = new khcModal({ modalAreaID: config.getConfigJson().modalAreaID });
    khcModalForForm.render().then(() => {
        let formComponent = new form({ parentObjID: khcModalForForm.getEleID(), code: params ,pageID:queryViewComponent.pageID});
        formComponent.khcModalForForm=khcModalForForm;
        khcModalForForm.formObjID=formComponent.getObjID()
        let khcModalForFormKey='khcModalForForm#'+formComponent.getObjID();
        pageInfoMap.push(khcModalForFormKey,khcModalForForm);
        formComponent.setFormShowType('modals')
        formComponent.render().then(() => {
            let eleMap = formComponent.getFormMap();
            for (let key in content) {
                if(util.isNull(eleMap.get(key))){
                    if(config.getConfigJson().logLevel=='debug') console.log('（警告）字段名：'+key+' 未在表单组件同步配置')
                    continue
                };
                eleMap.get(key).setValue(content[key])
            }
            let fieldList=['id','org_id','uuid','create_time','create_user'];
            //同理可以实现saveBefore
            formComponent.setSaveAfter( ()=> {
                khcModalForForm.hide();
                tableViewComponent.refresh();
            })
            for (let i = 0; i <fieldList.length; i++) {
                if(eleMap.get(fieldList[i])!=undefined){
                    eleMap.get(fieldList[i]).setValue('');
                }
            }
            document.getElementById(formComponent.getObjID()+'title').innerText='（复制）'+formComponent.formStructureData.formInfo.form_name
            formComponent.formEdit();
            khcModalForForm.show();
        });
    })

}
functionMap.set('copy', copy);// 将函数添加到 Map 中
/**
 * 子表新增，隐藏列表，展示新增表单，需要set父uuid用于关联数据（如果有三级子表，则在二级子表使用此方法，如果只有二级子表则在一级表使用：createOneByChild）
 * @param objID
 */
function createOneByChildPage(){
    let jsonConfig=this;
    let queryViewComponent = fullMap.getObj(jsonConfig.objID);
    let pageID = queryViewComponent.pageID;
    //如何获取form的code
    let params = {};
    let componentArray = fullMap.getObj(pageID).componentArray;
    for (let i = 0; i < componentArray.length; i++) {
        if (componentArray[i].type == 'form') {
            params = componentArray[i].code;
        }
    }
    let formPage = fullMap.getObj(pageID);
    formPage.formComponent.initForm();
    let formComponent=formPage.formComponent;
    let eleMap = formComponent.getFormMap();
    if(pageInfoMap.getObj(formComponent.code.queryCode)==undefined||
        pageInfoMap.getObj(formComponent.code.queryCode).page_parent_uuid==undefined){
    }else{
        eleMap.get('page_parent_uuid').setValue(pageInfoMap.getObj(formComponent.code.queryCode).page_parent_uuid)
    }
    formPage.formComponent.setSaveAfter( ()=> {
        formPage.formComponent.clearValue();
        formPage.showComponent('query');
        formPage.queryComponent.getTableObj().refresh();
    })
    formPage.formComponent.formCreate();
    formPage.showComponent('form');
}
functionMap.set('createOneByChildPage', createOneByChildPage);// 将函数添加到 Map 中
/**
 * 子表刷新列表
 * @param objID
 */
function refreshList(){
    let jsonConfig=this;
    let queryViewComponent = fullMap.getObj(jsonConfig.objID);
    //queryViewComponent.getTableObj().refresh();//本想在这加一个刷新列表的，测试时发现没有parent_uuid暂时改为刷新页面
    window.location.reload();

}
functionMap.set('refreshList', refreshList);// 将函数添加到 Map 中
/**
 * 数据导入（目前支持xls，xlsx）
 * @param objID
 */
function showUploadExcelTemplateByChild(){
    let jsonConfig=this;
    let queryViewComponent = fullMap.getObj(jsonConfig.objID);
    let upLoadParam = {};
    let params = {};
    let componentArray = fullMap.getObj(queryViewComponent.pageID).componentArray;
    for (let i = 0; i < componentArray.length; i++) {
        if (componentArray[i].type == 'form') {
            upLoadParam = componentArray[i].code;
        }
    }
    params.dsCode='ds_template';
    params.formCode='form_template_upload_file';
    khcModalForForm = new khcModal({ modalAreaID: config.getConfigJson().modalAreaID });
    khcModalForForm.render().then(() => {
        let formComponent = new form({ parentObjID: khcModalForForm.getEleID(), code: params ,pageID:queryViewComponent.pageID});
        formComponent.khcModalForForm=khcModalForForm;
        khcModalForForm.formObjID=formComponent.getObjID()
        let khcModalForFormKey='khcModalForForm#'+formComponent.getObjID();
        pageInfoMap.push(khcModalForFormKey,khcModalForForm);
        formComponent.setFormShowType('modals')
        //同理可以实现saveBefore
        formComponent.setSaveAfter( ()=> {
            queryViewComponent.getTableObj().refresh();
            khcModalForForm.hide();
        })
        formComponent.render().then(() => {
            let eleMap = formComponent.getFormMap();
            if(pageInfoMap.getObj(formComponent.code.queryCode)==undefined||
                pageInfoMap.getObj(formComponent.code.queryCode).page_parent_uuid==undefined){
            }else{
                eleMap.get('page_parent_uuid').setValue(pageInfoMap.getObj(formComponent.code.queryCode).page_parent_uuid)
            }
            //渲染完成后将模板的code替换为要导入的code
            formComponent.code.dsCode=upLoadParam.dsCode;
            formComponent.code.formCode=upLoadParam.formCode;
            formComponent.code.queryCode=upLoadParam.queryCode;
            formComponent.formCreate();
            khcModalForForm.show();
        });
    })
}
functionMap.set('showUploadExcelTemplateByChild', showUploadExcelTemplateByChild);// 将函数添加到 Map 中
/**
 * 数据导入（JSON）
 * @param objID
 */
function showTemplateJsonImport(){
    let jsonConfig=this;
    let queryViewComponent = fullMap.getObj(jsonConfig.objID);
    let upLoadParam = {};
    let params = {};
    let componentArray = fullMap.getObj(queryViewComponent.pageID).componentArray;
    for (let i = 0; i < componentArray.length; i++) {
        if (componentArray[i].type == 'form') {
            upLoadParam = componentArray[i].code;
        }
    }
    params.dsCode='ds_template';
    params.formCode='form_template_json_import';
    khcModalForForm = new khcModal({ modalAreaID: config.getConfigJson().modalAreaID });
    khcModalForForm.render().then(() => {
        let formComponent = new form({ parentObjID: khcModalForForm.getEleID(), code: params ,pageID:queryViewComponent.pageID});
        formComponent.khcModalForForm=khcModalForForm;
        khcModalForForm.formObjID=formComponent.getObjID()
        let khcModalForFormKey='khcModalForForm#'+formComponent.getObjID();
        pageInfoMap.push(khcModalForFormKey,khcModalForForm);
        formComponent.setFormShowType('modals')
        //同理可以实现saveBefore
        formComponent.setSaveAfter( ()=> {
            queryViewComponent.getTableObj().refresh();
            khcModalForForm.hide();
        })
        formComponent.render().then(() => {
            let eleMap = formComponent.getFormMap();
            if(pageInfoMap.getObj(formComponent.code.queryCode)==undefined||
                pageInfoMap.getObj(formComponent.code.queryCode).page_parent_uuid==undefined){
            }else{
                eleMap.get('page_parent_uuid').setValue(pageInfoMap.getObj(formComponent.code.queryCode).page_parent_uuid)
            }
            //渲染完成后将模板的code替换为要导入的code
            formComponent.code.dsCode=upLoadParam.dsCode;
            formComponent.code.formCode=upLoadParam.formCode;
            formComponent.code.queryCode=upLoadParam.queryCode;
            formComponent.formCreate();
            khcModalForForm.show();
        });
    })
}
functionMap.set('showTemplateJsonImport', showTemplateJsonImport);// 将函数添加到 Map 中

/**
 * 数据更新（JSON）
 */
function showTemplateJsonUpdate() {
    let jsonConfig=this;
    let queryViewComponent = fullMap.getObj(jsonConfig.objID);
    let tableViewComponent = queryViewComponent.getTableObj();
    let content = tableViewComponent.getContentMap().get(jsonConfig.pkCode.toString());
    let jsonUpdateParam = {};
    let params = {};
    let componentArray = fullMap.getObj(queryViewComponent.pageID).componentArray;
    for (let i = 0; i < componentArray.length; i++) {
        if (componentArray[i].type == 'form') {
            jsonUpdateParam = componentArray[i].code;
        }
    }
    params.dsCode='ds_template';
    params.formCode='form_template_json_update';
    khcModalForForm = new khcModal({ modalAreaID: config.getConfigJson().modalAreaID });
    khcModalForForm.render().then(() => {
        let formComponent = new form({ parentObjID: khcModalForForm.getEleID(), code: params ,pageID:queryViewComponent.pageID});
        formComponent.khcModalForForm=khcModalForForm;
        khcModalForForm.formObjID=formComponent.getObjID()
        let khcModalForFormKey='khcModalForForm#'+formComponent.getObjID();
        pageInfoMap.push(khcModalForFormKey,khcModalForForm);
        formComponent.setFormShowType('modals')
        //同理可以实现saveBefore
        formComponent.setSaveAfter( ()=> {
            queryViewComponent.getTableObj().refresh();
            khcModalForForm.hide();
        })
        formComponent.render().then(() => {
            let eleMap = formComponent.getFormMap();
            if(pageInfoMap.getObj(formComponent.code.queryCode)==undefined||
                pageInfoMap.getObj(formComponent.code.queryCode).page_parent_uuid==undefined){
            }else{
                eleMap.get('page_parent_uuid').setValue(pageInfoMap.getObj(formComponent.code.queryCode).page_parent_uuid)
            }
            //渲染完成后将模板的code替换为要导入的code
            formComponent.code.dsCode=jsonUpdateParam.dsCode;
            formComponent.code.formCode=jsonUpdateParam.formCode;
            formComponent.code.queryCode=jsonUpdateParam.queryCode;
            formComponent.code.content=content;
            formComponent.formCreate();
            khcModalForForm.show();
        });
    })
}
functionMap.set('showTemplateJsonUpdate', showTemplateJsonUpdate);// 将函数添加到 Map 中
/**
 * 数据导入-提交按钮
 * todo 这个按钮事件应该放到自己的扩展js，不应该放这个文件
 * @param objID
 */
function uploadExcelTemplateByChild(){
    let jsonConfig=this;
    let queryViewComponent = fullMap.getObj(jsonConfig.objID);
    let params = queryViewComponent.code;
    let eleMap = queryViewComponent.getFormMap();
    params.fileArray=eleMap.get('upload_file').getValue();
    params.readRow=eleMap.get('read_row').getValue();
    if(!params.fileArray.length>0){
        khcToastr.showErrorMessage('请选择导入文件')
        return ;
    }
    fullMap.getObj('mask').show('正在解析文件...')
    let pageParamsObj=pageInfoMap.getObj(queryViewComponent.code.queryCode);//页面传参对象（仅在子表会产生）
    fullMap.getObj('ws').khcWSFuncMap.set(queryViewComponent.code.queryCode,function (data){
        if(data.status=="ok"){
            if(data.isHideMask=="Y"){
                Swal.fire('导入成功', data.message,'success' )
                fullMap.getObj('mask').hide();
                queryViewComponent.runSaveAfter()
            }else{
                fullMap.getObj('mask').showNewText(data.message)
            }
        }else{
            let alertData={title:data.message,text:'标识码：' + data.status}
            khcAlert.showSystemError(alertData);
            //eleMap.get('upload_file').setValue([]);
            fullMap.getObj('mask').hide();
        }

    })
    if(pageParamsObj!=null){
        params.parentUUID=pageParamsObj.page_parent_uuid;
    }
    let obj={url:config.getConfigJson().importExcelDataNew,params:params}
    obj.errorCallback= (response)=>{
        eleMap.get('upload_file').setValue([]);
        fullMap.getObj('mask').hide();
    }
    return httpUtil.post(obj, (response)=>{
    })
}
functionMap.set('uploadExcelTemplateByChild', uploadExcelTemplateByChild);// 将函数添加到 Map 中
/**
 * table通用导出数据
 * @param objID,pkCode
 */
function downExcelByTable() {
    let jsonConfig=this;
    let queryComponent = fullMap.getObj(jsonConfig.objID);
    queryComponent.getTableObj().downExcel()
}
functionMap.set('downExcelByTable', downExcelByTable);// 将函数添加到 Map 中
/**
 * table通用导出oneWord
 * @param objID,pkCode
 */
function downOneWord() {
    let jsonConfig=this;
    let queryComponent = fullMap.getObj(jsonConfig.objID);
    let params = util.clone(queryComponent.getTableObj().code);
    params.pkId=jsonConfig.pkCode;
    if(!util.isNull(jsonConfig['button_click_json_action'])){
        params=util.mergeObject(params,jsonConfig['button_click_json_action'])
    }
    fullMap.getObj('mask').show(`正在导出中...`)
    let obj={url:config.getConfigJson().exportWordDataUrl,params:params}
    return httpUtil.post(obj, (response)=>{
        fullMap.getObj('mask').hide();
        khcToastr.showSuccessMessage('导出成功');
        let downExcelUrl=config.getConfigJson().downFileUrl+'?realFileName='+response.data.data.realFileName+'&fileDiskName='+response.data.data.diskFileName+'&suffix='+response.data.data.suffix
        window.open(downExcelUrl);
    })
}
functionMap.set('downOneWord', downOneWord);// 将函数添加到 Map 中
/**
 * table通用导出oneExcel
 * @param objID,pkCode
 */
function downOneExcel() {
    let jsonConfig=this;
    let queryComponent = fullMap.getObj(jsonConfig.objID);
    let params = util.clone(queryComponent.getTableObj().code);
    params.pkId=jsonConfig.pkCode;
    if(!util.isNull(jsonConfig['button_click_json_action'])){
        params=util.mergeObject(params,jsonConfig['button_click_json_action'])
    }
    fullMap.getObj('mask').show(`正在导出中...`)
    let obj={url:config.getConfigJson().exportExcelOneData,params:params}
    return httpUtil.post(obj, (response)=>{
        fullMap.getObj('mask').hide();
        khcToastr.showSuccessMessage('导出成功');
        let downExcelUrl=config.getConfigJson().downFileUrl+'?realFileName='+response.data.data.realFileName+'&fileDiskName='+response.data.data.diskFileName+'&suffix='+response.data.data.suffix
        window.open(downExcelUrl);
    })
}
functionMap.set('downOneExcel', downOneExcel);// 将函数添加到 Map 中
/**
 * table通用导出onePdf
 * @param objID,pkCode
 */
function downOnePdf() {
    let jsonConfig=this;
    let queryComponent = fullMap.getObj(jsonConfig.objID);
    let params = util.clone(queryComponent.getTableObj().code);
    params.pkId=jsonConfig.pkCode;
    if(!util.isNull(jsonConfig['button_click_json_action'])){
        params=util.mergeObject(params,jsonConfig['button_click_json_action'])
    }
    fullMap.getObj('mask').show(`正在导出中...`)
    let obj={url:config.getConfigJson().createOnePdfURL,params:params}
    httpUtil.post(obj, (response)=>{
        fullMap.getObj('mask').hide();
        khcToastr.showSuccessMessage('导出成功');
        let downExcelUrl = config.getConfigJson().downFileUrl + '?realFileName=' + response.data.data.diskFileName + '&fileDiskName=' + response.data.data.realFileName + '&suffix=' + response.data.data.suffix
        window.open(downExcelUrl);
    })
}
functionMap.set('downOnePdf', downOnePdf);// 将函数添加到 Map 中
/**
 * table通用导出模板
 * @param objID,pkCode
 */
function downExcelTemplate() {
    let jsonConfig=this;
    let queryComponent = fullMap.getObj(jsonConfig.objID);
    queryComponent.getTableObj().downExcelTemplate()
}
functionMap.set('downExcelTemplate', downExcelTemplate);// 将函数添加到 Map 中
/**
 * 工作流-通用查询进度方法
 * @param objID,pkCode
 */
function showHistoryTaskList(){
    let jsonConfig=this;
    let queryViewComponent = fullMap.getObj(jsonConfig.objID);
    let tableViewComponent = queryViewComponent.getTableObj();
    let content = tableViewComponent.getContentMap().get(jsonConfig.pkCode.toString());
    let params = {};
    params.dsCode='ds_bpm_history_task';
    params.formCode='form_bpm_history_task_by_child_page';
    params.queryCode='';
    khcModalForForm = new khcModal({ modalAreaID: config.getConfigJson().modalAreaID });
    khcModalForForm.render().then(() => {
        let formComponent = new form({ parentObjID: khcModalForForm.getEleID(), code: params ,pageID:queryViewComponent.pageID});
        formComponent.khcModalForForm=khcModalForForm;
        khcModalForForm.formObjID=formComponent.getObjID()
        let khcModalForFormKey='khcModalForForm#'+formComponent.getObjID();
        pageInfoMap.push(khcModalForFormKey,khcModalForForm);
        formComponent.setFormShowType('modals')
        //同理可以实现saveBefore
        formComponent.setSaveAfter( ()=> {
            khcModalForForm.hide();
        })
        formComponent.render().then(() => {
            let eleMap = formComponent.getFormMap();
            eleMap.get('uuid').setValue(content['uuid']);
            formComponent.formEdit();
            khcModalForForm.show();
        });
    })
}
functionMap.set('showHistoryTaskList', showHistoryTaskList);// 将函数添加到 Map 中

function showDetailText() {
    let jsonConfig=this;
    jsonConfig.kind='text_detail'//文本详情（不再渲染输入框，只渲染值）
    showDetail.call(jsonConfig)
}
functionMap.set('showDetailText', showDetailText);// 将函数添加到 Map 中

function showDetailForm() {
    let jsonConfig=this;
    jsonConfig.kind='default'//详情表单只读
    showDetail.call(jsonConfig)
}
functionMap.set('showDetailForm', showDetailForm);// 将函数添加到 Map 中

function showDetail() {
    let jsonConfig=this;
    let params = {};
    let queryViewComponent = fullMap.getObj(jsonConfig.objID);
    let pageComponent = fullMap.getObj(queryViewComponent.pageID).componentArray;
    let tableViewComponent = queryViewComponent.getTableObj();
    for (let i = 0; i < pageComponent.length; i++) {
        if (pageComponent[i].type == 'form') {
            params = pageComponent[i].code;
        }
    }
    params=util.clone(params);
    if(util.isNull(jsonConfig.kind)){//加一个参数，会重新请求后端获取参数
        params.order=1;
    }else{
        params.order=2;
    }
    let content = tableViewComponent.dataMap.get(jsonConfig.pkCode.toString());
    let modelKey=`${jsonConfig['button_method']}ByModalSlideForm`;
    let khcModalForForm=pageComponent[modelKey];
    if(khcModalForForm==null||khcModalForForm==undefined){
        khcModalForForm = new khcModalSlide({ modalAreaID: config.getConfigJson().modalAreaID });
        pageComponent[modelKey]=khcModalForForm;
        khcModalForForm.render().then(() => {
            let formComponent = new form({ parentObjID: khcModalForForm.getEleID(), code: params });
            khcModalForForm.formComponent=formComponent;
            formComponent.khcModalForForm=khcModalForForm;
            khcModalForForm.formObjID=formComponent.getObjID()
            let khcModalForFormKey='khcModalForForm#'+formComponent.getObjID();
            pageInfoMap.push(khcModalForFormKey,khcModalForForm);
            formComponent.setFormShowType('modals')
            formComponent.closeButton();
            if(util.isNull(jsonConfig.kind)){
                formComponent.kind='text_detail'
            }else{
                formComponent.kind=jsonConfig.kind
            }
            formComponent.render().then(() => {
                formComponent.renderThenFunc=(content)=> {
                    formComponent.renderValue(content).then(()=>{
                        let eleMap = formComponent.getFormMap();
                        if(pageInfoMap.getObj(formComponent.code.queryCode)==undefined||
                            pageInfoMap.getObj(formComponent.code.queryCode).page_parent_uuid==undefined){
                        }else{
                            eleMap.get('page_parent_uuid').setValue(pageInfoMap.getObj(formComponent.code.queryCode).page_parent_uuid)
                        }
                        if(!util.isNull(jsonConfig.kind)){
                            formComponent.formDetail()
                        }
                        khcModalForForm.show();
                    })

                }
                formComponent.renderThenFunc(content);
            });
        });
    }else{
        let formComponent=khcModalForForm.formComponent
        formComponent.renderThenFunc(content);
    }
}
functionMap.set('showDetail', showDetail);// 将函数添加到 Map 中