

import { translate } from '@/common/utils/language/index'
import { gather, set_params, goto_page, goto_back, get$$containerParams } from './events'
import { http } from '@/common/utils/request'


/* 结构化数据
 *  1，顺序： 页面>布局>容器(包含是否有页签)>组件(表单、表格等等)
 */
export const setPageData = (res:any) => {
    return new Promise( async (resolve, resject)=>{

        let menu_id:string = res['menu_id']
        let menu_name:string = res['menu_name']
        // 结构化页面层 
        let newPage:any = []
        for(let pageIndex in res['pages']){
            let page = res['pages'][pageIndex]
            let pageObj:any = {
                "seq": page['page_show_seq'],
                "index": [pageIndex],  // 下标（内置）
                "show": page['page_show_seq']==1?true:false,  // 显示（内置）
                "storey": 'page',
                "_EVENTS_" : page['events'],
                "events": {},


                "menu_id": menu_id,
                "menu_name": menu_name,
                "page_id": page['page_id'], 
                "page_code": page['page_code'],
                "page_name": page['page_name'],

                'containers':[],
                'container_query': {},
            }

            // layout结构化布局层
            let newContainers:any = [], newContainer_query=null
            for(let layoutIndex in page['layouts']){
                let layout = page['layouts'][layoutIndex]
                // containers结构化容器层
                for(let containerIndex in layout['containers']){
                    let container = layout['containers'][containerIndex]

                    // todo 容器权限

                    let containerObj:any = {
                        "data": null,
                        "seq": container['container_show_seq'],
                        "type": container['container_type'],  // table\form_query\form_input
                        "selectType": container['select_type'], // radio\checkbox\null
                        "storey": 'container',  
                        "index": [pageIndex,layoutIndex,containerIndex],
                        "logics": container['logics'],
                        "params": {},
                        "events": {},
                        "_EVENTS_" : container['events'],

                        "menu_id": menu_id,
                        "menu_name": menu_name,
                        "page_id": page['page_id'],
                        "page_code": page['page_code'],
                        "page_name": page['page_name'],
                        "container_id": container['container_id'],
                        "container_code": container['container_code'],
                        "container_name": container['container_name'],
                    }

                    for(let evt of container['events']){
                        if(evt['event']=='query' ) {
                            Object.assign(containerObj, {
                                queryEvent: evt,
                            })
                            if(containerObj['queryEvent'].runs?.length>0){
                                containerObj['queryEvent'].run = containerObj['queryEvent'].runs[0]
                                containerObj['queryEvent'].primarykey = containerObj['queryEvent'].run['to_API']['primarykey'] || ''
                            }
                        }
                        else if(evt['event']=='cell-dblclick'){
                            Object.assign(containerObj, {
                                clickEvent: evt,
                            })
                            if(containerObj['clickEvent'].runs?.length>0){
                                containerObj['clickEvent'].run = containerObj['clickEvent'].runs[0]
                            }
                            Object.assign(containerObj.clickEvent, {
                                click: (row:any) => {
                                    setEvent({ 
                                        "key": container['container_code'], //字段名
                                        'field': container['container_code'],
                                        "field_id": container['container_id'],
                                        "field_info": { }, 
                                        "container_info": {
                                            "menu_id": menu_id,
                                            "menu_name": menu_name,
                                            "page_id": page['page_id'],
                                            "page_code": page['page_code'],
                                            "page_name": page['page_name'],
                                            "container":container,
                                            "container_id": container['container_id'],
                                            "container_code": container['container_code'],
                                            "container_name": container['container_name'],
                                            "type": container['container_type']
                                        }, 
                                        "event":evt, 
                                        "event_name":evt['event'], 
                                        "event_type": 'listClick',   
                                        'row_data': row,
                                    })
                                }
                            })
                        }
                    }

                    //以下： 值、表单控件、表格列、组件事件等等处理
                    if(container['container_type']=='form'){ // 表单
                        containerObj['data'] = {}
                        Object.assign(
                            containerObj, 
                            setForm( container['fields'], {
                                "menu_id": menu_id,
                                "menu_name": menu_name,
                                "page_id": page['page_id'],
                                "page_code": page['page_code'],
                                "page_name": page['page_name'],
                                "container":container,
                                "container_id": container['container_id'],
                                "container_code": container['container_code'],
                                "container_name": container['container_name'],
                                "type": container['container_type'],
                            })
                        )
                    }else if(container['container_type']=='table'){
                        containerObj['data'] = []
                        Object.assign(
                            containerObj,
                            setTable(container['fields'], container['events'], {
                                "menu_id": menu_id,
                                "menu_name": menu_name,
                                "page_id": page['page_id'],
                                "page_code": page['page_code'],
                                "page_name": page['page_name'],
                                "container": container,
                                "container_id": container['container_id'],
                                "container_code": container['container_code'],
                                "container_name": container['container_name'],
                                "type": container['container_type'],
                            })
                        )  
                    }

                    
                    if(container['container_type']=='form' && container['form_use']=='query'){
                        newContainer_query = {...containerObj}
                    }else{
                        newContainers.push(containerObj)
                    }
                }
            }
            pageObj['containers'] = newContainers
            pageObj['container_query'] = newContainer_query
            newPage.push(pageObj)
        }
        console.log(newPage)
        // 结构化页面层 结束
        resolve(newPage)
    })
}


