

import { translate } from '@/common/utils/language/index'
import EXEC from "@/common/utils/exec"
import { DataStore } from '../stores/DataStore'


/**
 *  页面逻辑描述：
 *  根据某字段的相关参数，改变目标字段的相关参数；
 *  字段：这里包括表单和表格中的控件，列（？），按钮（右键） 等等； 后续补充；
 *  此为页面级函数；处理page内部，不涉及夸page； 
 *  顺序：当前page下=>容器=>field_id=>param(某个参数)=>value(判断rule, if value=='xxx')=>目标容器=>field_id=>param(某个参数)=>value(修改值)
 * 
 */
export const Form_Controls_Logic = ({
    container, 
    data,
    controls
}:any) => {
    if(!container['logics'] || JSON.stringify(container['logics'])=='{}') return
    return new Promise((resolve, reject) => {
        let logics = container['logics']
        let CONTAINER = DataStore().container
        let CONTROLS = controls
        let _x=CONTAINER, _b=container['buttons'],_c=controls,_C=CONTROLS
        console.log('执行了逻辑功能',{logics:{_x,_b,_c,_C}}) // 此一行不要删，不然打包不会变异以上变量
        // 处理条件 
        for(let row of logics){
    
            // 处理目标控件字段（key）
            let targetKeys_form = []
            let field_refer_arr = row['field_refer'].split(',')
            for(let key in container['controls']){
                if(row['cover'] == 'Y'){
                    if(field_refer_arr.indexOf(key)>=0){
                        targetKeys_form.push(key)
                    }
                }else if(row['cover'] == 'N'){
                    if(field_refer_arr.indexOf(key)<0){
                        targetKeys_form.push(key)
                    }
                }
            }

            // 处理目标控件字段（key）
            let targetKeys_btn = []
            for(let btn of container['buttons']){
                let key = btn.field
                if(row['cover'] == 'Y'){
                    if(field_refer_arr.indexOf(key)>=0){
                        targetKeys_btn.push(key)
                    }
                }else if(row['cover'] == 'N'){
                    if(field_refer_arr.indexOf(key)<0){
                        targetKeys_btn.push(key)
                    }
                }
            }
            let DATA = {...data}
            Object.assign(DATA,{
                ...EXEC
            }) 

            // 判断条件
            let pass = false
            let passArr:any = [], passArr_and:any = []
            for(let i = 0; i <= row['conditions'].length; i++){
                if(i == row['conditions'].length){
                    passArr.push(passArr_and)
                    passArr_and = []
                    break
                }
                let item = row['conditions'][i]
                if(item['relation'] && item['relation'] == 'or'){
                    passArr.push(passArr_and)
                    passArr_and = []
                }

                let data = DATA[item['field']] || ''
                let obj:any = {
                    field: item['field'],
                    type: item['field_type'],
                    value: data,
                    compare: item['compare'],
                    compare_value: item['compare_value'] || '',
                }
                passArr_and.push(obj)

            }
            for(let arr of passArr){
                let pass_d = true 
                for(let item of arr){
                    if(!getIf(item)){
                        pass_d = false
                        break
                    }
                }
                pass = pass_d
            }
            if(pass){

                for(let key of targetKeys_form){
                    if(row['control_type']=='disabled' || row['control_type']=='render' || row['control_type']=='show'){
                        container['controls'][key][row['control_type']] = (row['control_value']=='Y'?true:false)
                    }else if(row['control_type']=='required'){ // 必填 规则
                        let required:boolean = row['control_value']=='Y'?true:false
                        container['controls'][key][row['control_type']] = required
                        setRule(required)
                        function setRule(required:boolean){
                            for(let rule of container['controls'][key].rules){
                                if(rule.required == true || rule.required == false){
                                    rule.required = required
                                    return
                                }
                            }
                            container['controls'][key].rules.push({ required, message: translate('it is required'), trigger:'blur'})
                            
                        }

                    }else if(row['control_type']=='data'){
                        if(row['control_value'].indexOf('CONTAINER.') == 0){
                            let key_s = row['control_value'].slice(10).split('.')
                            data[key] = CONTAINER[key_s[0]][key_s[1]][key_s[2]]
                        }else if(row['control_value'].indexOf('DATA.') == 0){
                            let key_t = row['control_value'].slice(5)
                            data[key] = data[key_t]
                        }else{
                            data[key] = row['control_value']
                        }
                    }
                }
                // 处理控件
                for(let key of targetKeys_btn){
                    for(let btn of container['buttons']){
                        if(btn['field'] == key){
                            btn[row['control_type']] = (row['control_value']=='Y'?true:false)
                            break;
                        }
                    }
                }



            }
        }
        resolve('done')
    })
}

