/**
 * 主要针对固定按钮的事件操作，main函数作为固定的入口，
 */

"use strict";
import { util } from '../../../util/util.js'
import { fullMap } from '../../../fullMap.js';
import { khcAlert } from '../../alert/khcAlert.js'
import { config } from "../../../config.js";
import {khcModal} from "../../alert/khcModal.js";
import {pageInfoMap} from "../../../pageInfoMap.js";
import {httpUtil} from "../../../util/httpUtil.js";
import {form} from "./form.js";
import {khcToastr} from "../../alert/khcToastr.js";

//objID 是按钮所在的组件的id，可以根据id获取到组件对象本身，然后展开对组件的各项操作。
//method 真正的执行方法
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);
    }
}
function save() {
    let jsonConfig=this;
    let formComponent = fullMap.getObj(jsonConfig.objID);
    formComponent.saveData();
}
functionMap.set('save', save);// 将函数添加到 Map 中
function returnQuery() {
    let jsonConfig=this;
    let component = fullMap.getObj(jsonConfig.objID);
    if(component.returnQuery!=undefined){
        component.returnQuery();
    }else{
        let eleMap = component.getFormMap();
        let content = component.getFormValue();
        let pageFormObj = fullMap.getObj(component.pageID);
        if (pageFormObj == undefined) {
            if(util.getUrlParam('pageCode')){//工作流的链接
                let aaa=util.getUrlParam('taskId');
                if(component.pageID==undefined){//工作流的子表返回关闭并模态框刷新数据
                    let khcModalForForm=pageInfoMap.getObj('khcModalForForm#'+component.getObjID());
                    khcModalForForm.hide();
                }else if(util.getUrlParam('taskId')!='-1'){
                    let userName=util.getLocalStorageItem('userName');
                    if(content['create_user']==userName){
                        let pageCode=util.getUrlParam('pageCode');
                        window.location.href=config.getIndexUrl()+'?pageCode='+pageCode+'&queryInfo={}';
                    }else{
                        window.location.href=config.getIndexUrl()+'#page_todo';//非起草人全部跳转到待办列表
                    }
                }else{
                    window.location.href=config.getIndexUrl()+'#'+util.getUrlParam('pageCode');//普通编辑页面，从哪个页面来，跳回哪个页面
                }
            }else{
                let khcModalForForm=pageInfoMap.getObj('khcModalForForm#'+component.getObjID());
                khcModalForForm.hide();
                //document.getElementById(config.getConfigJson().modalAreaID).innerHTML = '';
            }
        } else {
            let eleMap=component.getFormMap()
            let pkFieldName=component.pkFieldName;
            if(util.isNull(eleMap.get(pkFieldName))){
                khcToastr.showErrorMessage('找不到配置的主键字段：'+pkFieldName+',请前往数据源query组件管理修改。');
                return ;
            }
            let pkId=eleMap.get(pkFieldName).getValue();
            let isReturnQuery=true;
            if(util.isNull(pkId)){
                eleMap.forEach(async  (obj,key)=>{
                    if(obj.type=='childPage'){
                        let queryComponent=obj.pageObj.queryComponent;
                        let tableView=queryComponent.tableView
                        if(tableView.allItemNum!=0){
                            isReturnQuery=false;
                            let alertData = {};
                            alertData.title = '当前子表"'+queryComponent.queryInfo.query_name+'"已填'+tableView.allItemNum+'条数据,请确认是否继续返回';
                            alertData.text = '如果不保存则可能造成数据丢失';//目前只对默认的formComponent生效，重写的不会生效，后续再优化
                            alertData['cancelButtonColor'] = '#181C21E6';
                            khcAlert.showConfirm(alertData, ()=>{
                                pageFormObj.showComponent('query')
                            })
                        }
                    }
                })
                if(isReturnQuery){
                    if(component.khcModalForForm!=null){
                        component.khcModalForForm.hide();
                    }else{
                        pageFormObj.showComponent('query')
                    }
                }
            }else{
                let returnFunc=function (){
                    let isReturnUpdateData=component.isReturnUpdateTableData
                    if(!util.isNull(isReturnUpdateData)&&isReturnUpdateData){//返回是否更新列表数据
                        pageFormObj.queryComponent.tableView.refresh();
                    }
                    if(component.khcModalForForm!=null){
                        component.khcModalForForm.hide();
                    }else{
                        pageFormObj.showComponent('query')
                    }
                }
                eleMap.forEach(async  (obj,key)=>{
                    if(obj.type=='childPage'){
                        let queryComponent=obj.pageObj.queryComponent;
                        let tableView=queryComponent.tableView
                        if ((tableView.tUtil!=null&&tableView.isEditTableData())) {//子表列表编辑时数据修改了提示修改信息。
                            isReturnQuery=false;
                            let alertData = {};
                            alertData.title = '当前子表"'+queryComponent.queryInfo.query_name+'"修改了数据未保存,请确认是否继续返回';
                            alertData.text = '如果不保存则修改的内容不会更新';//目前只对默认的formComponent生效，重写的不会生效，后续再优化
                            alertData['cancelButtonColor'] = '#181C21E6';
                            khcAlert.showConfirm(alertData, ()=>{
                                returnFunc();
                            })
                        }
                    }
                })
                if(!isReturnQuery){
                    return ;
                }
                returnFunc();
            }
        }
    }

}
functionMap.set('returnQuery', returnQuery);// 将函数添加到 Map 中
function createOnePdf() {
    let jsonConfig=this;
    let component = fullMap.getObj(jsonConfig.objID);
    let eleMap = component.getFormMap();
    let pkId = eleMap.get(component.pkFieldName).getValue();
    let params = component.code;
    params.pkId = pkId;
    let obj={url:config.getConfigJson().createOnePdfURL,params:params}
    httpUtil.post(obj, (response)=>{
        Swal.fire(
            '导出成功',
            response.data.data.diskFileName,
            'success'
        )
        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('createOnePdf', createOnePdf);// 将函数添加到 Map 中

function showNextNodeUser(objID, buttonInfo) {
    let component = fullMap.getObj(objID);
    let eleMap= component.getFormMap();
    let oldEditData=component.oldEditData;
    let content = component.getFormValue();
    let formButtons=eleMap.get('buttons');
    let buttonEle = document.getElementById(formButtons.objID+'_header_button').querySelector('button[name="save"]');
    for (let key in content) {
        if(key.indexOf('vm_')>=0){
            content[key]='';
        }
    }
    let canNullArray=pageInfoMap.getObj('canNullArray');
    if(canNullArray instanceof Array){
        for (let i = 0; i < canNullArray.length; i++) {
            let obj=eleMap.get(canNullArray[i]);
            if(obj.type!='file'){
                let value=obj.getValue();
                if(util.isNull(value)){
                    khcAlert.showWarningMessage(obj.data.label_name+' 为必填项');
                    return ;
                }
            }else{
                let value=obj.getValue();
                if(!(value instanceof Array)||value.length==0){// 判断不是数组或长度等于0就不予送下一节点
                    khcAlert.showWarningMessage(obj.data.label_name+' 为必填项');
                    util.toTops({id:obj.eleID,isFocus:true})
                    return ;
                }
            }
        }
    }
    if(!util.compareJsonObj(oldEditData,content)){//&&buttonEle.style.display==''
        khcAlert.showWarningMessage('检测到您修改了数据，请先保存！');
        return ;
    }
    if(eleMap.get('work_order_opinion').opinion_add=='Y'){
        if(!eleMap.get('work_order_opinion').isEdit){//没有添加意见则不允许送下一步
            khcAlert.showWarningMessage('当前节点要求需要填写意见');
            util.toTops({id:eleMap.get('work_order_opinion').eleID,isFocus:true})
            return ;
        }else if(eleMap.get('work_order_opinion').editData.is_agree=='否'){
            khcAlert.showWarningMessage('您的意见是不同意，可退回');
            return ;
        }
    }
    console.log(component.code);
    let pkId = content[component.pkFieldName]
    let taskID = content['process_task_id']
    let defID = content['process_definition_id']
    let insID = content['process_instance_id']
    if(buttonInfo.is_end_bpm!='Y'){
        let text = '';
        let nextUserID = '';
        for (let i = 0; i < buttonInfo.user.length; i++) {
            let user = buttonInfo.user[i];
            text += '部门:' + user.orgName + '\n';
            text += '姓名:' + user.userName;
            nextUserID = user.userID;
        }
        let data = {};
        data['title'] = '确认是否送' + buttonInfo.buttonName;
        data['showCancelButton'] = true;
        data['confirmButtonColor'] = '#3085d6';
        data['cancelButtonColor'] = '#99a0a6';
        let taskId = util.getUrlParam('taskId');
        let pageCode=util.getUrlParam('pageCode')
        if(pageCode==null){
            pageCode=config.getPageCode();
        }
        khcAlert.showConfirm(data, ()=>{
            let params = {defID: defID, insID: insID, pkId: pkId, dsCode: component.code.dsCode,pageCode: pageCode,nextUserID:nextUserID,nodeName:buttonInfo.buttonName,taskId:taskId }
            let obj={url:config.getConfigJson().contextPath+'/bpm/sendNext',params:params}
            httpUtil.post(obj, (response)=>{
                khcAlert.showSuccessMessage('操作成功，即将跳转页面...')
                setTimeout(()=>{
                    let userName=util.getLocalStorageItem('userName');
                    if(content['create_user']==userName){//起草人
                        let pageCode=util.getUrlParam('pageCode');
                        if(pageCode==null){
                            let pageFormObj = fullMap.getObj(component.pageID);
                            pageFormObj.showComponent('query')
                        }else{
                            let pageCode=util.getUrlParam('pageCode');
                            window.location.href=config.getIndexUrl()+'?pageCode='+pageCode+'&queryInfo={}';
                        }
                    }else{
                        window.location.href=config.getIndexUrl()+'#page_todo';//非起草人全部跳转到待办列表
                    }
                }, 2000);
            })

    
        })
    }else{
        let title =  buttonInfo.buttonName
        let data = {};
        data['title'] = title;
        data['text'] = '点击确定结束流程';
        data['text'] = '点击确定'+title;
        data['confirmButtonColor'] = '#d33';
        data['cancelButtonColor'] = '#3085d6';
        data['confirmButtonText'] = '确定';
        khcAlert.showConfirm(data,  ()=> {
            let params = { taskID: taskID, defID: defID, insID: insID, pkId: pkId, dsCode: component.code.dsCode,nodeName:buttonInfo.buttonName }
            let obj={url:config.getConfigJson().contextPath+'/bpm/endProcess',params:params}
            httpUtil.post(obj, (response)=>{
                khcAlert.showSuccessMessage('操作成功，即将跳转页面...')
                setTimeout(()=>{
                    let userName=util.getLocalStorageItem('userName');
                    if(content['create_user']==userName){//起草人
                        let pageCode=util.getUrlParam('pageCode');
                        if(pageCode==null){
                            let pageFormObj = fullMap.getObj(component.pageID);
                            pageFormObj.showComponent('query')
                        }else{
                            //window.location.href='./index.html#'+util.getUrlParam('pageCode');//跳转页面，如果在子表里添加工作流就不好跳转了，全部改为跳转待办
                            window.location.href=config.getIndexUrl()+'#page_todo';//非起草人全部跳转到待办列表
                        }
                    }else{
                        window.location.href=config.getIndexUrl()+'#page_todo';//非起草人全部跳转到待办列表
                    }
                }, 2000);
            })
        })
    }

    
}
functionMap.set('showNextNodeUser', showNextNodeUser);// 将函数添加到 Map 中
let khcModalForForm;
//这个不能控制退回收回等状态，被废弃
/*function showHistoryTaskList(objID, buttonInfo) {
    let component = fullMap.getObj(objID);
    let content = component.getFormValue();
    khcModalForForm = new khcModal({ modalAreaID: config.getConfigJson().modalAreaID });
    let showHistoryObjId=util.getUUID();
    let khcModalHtml = '';
    khcModalHtml += '<div class="card mb-4">'
    khcModalHtml += '<h6 class="card-header">'
    khcModalHtml += '流程进度'
    khcModalHtml += '</h6>';
    khcModalHtml += '<div style="padding: 0.1rem;" class="" id="'+showHistoryObjId+'">'
    khcModalHtml += '</div></div>';
    let process_instance_id = content['process_instance_id']
    let params = {process_instance_id:process_instance_id}
    let obj={url:config.getConfigJson().contextPath+'/bpm/historyTaskList',params:params}
    httpUtil.post(obj,function (response){
        khcModalForForm.render().then(() => {
            document.getElementById(khcModalForForm.getEleID()).insertAdjacentHTML("beforeEnd", khcModalHtml);
            let historyTaskList=response.data.data.data;
            let buttonHtml = '<div class="demo-inline-spacing mt-3" style="margin-left:20px">';
            buttonHtml += '<button type="button" id="'+showHistoryObjId+'returnQuery" style="margin: 0.375rem 0.375rem 0.9375rem 0 !important;" class="btn btn-dark">返回</button>';
            buttonHtml += '</div>';
            document.getElementById(showHistoryObjId).insertAdjacentHTML("beforeEnd", buttonHtml);
            let historyHtml='';
            historyHtml+='<div class="col-sm-12" style="overflow:auto;">\n' +
                '    <table id="khcafd66bed9929b5198462ce87b48d8ffc" width="100%" style="min-width:400px;"\n' +
                '           class=" table table-striped table-bordered dataTable no-footer">\n' +
                '        <thead>\n' +
                '        <tr style="background-color:#cccccc" role="row">\n' +
                '            <th width="100" style="text-align:center" fieldname="">操作人</th>\n' +
                '            <th width="100" style="text-align:center" fieldname="">节点</th>\n' +
                '            <th width="100" style="text-align:center" fieldname="">收到时间</th>\n' +
                '            <th width="100" style="text-align:center" fieldname="">完成时间</th>\n' +
                '        </tr>\n' +
                '        </thead>\n' +
                '        <tbody>\n'
            let sortHistoryTaskList=[];
            let nullTimeHistoryTaskList=[];
            for (let i = 0; i < historyTaskList.length; i++) {
                let nodeEndTime=historyTaskList[i].nodeEndTime;
                if(nodeEndTime==null){
                    if(i==0){
                        historyTaskList[i].nodeEndTime='草稿';
                    }else{
                        historyTaskList[i].nodeEndTime='办理中';
                    }
                    nullTimeHistoryTaskList.push(historyTaskList[i]);
                }else{
                    sortHistoryTaskList.push(historyTaskList[i]);
                }
            }
            sortHistoryTaskList=util.jsonSort(sortHistoryTaskList,'nodeEndTime',false)
            for (let i = 0; i < sortHistoryTaskList.length; i++) {
                historyHtml+=
                    '        <tr showdatatr="" class="gradeA odd" role="row">\n' +
                    '            <td eleName="" style="vertical-align: middle;">'+sortHistoryTaskList[i].nodeUser+'</td>\n' +
                    '            <td eleName="" style="vertical-align: middle;">'+sortHistoryTaskList[i].nodeName+'</td>\n' +
                    '            <td eleName="" style="vertical-align: middle;">'+sortHistoryTaskList[i].nodeStartTime+'</td>\n' +
                    '            <td eleName="" style="vertical-align: middle;">'+sortHistoryTaskList[i].nodeEndTime+'</td>\n' +
                    '        </tr>\n'
            }
            for (let i = 0; i < nullTimeHistoryTaskList.length; i++) {
                historyHtml+=
                    '        <tr showdatatr="" class="gradeA odd" role="row">\n' +
                    '            <td eleName="" style="vertical-align: middle;">'+nullTimeHistoryTaskList[i].nodeUser+'</td>\n' +
                    '            <td eleName="" style="vertical-align: middle;">'+nullTimeHistoryTaskList[i].nodeName+'</td>\n' +
                    '            <td eleName="" style="vertical-align: middle;">'+nullTimeHistoryTaskList[i].nodeStartTime+'</td>\n' +
                    '            <td eleName="" style="vertical-align: middle;">'+nullTimeHistoryTaskList[i].nodeEndTime+'</td>\n' +
                    '        </tr>\n'
            }
            historyHtml+='        </tbody>\n' +
                '    </table>\n' +
                '</div>'
            document.getElementById(showHistoryObjId).insertAdjacentHTML("beforeEnd", historyHtml);
            document.getElementById(showHistoryObjId+'returnQuery').addEventListener('click', function (){
                khcModalForForm.hide();
            });
            khcModalForForm.show();
        })
    })
}*/
function showHistoryTaskList() {
    let jsonConfig=this;
    let component = fullMap.getObj(jsonConfig.objID);
    let content = component.getFormValue();
    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 });
        khcModalForForm.formObjID=formComponent.getObjID()
        let khcModalForFormKey='khcModalForForm#'+formComponent.getObjID();
        pageInfoMap.push(khcModalForFormKey,khcModalForForm);
        formComponent.setFormShowType('modals')
        formComponent.render().then(() => {
            let eleMap = formComponent.getFormMap();
            eleMap.get('uuid').setValue(content['uuid']);
            formComponent.formEdit();
            khcModalForForm.show();
        });
        //同理可以实现saveBefore
        formComponent.setSaveAfter( ()=> {
            khcModalForForm.hide();
        })
    })
}
functionMap.set('showHistoryTaskList', showHistoryTaskList);// 将函数添加到 Map 中
function shouhui() {
    let jsonConfig=this;
    let component = fullMap.getObj(jsonConfig.objID);
    let eleMap= component.getFormMap();
    let content = component.getFormValue();
    console.log(component.code);
    let pkId = content[component.pkFieldName]
    let taskID = content['process_task_id']
    let defID = content['process_definition_id']
    let insID = content['process_instance_id']
    let title = '确认是否收回'
    let data = {};
    data['title'] = title;
    data['showCancelButton'] = true;
    data['confirmButtonColor'] = '#3085d6';
    data['cancelButtonColor'] = '#99a0a6';
    data['confirmButtonText'] = '确定';
    khcAlert.showConfirm(data,  () =>{
        let params = { process_definition_id: defID, process_instance_id: insID }
        let obj={url:config.getConfigJson().contextPath+'/bpm/shouhui',params:params}
        httpUtil.post(obj, (response)=>{
            khcAlert.showSuccessMessage('操作成功，即将跳转页面...')
            setTimeout(()=>{
                let userName=util.getLocalStorageItem('userName');
                if(content['create_user']==userName){//起草人
                    let pageCode=util.getUrlParam('pageCode');
                    if(pageCode==null){
                        let pageFormObj = fullMap.getObj(component.pageID);
                        pageFormObj.showComponent('query')
                    }else{
                        let pageCode=util.getUrlParam('pageCode');
                        window.location.href=config.getIndexUrl()+'?pageCode='+pageCode+'&queryInfo={}';
                    }
                }else{
                    window.location.href=config.getIndexUrl()+'#page_todo';//非起草人全部跳转到待办列表
                }
            }, 2000);
        })
    })
}
functionMap.set('shouhui', shouhui);// 将函数添加到 Map 中
function tuihui() {
    let jsonConfig=this;
    let component = fullMap.getObj(jsonConfig.objID);
    let eleMap= component.getFormMap();
    let content = component.getFormValue();
    console.log(component.code);
    let pkId = content[component.pkFieldName]
    let taskID = content['process_task_id']
    let defID = content['process_definition_id']
    let insID = content['process_instance_id']
    let title = '确认是否退回'
    let data = {};
    data['title'] = title;
    data['showCancelButton'] = true;
    data['confirmButtonColor'] = '#3085d6';
    data['cancelButtonColor'] = '#99a0a6';
    data['confirmButtonText'] = '确定';
    khcAlert.showConfirm(data,  () =>{
        let params = { process_definition_id: defID, process_instance_id: insID }
        let obj={url:config.getConfigJson().contextPath+'/bpm/tuihuiQicaoren',params:params}
        httpUtil.post(obj, (response)=>{
            khcAlert.showSuccessMessage('操作成功，即将跳转页面...')
            setTimeout(()=>{
                let userName=util.getLocalStorageItem('userName');
                if(content['create_user']==userName){//起草人
                    let pageCode=util.getUrlParam('pageCode');
                    if(pageCode==null){
                        let pageFormObj = fullMap.getObj(component.pageID);
                        pageFormObj.showComponent('query')
                    }else{
                        window.location.href=config.getIndexUrl()+'#'+util.getUrlParam('pageCode');
                    }
                }else{
                    window.location.href=config.getIndexUrl()+'#page_todo';//非起草人全部跳转到待办列表
                }
            }, 2000);
        })
    })
}
functionMap.set('tuihui', tuihui);// 将函数添加到 Map 中

/**
 * 表单按钮，通过json配置执行简单操作
 * this
 * this['button_click_json_config']
 * this['button_click_json_config']['type'] 必填 （form1：更新行状态并保存）
 * this['button_click_json_config']['content'] type==form1 必填 （要更新的数据）
 */
function formButtonClickFunc(){
    let jsonConfig=this;
    let formComponent = fullMap.getObj(jsonConfig.objID);
    let buttonJsonConfig=jsonConfig['button_click_json_config'];
    let eleMap = formComponent.getFormMap();
    let updateContent=buttonJsonConfig['content'];
    if(buttonJsonConfig['type']=='form1') {//1，编辑状态并保存
        for (const key in updateContent) {
            eleMap.get(key).setValue(updateContent[key]);
        }
        formComponent.saveData();
    }
}
functionMap.set('formButtonClickFunc', formButtonClickFunc);// 将函数添加到 Map 中