const controlsList:any = {
    "line":'line',
    "button": 'button',
    "radio": 'radio',
    "checkbox": 'checkbox',
    "input": 'input',
    "number": 'number',
    "textarea": 'textarea',
    "select-multiple": 'selectmultiple',
    "select": 'select',
    "switch": 'switch',
    "datetime": 'date',
    "datetimerange": 'datetimerange',
    "progress": "progress",
    "scan": "input",
    "scan-input": "input",
    "sort": 'sort',
    "dialog": "dialog",
}


const setForm = (res:any, container_info:any) => {
    let controls:any = {},  buttons:any = [],  quickSelect:any = {},  search:any = {} , sort = {}; 
    for(let fieldIndex in res){
        let field = res[fieldIndex]

        if(controlsList[field['component']]=='button'){
            if(field['parent_field_id']){
                let dropdown_item = {
                    'key': field['field'],
                    'field': field['field'],
                    "field_id": field['field_id'],
                    "alias": field['alias'],
                    "label": translate(field['alias']|| field['field']),
                    "disabled": field['disabled']=='Y'?true:false,
                    "not_verify": field['not_verify']=='Y'?true:false,
                    "auto_run" : false,
                    "type": field['tag_type'],
                    "_EVENTS_" :field['events'],
                    "render": (field['render']=='Y' || field['invalid']=='Y')?true:false, // 渲染
                    "show": field['show']=='Y'?true:false, // 显示
                }
                for(let event of field['events']){
                    if(event['event']=='click' && event['event'][0].auto_run == 'Y'){
                        dropdown_item.auto_run = true
                    }
                    Object.assign(dropdown_item, {
                        [event['event']]: () => {
                            buttonClick({field, container_info, obj:dropdown_item, event, not_verify: field['not_verify']=='Y'?true:false})
                        }
                    }) 
                }
                for(let btn of buttons){
                    if(btn['field'] == field['parent_field_id']){
                        if(!btn['dropdowns']) btn['dropdowns']=[]
                        btn['dropdowns'].push(dropdown_item)
                    }
                }
            }else{

                let obj = {
                    "key": field['field'], //字段名
                    'field': field['field'],
                    "field_id": field['field_id'],
                    "alias": field['alias'],
                    "label": translate(field['alias']|| field['field']),
                    "type": field['tag_type'],
                    "disabled": field['disabled']=='Y'?true:false,
                    "not_verify": field['not_verify']=='Y'?true:false,
                    "params": '',
                    "auto_run": false,
                    "_EVENTS_" :field['events'],
                    "render": (field['render']=='Y' || field['invalid']=='Y')?true:false, // 渲染
                    "show": field['show']=='Y'?true:false, // 显示
                }
                for(let event of field['events']){
                    if(event['event']=='click' && event['runs'] &&  event['runs'][0]?.auto_run == 'Y'){
                        obj.auto_run = true
                    }
                    if(event['event']=='query') continue
                    Object.assign(obj, {
                        [event['event']]: (check:any) => {
                            buttonClick({field, container_info, obj, event, not_verify: field['not_verify']=='Y'?true:false})
                        }
                    })
                }
                buttons.push(obj)
            }
        }else{
            let obj:any = {
                // 标识类
                "key": field['field'], //字段名
                "field": field['field'], //字段名
                "field_id": field['field_id'], //字段ID
                "seq": field['show_seq'], // 顺序（只是标示而已，并不是真正顺序）
                "type": controlsList[field['component']] || 'input',
    
                // 文本类
                "alias": field['alias'],
                "label": translate(field['alias'] || field['field']),
    
                // 显示类
                "render": (field['render']=='Y' || field['invalid']=='Y')?true:false, // 渲染
                "show": field['show']=='Y'?true:false, // 显示
    
                // 状态类
                "required": field['required']=='Y'?true:false, // 必填
                "disabled": (field['disabled']=='Y' || field['invalid']=='Y')?true:false, // 禁用
                "invalid":  field['invalid']=='Y'?true:false, // 坚定的： 不能被方案控制；逻辑要正常
                "status": field['tag_type'] || '',
    
                // 其他
                "compare": field['compare'] || '',
                "attrs": {},
                "events": field['events'],
                "rules": <any>[], 
                "def_value": field['def_value'],
                "placeholder": field['placeholder'] || '',

                // 携带信息
                "carry": <any>{},
            }

            if(field['field_style'] == 'F'){
                Object.assign(obj, {
                    "expand":true
                })
            }
    
            // 类型特殊处理
            if(obj['type'] == 'select' || obj['type'] == 'selectmultiple' ){  // 下拉框 select
                let select = {
                    "type": field['code_type'],
                }
                if( obj['type'] == 'selectmultiple'){
                    Object.assign(select, {
                        "multiple": true,
                    })
                }
                if(obj.def_value && obj.def_value.indexOf('$$SELECT()')==0){
                    Object.assign(select, {
                        "getDefault": true,
                    })
                }
                Object.assign(obj, {  select, })


                //mappings 
                if(field['list_carrys']){
                    let mappings = []
                    for(let row of field['list_carrys']){
                        mappings.push({ param: row['list_carry_field'] , control:row['carry_to_field'] })
                    }
                    Object.assign(obj['select'] ,{mappings,})
                }else if(field['list_carry']){
                    let arr = field['list_carry'].split(','), mappings=[]
                    for(let key of arr){
                        mappings.push({ control:key })
                    }
                    Object.assign(obj['select'] ,{mappings,})
                }

            }else if(obj['type'] == 'dialog' ){  // 下拉框 select
                let dialog = {
                    "type": field['code_type'],
                }

                //mappings 
                if(field['list_carrys']){
                    let mappings = []
                    for(let row of field['list_carrys']){
                        mappings.push({ param: row['list_carry_field'] , control:row['carry_to_field'] })
                    }
                    Object.assign(obj['select'] ,{mappings,})
                }else if(field['list_carry']){
                    let arr = field['list_carry'].split(','), mappings=[]
                    for(let key of arr){
                        mappings.push({ control:key })
                    }
                    Object.assign(obj['select'] ,{mappings,})
                }
                Object.assign(obj, { type: 'dialog', dialog, })
            }else if(obj['type'] == 'switch'){
                Object.assign(obj['attrs'],{
                    "active-value": 'Y',
                    "inactive-value": 'N',
                })
            }

            if(field['component']=='scan' || field['component']=='scan-input'){
                if(field['component']=='scan'){
                    obj['scan'] = {
                        "show": true,
                        'justScan': true,
                    }
                }else{
                    obj['scan'] = {
                        "show": true,
                    }
                }
            }else if(field['component']=='sort' ){
                let keys = field.select_label.split(','), sort = []
                for(let key of keys){
                    let arr = key.split(' ')
                    sort.push({
                        key: arr[0],
                        type: arr[1] || 'ASC' ,
                    })
                }
                obj.sort = sort
            }
            
    

            // 联动 childrens
            if(field['linked_fields']){
                let childrens = []
                for(let item of field['linked_fields']){
                    childrens.push({
                        key: item['field'],
                        paramKey: item['to_parameter'],
                    })
                }
                Object.assign(obj, {
                    childrens: childrens
                })
            }

            // 联动带参  carry
            if(field['events'] && field['events'].length>0 && field['events'][0].event == 'change' && field['events'][0].runs && field['events'][0].runs[0]){
                let run = field['events'][0].runs[0]
                let carry:any = {}
                if(run['filter']){
                    Object.assign(carry, {
                        inKey: run['filter'],
                    })
                }
                if(run['carry_to']){
                    Object.assign(carry, {
                        outKey: run['carry_to'],
                    })
                }
                if(run['to_API']){
                    if(run['to_API'].request_uri){
                        Object.assign(carry, {
                            url: run['to_API'].request_uri,
                        })
                    }
                    if(run['to_API'].params){
                        Object.assign(carry, {
                            params: run['to_API'].params,
                        })
                    }
                    if(run['to_API'].program ){
                        if(carry.params)
                            Object.assign(carry.params, {
                                "[ProcedureName]": run['to_API']['program'],
                            })
                        else
                            Object.assign(carry, {
                                params: {"[ProcedureName]": run['to_API']['program']},
                            })
                    }
                }
                Object.assign(obj,{carry,})
            }


            //判断是否是快速下拉
            if(field['component']=='select' && field['component_config'] && field['component_config'].indexOf('quickSelect=true')>=0){
                Object.assign(obj, { quick:true })
            }
            //判断是否是快速下拉
            if(field['component']=='search' || (field['component']=='input'&&field['component_config'] && field['component_config'].indexOf('search=true')>=0)){
                Object.assign(obj, { search:true })
            }

            
            if(obj.type=='sort'){
                Object.assign(sort, { ...obj })
            }else{
                Object.assign(controls, { [field['field']]:obj })
            }
        }
        
    }
    return {
        controls, buttons, quickSelect, search, sort,
    }
}