export const Table_Controls_Logic = ({container, rows,}:any) => {
    if(!container['logics'] || JSON.stringify(container['logics'])=='{}') return
    return new Promise((resolve, reject) => {
        let logics = container['logics']
        let datas = rows // 选中的列
        // 处理条件 
        let evalstr = ''
        try {
            for(let row of logics){

                // 处理目标控件字段（key）
                let field_refer_arr = row['field_refer'].split(',')
                let targetKeys_btn = []
                for(let btn of container['buttons']){
                    let key = btn.field
                    if(row['cover'] == 'Y'){
                        if(field_refer_arr.indexOf(key)>=0){
                            targetKeys_btn.push(key)
                        }
                    }else if(row['cover'] == 'N'){
                        if(field_refer_arr.indexOf(key)<0){
                            targetKeys_btn.push(key)
                        }
                    }
                    if(btn.dropdowns){
                        for(let dropdown of btn.dropdowns){
                            let key = dropdown.field
                            if(row['cover'] == 'Y'){
                                if(field_refer_arr.indexOf(key)>=0){
                                    targetKeys_btn.push(key)
                                }
                            }else if(row['cover'] == 'N'){
                                if(field_refer_arr.indexOf(key)<0){
                                    targetKeys_btn.push(key)
                                }
                            }
                        }
                    }
                }
                let work = false // 只要一行执行
                //循环行数据
                for(let ritem of rows){
                    evalstr = ''
                    for(let c of row['conditions']){
                        let data = ritem[c['field']] || ''
                        if(data){
                            evalstr = ` ${evalstr} ${c['before_bracket']||''} '${data}' ${stringList[c['compare']] || c['compare']} '${c['compare_value'] || ''}' ${c['after_bracket']||''} ${stringList[c['relation']] || c['relation'] || ''}`
                        }
                    }
                    if(eval(evalstr)){
                        work = true
                    }
                }
                if(work){
                    // 处理控件
                    for(let key of targetKeys_btn){
                        for(let btn of container['tableMenus']){
                            if(btn.children){
                                for(let dropdown of btn.children){
                                    if(dropdown.code == key){
                                        dropdown[row['control_type']] = (row['control_value']=='Y'?true:false)
                                        break;
                                    }
                                }
                            }
                            if(btn['code'] == key){
                                btn[row['control_type']] = (row['control_value']=='Y'?true:false)
                                break;
                            }
                        }
                        for(let btn of container['buttons']){
                            if(btn.dropdowns){
                                for(let dropdown of btn.dropdowns){
                                    if(dropdown.field == key){
                                        dropdown[row['control_type']] = (row['control_value']=='Y'?true:false)
                                        break;
                                    }
                                }
                            }
                            if(btn['field'] == key){
                                btn[row['control_type']] = (row['control_value']=='Y'?true:false)
                                break;
                            }
                        }
                    }


                }
            }

            resolve('done')
        }
        catch(err){
            reject('false')
        }
        
    })
}




var stringList:any = {
    '<>': '!=',
    '=': '=='
}

const getIf = ({compare, compare_value, value}:any) => {
    if(compare=='<>'){
        return value != compare_value
    }else if(compare=='='){
        return value == compare_value
    }
}



