"use strict";
import { util } from '../../util/util.js'
import {verify} from '../../util/verify.js'
import {pageInfoMap} from "../../pageInfoMap.js";
import {vCutChar} from "../input/vCutChar.js";
import {inputText} from "../input/inputText.js";
import {inputHidden} from "../input/inputHidden.js";
import {inputSelect} from "../input/inputSelect.js";
import {inputCheckBox} from "../input/inputCheckBox.js";
import {inputFile} from "../input/inputFile.js";
import {httpUtil} from "../../util/httpUtil.js";
import {config} from "../../config.js";

class bpm {
    constructor(data) {
        this.data=data
        this.showButtonNameArray=[];
    }
    //渲染工作流按钮
    render() {
        let that=this;
        let formView = that.data.formView
        let params=formView.code;
        let eleMap = formView.getFormMap();
        let content=formView.getFormValue();
        that.taskId= util.getUrlParam('taskId');
        if(that.taskId==null){//null的入口是列表点击编辑时的入口
            that.process_definition_id=content['process_definition_id']
            that.process_instance_id=content['process_instance_id']
            that.taskIsOnFirstNode()
        }else if(that.taskId!='-1'){//待办的入口（-1则是普通页面和工作流无关）
            let taskData = { formCode: util.getUrlParam('formCode'), pkId: params.pkId, taskId:that.taskId}
            let obj={url:config.getConfigJson().contextPath+'/bpm/getTaskIdFromFormCodeAndPkID',params:taskData}
            httpUtil.post(obj, (response)=>{
                let buttons=eleMap.get("buttons");
                if (!util.isNull(response.data.data.task_id)) {
                    that.process_definition_id=content['process_definition_id']
                    that.process_instance_id=content['process_instance_id']
                    that.taskIsOnFirstNode()
                }else{
                    let buttonEle=document.getElementById(buttons.objID+'_header_button').querySelector('button[name="save"]');
                    buttonEle.style.display='none';//隐藏
                }
                let buttonEle=document.getElementById(buttons.objID+'_header_button').querySelector('button[name="returnQuery"]');
                if(buttonEle!=null){
                    buttonEle.style.display='';//展示
                }
            })
        }
    }
    taskIsOnFirstNode(){
        let that=this;
        let bpmData = { process_definition_id: that.process_definition_id, process_instance_id: that.process_instance_id }
        let obj={url:config.getConfigJson().contextPath+'/bpm/taskIsOnFirstNode',params:bpmData}
        httpUtil.post(obj, (response)=>{
            that.onFirstNode=response.data.data.onFirstNode;
            if(that.taskId==undefined){
                that.taskId=response.data.data.taskID;
            }
            that.getNextButton();
        })
    }
    getNextButton(){
        let that=this;
        let formView = that.data.formView
        let eleMap = formView.getFormMap();
        let content=formView.getFormValue();
        let formButtons = formView.formMap.get('buttons');
        let params = { taskID: that.taskId, defID: that.process_definition_id, insID: that.process_instance_id };
        let obj={url:config.getConfigJson().contextPath+'/bpm/getNextButton',params:params}
        httpUtil.post(obj, (response)=>{
            let elements=document.getElementById(formButtons.objID+'_header_button').querySelectorAll('button[elename="khcBpm"]')
            elements.forEach(element => {//删除旧的按钮，重新渲染新的
                element.remove();
            });
            if (response.data.status == "ok") {
                let buttonMapList=[]
                if(response.data.data==null){
                    that.docConfig= {};
                }else{
                    that.docConfig=response.data.data.docConfig;
                    buttonMapList=response.data.data.buttonMapList;
                }
                that.initFormField();
                formButtons.addBpmButton('showHistoryTaskList', '黄色', '查看进度', 'click', 'showHistoryTaskList', '')
                that.showButtonNameArray.push('showHistoryTaskList')
                for (let i = 0; i < buttonMapList.length; i++) {
                    let buttonInfo = buttonMapList[i];
                    formButtons.addBpmButton(buttonInfo.buttonName, '绿色', buttonInfo.buttonName, 'click', 'showNextNodeUser', buttonInfo)
                    that.showButtonNameArray.push(buttonInfo.buttonName)
                }
                let userName=util.getLocalStorageItem('userName');
                let userID='';
                if(buttonMapList.length>0&&buttonMapList[0].user.length>0){
                    userID=buttonMapList[0].user[0].userID;
                }
                if(content['create_user']!=userName&&userID!='end_bingfa'){//起草人  todo 这里的退回需要调整一下，现在只有不是起草人时，展示退回
                    formButtons.addBpmButton('tuihui', '灰色', '退回', 'click', 'tuihui', '')
                    that.showButtonNameArray.push('tuihui')
                }
                //隐藏收回按钮
                let showNextNodeUserButton=document.getElementById(formButtons.objID+'_header_button').querySelector('button[name="shouhui"]')
                if(showNextNodeUserButton!=null){
                    document.getElementById(formButtons.objID+'_header_button').querySelector('button[name="shouhui"]').style.display='none';
                }
                //屏幕看不到按钮后添加固定按钮样式
                if(formView.formStructureData.formInfo.is_bpm_model=='Y'){
                    that.bpmOnscroll()
                }

            }else{//todo 已结束的任务是否需要控制表单（当前未控制，查看已办时会看到所有的表单信息）
                //删除主表按钮
                if (!that.onFirstNode) {
                    console.log(formButtons.data.buttons)
                    document.getElementById(formButtons.objID+'_header_button').querySelector('button[name="save"]').style.display='none';
                    let showNextNodeUserButton=document.getElementById(formButtons.objID+'_header_button').querySelector('button[name="showNextNodeUser"]')
                    if(showNextNodeUserButton!=null){
                        document.getElementById(formButtons.objID+'_header_button').querySelector('button[name="showNextNodeUser"]').style.display='none';
                    }
                }

                eleMap.forEach( (obj, key)=> {
                    if(that.onFirstNode&&(key!='buttons'&&key!='work_order_opinion')){
                        eleMap.get(key).removeDisabled();//起草节点不控制字段的只读
                    }
                    if(!that.onFirstNode&&(key!='buttons'&&key!='work_order_opinion')){
                        eleMap.get(key).setDisabled();
                    }
                })
                formButtons.addBpmButton('showHistoryTaskList', '黄色', '查看进度', 'click', 'showHistoryTaskList', '')
                eleMap.forEach( (obj, key)=> {
                    if (obj.type == 'opinion') {
                        obj.page_parent_uuid = eleMap.get('uuid').getValue();
                        obj.opinion_show = 'Y'
                        obj.opinion_add = 'N'
                        obj.opinion_edit = 'N'
                        obj.task_id = that.taskId;
                        obj.refreshOpinion();
                    }
                })
                //start 是否展示收回按钮
                let bpmData = { process_definition_id: that.process_definition_id, process_instance_id: that.process_instance_id }
                let obj={url:config.getConfigJson().contextPath+'/bpm/showShouhui',params:bpmData}
                if(!that.onFirstNode){
                    httpUtil.post(obj, (response)=>{
                        if (response.data.data.isShowShouhui == true) {
                            formButtons.addBpmButton('shouhui', '浅蓝', '收回', 'click', 'shouhui', '')
                        }
                    })
                }
            }
        })
    }
    initFormField(){
        let that=this;
        let formView = that.data.formView
        let eleMap = formView.getFormMap();
        let canNullArray=that.docConfig.can_null;
        pageInfoMap.push('canNullArray',canNullArray)
        if(!util.isNull(that.docConfig.show_field)&&util.isNull(formView.layoutFileUrl)){//配置字段白名单则全部隐藏，仅展示白名单字段
            eleMap.forEach( (obj,key)=>{
                if(key!='buttons'&&key!='work_order_opinion'&&eleMap.get(key).hide!=undefined){
                    eleMap.get(key).hide();
                }
            })
        }
        eleMap.forEach( (obj, key)=> {
            if (obj.type == 'opinion') {
                if(that.docConfig.opinion!=undefined){
                    obj.page_parent_uuid = eleMap.get('uuid').getValue();
                    if(that.docConfig.opinion.opinion_show=='Y'){
                        obj.opinion_show=that.docConfig.opinion.opinion_show
                    }
                    if(that.docConfig.opinion.opinion_add=='Y'){
                        obj.opinion_add=that.docConfig.opinion.opinion_add
                    }
                    obj.task_id=that.taskId;
                    obj.refreshOpinion();
                }
            }
            //只读控制
            if(that.docConfig.read_only!=undefined&&key!='buttons'){
                let readOnlyArray=that.docConfig.read_only.split(',');
                if (readOnlyArray.includes(key)) {
                    if(obj.type=='tree'){
                        obj.data.is_read_only='Y'
                        obj.addEventListener();
                    }else{
                        obj.setDisabled();
                    }
                }
            }
            if(obj.type == 'buttons'){
                for (let i = 0; i < obj.data.buttons.length; i++) {
                    if(that.docConfig.show_buttons!=undefined){
                        let buttonEle=document.getElementById(obj.objID+'_header_button').querySelector('button[name="' + obj.data.buttons[i].button_name + '"]');
                        if(that.docConfig.show_buttons.toString().indexOf(obj.data.buttons[i].button_name)==-1){
                            buttonEle.style.display='none';//隐藏
                        }else{
                            buttonEle.style.display='';//展示
                            that.showButtonNameArray.push(obj.data.buttons[i].button_name)
                        }
                    }else{//没有配置指定按钮展示，默认全部展示
                        document.getElementById(obj.objID+'_header_button').querySelector('button[name="' + obj.data.buttons[i].button_name + '"]').style.display='';;
                        that.showButtonNameArray.push(obj.data.buttons[i].button_name)
                    }
                }
            }
            if(!that.onFirstNode){//起草节点不控制字段的只读
                if(that.docConfig.is_form_edit==undefined||that.docConfig.is_form_edit=='N'){
                    if(key!='buttons'&&key!='work_order_opinion'){
                        eleMap.get(key).setDisabled();
                    }
                }
            }else{
                if(key!='buttons'&&key!='work_order_opinion'){
                    if(obj.data.is_read_only!='Y'){
                        eleMap.get(key).removeDisabled();
                    }
                }

            }
            //默认模板控制字段展示
            if(!util.isNull(that.docConfig.show_field)&&util.isNull(formView.layoutFileUrl)&&that.docConfig.show_field.includes(key)){
                eleMap.get(key).show();
            }
            if(obj.type=='childPage'){//子表控制
                setTimeout( ()=>{
                    console.log(obj.data.name)
                    if(that.docConfig.child_page_json==undefined){
                        that.docConfig.child_page_json={};
                    }
                    let childPageConfig=that.docConfig.child_page_json[obj.pageObj.pageCode]
                    //start row按钮展示
                    let tableView=obj.pageObj.queryComponent.tableView
                    let rowButtonArray=tableView.queryInfo.rowButtonArray
                    for (let i = 0; i < rowButtonArray.length; i++) {
                        if(childPageConfig==undefined){
                            if(rowButtonArray[i].button_show_query_type!='3'){
                                rowButtonArray[i].button_show_query_type='2'
                            }
                        }else if(childPageConfig.row_buttons!=undefined){
                            let childPageRowButtons=childPageConfig.row_buttons.split(',');
                            for (let j = 0; j < childPageRowButtons.length; j++) {
                                if(!util.isNull(childPageRowButtons[j])){
                                    if(rowButtonArray[i].button_name==childPageRowButtons[j]){
                                        rowButtonArray[i].button_show_query_type='1'
                                        break;
                                    }else{
                                        rowButtonArray[i].button_show_query_type='2'
                                    }
                                }
                            }
                        }else{
                            rowButtonArray[i].button_show_query_type='2'
                        }
                    }
                    //end row按钮展示
                    //start table按钮展示
                    let tableButtonArray=tableView.queryInfo.tableButtonArray
                    for (let i = 0; i < tableButtonArray.length; i++) {
                        if(childPageConfig==undefined){
                            if(tableButtonArray[i].button_show_query_type!='3'){
                                tableButtonArray[i].button_show_query_type='2'
                            }
                        }else if(childPageConfig.table_buttons!=undefined){
                            let childPageTableButtons=childPageConfig.table_buttons.split(',');
                            for (let j = 0; j < childPageTableButtons.length; j++) {
                                if(!util.isNull(childPageTableButtons[j])){
                                    if(tableButtonArray[i].button_name==childPageTableButtons[j]){
                                        tableButtonArray[i].button_show_query_type='1'
                                        break;
                                    }else{
                                        tableButtonArray[i].button_show_query_type='2'
                                    }
                                }
                            }
                        }else{
                            tableButtonArray[i].button_show_query_type='2'
                            if(tableButtonArray[i].button_name!='deleteChecked'){
                                document.getElementById(obj.pageObj.queryComponent.parentObjID).querySelector('button[name="'+tableButtonArray[i].button_name+'"]').style.display='';
                            }else if(tableView.queryInfo.is_checkbox=='Y'){
                                document.getElementById(obj.pageObj.queryComponent.parentObjID).querySelector('button[name="'+tableButtonArray[i].button_name+'"]').style.display='';
                            }
                        }
                    }
                    //end table按钮展示
                    //start 设置子表的一些属性
                    if(childPageConfig!=undefined&&childPageConfig.table_view!=undefined){
                        //todo 这里不应该写if，如果后面添加其他配置会造成代码冗余（现在先偷懒一下先写if）
                        if(childPageConfig.table_view.is_checkbox!=undefined){
                            obj.pageObj.queryComponent.tableView.queryInfo.is_checkbox=childPageConfig.table_view.is_checkbox;
                        }
                        if(childPageConfig.table_view.is_manager!=undefined){
                            obj.pageObj.queryComponent.tableView.queryInfo.is_managing=childPageConfig.table_view.is_manager;
                        }
                    }
                    //end 设置子表的一些属性
                    //start 将子表单字段设置只读
                    /*let eleMapByChild=obj.pageObj.formComponent.getFormMap()//page渲染
                    let readOnlyKey='readOnly#'+obj.pageObj.formCode.code.formCode
                    if(childPageConfig!=undefined&&childPageConfig.read_only!=undefined){
                        pageInfoMap.push(readOnlyKey,childPageConfig.read_only);
                        eleMapByChild.forEach( (obj,key)=>{//控制子表字段的只读
                            let childPageReadOnly=childPageConfig.read_only.split(',');
                            for (let i = 0; i < childPageReadOnly.length; i++) {
                                if(key==childPageReadOnly[i]){
                                    obj.data.is_read_only='Y';
                                    obj.setDisabled();
                                }
                            }
                        })
                    }*/
                    //end 将子表单字段设置只读
                    //start 将子表字段设置必填
                    let canNullKey='canNull#'+obj.pageObj.formCode.code.formCode
                    if(childPageConfig!=undefined&&childPageConfig.can_null!=undefined&&childPageConfig.can_null.length>0){
                        pageInfoMap.push(canNullKey,childPageConfig.can_null);
                        eleMapByChild.forEach( (obj,key)=>{//控制子表的必填项
                            let childPageCanNull=childPageConfig.can_null.split(',');
                            for (let i = 0; i < childPageCanNull.length; i++) {
                                if(key==childPageCanNull[i]){
                                    obj.data.canNull='Y';
                                    obj.refreshCanNull();
                                }
                            }
                        })
                    }
                    //end 将子表字段设置必填
                    obj.pageObj.queryComponent.getTableObj().refresh();//此时按钮已渲染，上面设置按钮状态，但已渲染的还在，需要刷新一下重重新渲染
                },2000)
            }
        })
        //自定义模板控制字段展示
        if(that.docConfig.show_field!=undefined&&!util.isNull(formView.layoutFileUrl)){
            that.showField();
        }
    }
    //自定义展示字段，如果使用了自定义模板则会隐藏，最终只展示自定义字段
    showField(){
        let that=this;
        let formView = that.data.formView
        let eleMap = formView.getFormMap();
        let content=formView.getFormValue();
        let showFieldArray=that.docConfig.show_field
        document.getElementById('showInputDivlayout').style.display='none'
        let formData= formView.formStructureData.formData;
        //只读控制
        let readOnlyArray=[];
        if(that.docConfig.read_only!=undefined){
            readOnlyArray=that.docConfig.read_only.split(',');
        }
        console.log(readOnlyArray)
        let parentObjID='showInputDivdefault'
        let eleParentObjID='showInputDivdefault'
        for (let i = 0; i < formData.length; i++) {
            let objData = formData[i];
            let key=objData.data.name;
            if(showFieldArray.indexOf(key)==-1){
                continue;
            }
            objData.data.kind='default';// (default：默认水平),(formRow：表格行),(custom：自定义模板)
            //虚拟字段，用来分割默认布局的表单
            //cutChar的上级元素和其他控件不同，其他的上级控件是form本身，而cutChar的和form是同级的存在
            if (objData.show_type == 'cutChar') {
                let cutCharElement = new vCutChar(objData.data);//初始化
                cutCharElement.render(parentObjID);//渲染
                eleParentObjID = cutCharElement.getObjID();
                cutCharElement.show();
            }
            if (objData.show_type == 'text') {
                let textElement = new inputText(objData.data);//初始化
                textElement.render(eleParentObjID);//渲染
                textElement.setValue(content[key])
                if((that.docConfig.is_form_edit==undefined||that.docConfig.is_form_edit=='N')||!readOnlyArray.includes(key)){
                    textElement.setDisabled()
                }
                eleMap.set(key,textElement)
                textElement.show();
            }
            if (objData.show_type == 'hidden') {
                let hiddenElement = new inputHidden(objData.data);//初始化
                hiddenElement.render(eleParentObjID);//渲染
                hiddenElement.setValue(content[key])
            }
            if (objData.show_type == 'select') {
                let selectElement = new inputSelect(objData.data);//初始化
                selectElement.render(eleParentObjID);//渲染
                selectElement.setValue(content[key])
                if((that.docConfig.is_form_edit==undefined||that.docConfig.is_form_edit=='N')||!readOnlyArray.includes(key)){
                    selectElement.setDisabled()
                }
                eleMap.set(key,selectElement)
                selectElement.show();
            }
            if (objData.show_type == 'checkbox') {
                let checkboxElement = new inputCheckBox(objData.data);//初始化
                checkboxElement.render(eleParentObjID);//渲染
                checkboxElement.setValue(content[key])
                if((that.docConfig.is_form_edit==undefined||that.docConfig.is_form_edit=='N')||!readOnlyArray.includes(key)){
                    checkboxElement.setDisabled()
                }
                eleMap.set(key,checkboxElement)
                checkboxElement.show();
            }
            if (objData.show_type == 'file') {
                let fileElement = new inputFile(objData.data);//初始化
                fileElement.render(eleParentObjID);//渲染
                fileElement.setValue(content[key])
                if((that.docConfig.is_form_edit==undefined||that.docConfig.is_form_edit=='N')||!readOnlyArray.includes(key)){
                    fileElement.setDisabled()
                }
                eleMap.set(key,fileElement)
                fileElement.show();
            }
        }
        document.getElementById('showInputDivdefault').style.display=''
    }
    bpmOnscroll(){
        let that=this;
        let formView = that.data.formView;
        let eleMap = formView.getFormMap();
        let buttons=eleMap.get("buttons");
        /*window.onscroll= ()=>{
            let buttonsHtmlObj=document.getElementById(buttons.objID+'_header_button');
            if(buttonsHtmlObj!=null){
                //滚动条高度+视窗高度 = 可见区域底部高度
                let visibleBottom = window.scrollY + document.documentElement.clientHeight;
                //可见区域顶部高度
                let visibleTop = window.scrollY;
                let buttonEle=document.getElementById(buttons.objID+'_header_button').querySelector('button[name="' + buttons.data.buttons[0].button_name + '"]');
                let centerY = buttonEle.offsetTop+(buttonEle.offsetHeight/2)+120;//加120高度
                if(centerY>visibleTop&&centerY<visibleBottom){
                    for (let i = 0; i < that.showButtonNameArray.length; i++) {
                        let buttonEle=document.getElementById(buttons.objID+'_header_button').querySelector('button[name="' + that.showButtonNameArray[i] + '"]');
                        if(buttonEle.style.display==''){
                            buttonEle.style.position='';
                            buttonEle.style.top='';
                            buttonEle.style.zIndex='';
                        }
                    }
                }else{
                    let auto=1;
                    for (let i = 0; i < that.showButtonNameArray.length; i++) {
                        let buttonEle=document.getElementById(buttons.objID+'_header_button').querySelector('button[name="' + that.showButtonNameArray[i] + '"]');
                        if(buttonEle.style.display==''){
                            let buttonTop=10+auto*45;
                            auto++;
                            buttonEle.style.position='fixed';
                            buttonEle.style.top=buttonTop+'px';
                            buttonEle.style.left='88%';
                            buttonEle.style.zIndex=99;
                        }
                    }
                }
            }
        }*/
    }
}
export { bpm }