const setTable = (fields:any, events:any, container_info:any) => {
    let columns:any = [], buttons:any = [],  _Events_:any = []

    let fields_arr:any = []
    for(let field of fields){
        if(fields_arr.indexOf(field['field'])<0) fields_arr.push(field['field'])
        else continue

        if(field.component == 'button'){
            // 生成表格按钮
            if(field['parent_field_id']){
                // 按钮 
                let dropdown_item = {
                    'key': field['field'],
                    'field': field['field'],
                    "field_id": field['field_id'],
                    "alias": field['alias'],
                    "label": translate(field['alias']|| field['field']),

                    "type": field['tag_type'],
                    "disabled": field['not_verify']=='Y'?false:true,
                    "not_verify": field['not_verify']=='Y'?true:false,
                    "single_row": field['single_select_valid']=='Y'?true:false,   // 选中一行
                    "_EVENTS_" :field['events'],
                }
                for(let event of field['events']){
                    let ev = {
                        [event['event']]: () => {
                            buttonClick({field, container_info, obj:dropdown_item, event, not_verify: field['not_verify']=='Y'?true:false})
                        }
                    }
                    Object.assign(dropdown_item, ev)
                }
                for(let btn of buttons){
                    if(btn['field'] == field['parent_field_id']){
                        if(!btn['dropdowns']) btn['dropdowns']=[]
                        btn['dropdowns'].push(dropdown_item)
                    }
                }
            }else{
                // 按钮
                let btn = {
                    "key": field['field'], 
                    "field": field['field'], 
                    "field_id": field['field_id'],
                    "alias": field['alias'],
                    "label": translate(field['alias']|| field['field']),
                    "type": field['tag_type'],
                    "visible":field['show']=='Y'?true:false,
                    "disabled": field['not_verify']=='Y'?false:true,
                    "not_verify": field['not_verify']=='Y'?true:false,
                    "single_row": field['single_select_valid']=='Y'?true:false,
                    "_EVENTS_" :field['events'],
                }
                
                
                for(let event of field['events']){
                    let ev = {
                        [event['event']]: () => {
                            buttonClick({field, container_info, obj:btn, event, not_verify: field['not_verify']=='Y'?true:false})
                        }
                    }
                    Object.assign(btn, ev)
                }
                buttons.push(btn)
                _Events_.push(field['events'])
            }
        }else{

            let col:any = {
                "key": field['field'], 
                "field": field['field'], 
                "field_id": field['field_id'],
                "alias": field['alias'],
                "label": translate(field['alias']|| field['field']),
                "field_style": field['field_style'] || '',
                "show": (field['show']=='Y' && field['render']=='Y')?true:false, // 显示
                "render":  field['render']=='Y'?true:false,
                "invalid" : (field['invalid']=='Y')?true:false, // 动态标题也会提交
                "isNumber": field['export_sum']=='Y'?true:false,
                "grid": field['columns'] || 2,
                "type": field['component'],
                "showLabel": true,
            }
            if(field['field_style']=='M'){
                Object.assign(col, { 'lv': 1 })
            }else if(field['field_style']=='S'){
                Object.assign(col, { 'lv': 2 })
            }else if(field['field_style']=='F'){
                Object.assign(col, { 'expand': true })
            }else if(field['field_style']=='C'){
                Object.assign(col, { 'isStatus': true, expand: true  })
            }
            columns.push(col)
        }
    }
    return {
        columns, buttons,
    }
}

const buttonClick = ({field, container_info, obj, event, not_verify}:any) => {
    if(field['tag_type']=='danger'){
        uni.showModal({
            title: translate('tip'),
            content: `${translate('Continue to')} ${translate(field['field'])}?`,
            success: function (res) {
                if (res.confirm) {
                    setEvent({ 
                        "key": field['field'], //字段名
                        'field': field['field'],
                        "field_id": field['field_id'],
                        "field_info": { ...obj }, 
                        "container_info": container_info, 
                        "event":event, 
                        "event_name":event['event'], 
                        "event_type": 'buttonClick',   
                        "not_verify":not_verify,
                    })
                } 
            }
        });
    }else{
        setEvent({ 
            "key": field['field'], //字段名
            'field': field['field'],
            "field_id": field['field_id'],
            "field_info": { ...obj }, 
            "container_info": container_info, 
            "event":event, 
            "event_name":event['event'], 
            "event_type": 'buttonClick',    
            "not_verify":not_verify,
        })
    }
}
const setEvent = async (config:any) => {
    let {
        field,
        field_id,
        field_info,
        container_info,
        event_type,
        event, 
        event_name, 
        row_data,
        not_verify,
    } = config


    try {
        // 单事件
        let from_page = container_info.page_code
        let from_container = container_info.container_code
        if(event?.runs.length==1){
            let run:any = event.runs[0]
            let to_page = run.to_pages || container_info.page_code
            let to_container = run.to_containers 

            // 判断是否要跳页面
            let goto = to_page == from_page? false : true
            // 按钮事件
            if(event_type=='buttonClick' ){
                if(run.to_API && run.to_API['request_uri'] && run.to_API['request_method']){
                    // 如果有接口
                    gather({page_code:from_page, container_code:from_container, type:container_info.type, run}).then(async (data:any) => {
                        toAPI({
                            datas: data,
                            view:{
                                ...container_info
                            },
                            to_API: run.to_API, 
                            event: run, 
                            field: field_info,
                        }).then((res:any) => {
                            if(run.to_pages == 'BACK'){
                                uni.navigateBack({
                                    delta: 1
                                });
                            }else if(run.to_pages == 'REFRESH'){
                                
                            }else if(to_container){
                                let res_data = {}
                                if(res.data.result){
                                    res_data = res.data.result
                                }
                                set_params({data:{
                                    ...res_data,
                                }, page_code:to_page, container_code:to_container })
                                if(goto) goto_page({page_code:to_page})
                            }else if(goto){
                                goto_page({page_code:to_page})
                            }
                        })
                    })
                }else{
                    // 如果没接口
                    if(to_container){
                        gather({page_code:from_page, container_code:from_container, type:container_info.type, run}).then(async (data:any) => {
                            if(data){
                                await set_params({data, page_code:to_page, container_code:to_container })
                            }

                            if(goto){
                                goto_page({page_code:to_page})
                            }
                        })
                    }else{
                        if(to_page == 'RETURN_DATA'){
                            uni.navigateBack({
                                delta: 1
                            });
                            gather({page_code:from_page, container_code:from_container, type:container_info.type, run}).then(async (data:any) => {
                                uni.$emit('returnData', { data, })
                            })
                        }else if(goto){
                            goto_page({page_code:to_page})
                        }
                    }
                }
            }
            // 列表点击事件
            else if(event_type=='listClick' ){
                let newData = {}
                let filters:any = run?.filter?.split(',') || null
                if(run?.filter && filters?.length>0){
                    for(let key of filters){
                    if(row_data[key]){
                        Object.assign(newData, {[key]:row_data[key]})
                    }
                    }
                }else{
                    Object.assign(newData, row_data)
                }

                await set_params({data:newData, page_code:to_page, container_code:to_container })
                
                if(to_page == 'RETURN_DATA'){
                    uni.navigateBack({
                        delta: 1
                    });
                    uni.$emit('returnData', { data:[newData], })
                }else if(goto) {
                    goto_page({page_code:to_page, page_name:container_info.page_name})
                }
            }


        }

        // 多事件
        else if(event?.runs.length > 1){
            
            let length = event.runs.length
            let run = event.runs[length-1]
            let to_page = run.to_pages || container_info.page_code
            let to_container = run.to_containers 
            let goto = to_page == from_page? false : true

            let MultiEventApi:any = []
            for(let i in event.runs){
                let api = event.runs[i].to_API || {}
                
                let row = {
                    "request_method":api["request_method"],
                    "request_uri":api["request_uri"],
                    "runParams":get$$containerParams(api['params']) || {},
                    "primarykey": api['primarykey'],
                    "filter": event.runs[i].filter,
                }
                if(api['program']){
                    Object.assign(row.runParams, {
                        '[ProcedureName]':api['program']
                    })
                }
                // 处理access固定参数
                MultiEventApi.push({...row})
            }

            if(event_type=='buttonClick' ){
                if(run.to_API && run.to_API['request_uri'] && run.to_API['request_method']){
                    // 如果有接口
                    gather({page_code:from_page, container_code:from_container, type:container_info.type, run, }).then(async (data:any) => {
                        toAPI({
                            datas: data,
                            view:{
                                ...container_info
                            },
                            to_API: run.to_API, 
                            event: run, 
                            field: field_info,
                            MultiEventApi,
                        }).then((res:any) => {
                            if(run.to_pages == 'BACK'){
                                uni.navigateBack({
                                    delta: 1
                                });
                            }else if(run.to_pages == 'REFRESH'){
                                
                            }else if(to_container){
                                let res_data = {}
                                if(res.data.result){
                                    res_data = res.data.result
                                }
                                set_params({data:{
                                    ...res_data,
                                }, page_code:to_page, container_code:to_container })
                                if(goto) goto_page({page_code:to_page})
                            }else if(goto){
                                goto_page({page_code:to_page})
                            }
                        })
                    })
                }
            }
        }

    }
    catch (error:any) {
    }

}


export const toAPI = ({view, to_API, datas, event, limit=false, field, MultiEventApi=undefined}:any) => {
    return new Promise((resolve, reject)=> {
        let params = {}

        // 处理access固定参数
        let apiParams = get$$containerParams(to_API['params'])
        if(Array.isArray(datas)){
            if(to_API['request_method']=='POST'){
                let rows = datas
                Object.assign(params, { ...apiParams, })
                Object.assign(params, {
                    "[commMapStr]": JSON.stringify({
                        "[ProcedureName]": to_API['program'],
                        ...apiParams,
                        "[Primarykey]": to_API['primarykey'],
                    }),
                    "[detailListStr]": JSON.stringify(rows),
                })
            }else if(to_API['request_method']=='POST-A'){
                let primarykey = to_API['primarykey']
                let primaryDataArr = []
                for(let row of datas){
                    primaryDataArr.push(row[primarykey])
                }
                let headerMapStr = {
                    "[ProcedureName]": to_API['program'],
                    ...apiParams,
                    ...datas[0],
                    "[Primarykey]": to_API['primarykey'],
                    [primarykey]:primaryDataArr.join(',')
                }
                Object.assign(params, {
                    "[headerMapStr]": JSON.stringify(headerMapStr),
                    ...datas[0],
                    [primarykey]:primaryDataArr.join(',')
                })
            }else if(to_API['request_method']=='POST-F'){
                let rows = datas
                Object.assign(params, { ...apiParams, })
                Object.assign(params, {
                    "[commMapStr]": JSON.stringify({
                        "[ProcedureName]": to_API['program'],
                        ...apiParams,
                        "[Primarykey]": to_API['primarykey'],
                    }),
                    "[detailListStr]": JSON.stringify(rows),
                })
                Object.assign(params, {'[IS-FORM-DATA]': true})
            }else{
                uni.showToast({
                    icon: 'error',
                    title: '请求方式配置有误',
                })
            }
        }else{
            Object.assign(params, { ...datas, ...apiParams, })
            if(to_API['request_method']=='POST'){
                let headerMapStr = {
                    "[ProcedureName]": to_API['program'],
                    ...apiParams,
                    "[Primarykey]": to_API['primarykey'],
                }
                if(datas['exec_type']){
                    headerMapStr['exec_type'] = datas['exec_type']
                }
                Object.assign(params, {
                    "[headerMapStr]": JSON.stringify(headerMapStr)
                })
            }else{
                Object.assign(params, {
                    "[ProcedureName]": to_API['program'],
                    ...apiParams,
                })
            }
            if(limit){
                Object.assign(params, {
                    limit: 100, // pageSize
                    start: 1, // currentPage
                })
            }
        }

        // 处理 udf_param_json
        let udf_param_json = { 
            "container_id": view['container_id'],
            "field_id": field?.field_id,
            "run_id": event['run_id'],
        }
        if(to_API['cross_container_to_table']){
            Object.assign(udf_param_json, {cross_container_to_table: to_API['cross_container_to_table']})
        }
        if(to_API['order_by']){
            Object.assign(udf_param_json, {order_by: to_API['order_by']})
        }
        if(to_API['auth']){
            Object.assign(udf_param_json, {auth: to_API['auth']})
        }
        Object.assign(params, {
            'udf_param_json': JSON.stringify(udf_param_json)
        })
        if(MultiEventApi){
            Object.assign(params, {
                '[MultiEventApi]': JSON.stringify(MultiEventApi)
            })
        }


        
        /**
         * 以下下运行请求 
         *  @param request_method 请求类型 post、get、put、detele..  注意这里需要转成小写；
         *  @param request_uri 请求接口 
         */
        let options:any = {}
        let method = to_API['request_method'].toLowerCase()
        if(to_API['request_method'] == 'POST-A') method = 'post'
        else if(to_API['request_method'] == 'POST-F') {
            method = 'post'
            options['_isFormData_'] = true
        }
        
        http[method](to_API['request_uri'], params, options).then((res:any)=>{
            if(method=='post'){
                uni.showToast({
                    icon: 'success',
                    title: `${translate(field?.field)}  ${translate('success')}`,
                })
            }
            let timer=setTimeout(()=>{
                clearTimeout(timer)
                resolve(res)
            }, method=='post'? 1000:0)
        }).catch((err:any)=>{ 
            reject(false)
        })
    })
}