<style lang="less">
    .vertical-center-modal{
        display: flex;
        align-items: center;
        justify-content: center;

        .ivu-modal{
            top: 0;
            .ivu-modal-content {
                .ivu-modal-body {
                    padding:0px;
                }
            }
        }
    }
   
</style>
<template>
    <div>
        <Modal v-model="modalSearch" :width="900"  title="高级查询" class-name="vertical-center-modal" :footer-hide="true">
        <div style="padding:10px">
        <Row type="flex" :gutter="10" justify="start" align="middle">
            <Col>
            <Button icon="ios-add" type="primary" @click="addCondition">新建</Button>
            </Col>
            <Col>
            <Button icon="ios-remove" type="primary" @click="delCondition">删除</Button>
            </Col>
            <Col>
            <Button icon="ios-close" type="primary" @click="clearCondition">清空</Button>
            </Col>
            <Col>
            <Button icon="ios-redo-outline" style="float:right;" @click="backCondition">取消</Button>
            </Col>
            <Col>
            <Button icon="ios-search" style="float:right;margin-right:5px;" type="primary" @click="searchCondition">确定查询</Button>
            </Col>
        </Row>
         <EditGrid ref="grid" :config="gridConfig" :dictData="dictData">
        </EditGrid>
        </div>
        </Modal>
    </div>


</template>
<script>
export default {
    name:'searchgrid',
    data () {
        return {
            myConfig:{},
            searchDictData:{},
            modalSearch:false,
            gridConfig:{
                showAddBtn:false,
                showDelBatchBtn:false,
                showDelRow:true,
                showCheckBox:true,
                showIndex:false,
                height:0.5,
                cellbeginedit:this.cellbeginedit,
                items:[  {
                    label:'左括号',
                    name:'bracket_left',
                    type:'ComboBox',
                    width:80,
                    align:'center',
                    codeWithName:false,
                    data:[{code:'1',name:'('},{code:'2',name:'(('}]
                },{
                    label:'条件字段',
                    name:'field',
                    type:'ComboBox',
                    codeWithName:false,
                    align:'center',
                    contentAlign:'left',
                    dictkey:'FIELD'
                }, {
                    label:'运算',
                    name:'calculator',
                    type:'ComboBox',
                    width:100,
                    align:'center',
                    codeWithName:false,
                    clearable:false,
                    data:[{
                        name: '等于',
                        code: '=='
                    }, {
                        name: '大于',
                        code: '>'
                    }, {
                        name: '大于等于',
                        code: '>='
                    }, {
                        name: '小于',
                        code: '<'
                    }, {
                        name: '小于等于',
                        code: '<='
                    }, {
                        name: '不等于',
                        code: '<>'
                    }, {
                        name: '包含',
                        code: 'LIKE'
                    }],
                    defaultValue:'=='
                }, {
                    label:'条件值',
                    name:'editors',
                    type:'TextBox',
                    align:'center',
                    contentAlign:'left',
                    updateCellConfig:this.updateCellConfig
                },{
                    label:'右括号',
                    name:'bracket_right',
                    type:'ComboBox',
                    width:80,
                    align:'center',
                    codeWithName:false,
                    data:[{code:'1',name:')'},{code:'2',name:'))'}]
                },{
                    label:'关系',
                    name:'relationship',
                    type:'ComboBox',
                    width:80,
                    align:'center',
                    codeWithName:false,
                    clearable:false,
                    data:[{code:'1',name:'且'},{code:'2',name:'或'}]
                }]
            },
            initData:[],
            condition:[], 
            bracket:[],
            bracketLeft:0,
            bracketRight:0
        };
    },
    props: {
        config: {
            type: Object,
            default: () => {
                return {};          
            }
        },
        dictData: {
            type: Object,
            default:null
        },
        dataType: {
            type: Object,
            default:null
        },
    },
    created() {
        this.init();
    },
    methods: {
        init() {
            this.myConfig = this.$Method.copy(this.config);
            for (let i=0;i<6;i++) {
                let obj = {};
                obj.relationship = '1';
                obj.field = '';
                obj.calculator = '==';
                obj.editors = '';
                obj.bracket_left = '';
                obj.bracket_right = '';
                this.initData.push(obj);
            }
        },
        updateCellConfig(obj) {
            let field = obj.row.field;
            let itemConfig = Object.assign({},obj.column,this.dataType[field]);
            itemConfig.name = 'editors';
            if (itemConfig.readOnly) {
                delete itemConfig.readOnly;
            }
            if (!itemConfig.visible) {
                delete itemConfig.visible;
            }
            return itemConfig; 
         
        },
        cellbeginedit (obj) {
            let field = obj.column.key;
            let record = obj.row;
            if (field === 'editors') {
                if (!record.field) {
                    return false;
                }
            }
            return true;
        },
        addCondition() {
            this.$refs.grid.addRow();
        },
        delCondition() {
            this.$refs.grid.delBatchRow();
        },
        clearCondition() {
            this.condition = [];
            let data = this.$Method.copy(this.initData);
            this.$refs.grid.setData(data);
        },
        getResultCondition() {
            let obj = {};
            if (this.condition.length > 0) {
                if (this.condition.length === 1) {
                    obj = Object.assign({}, obj, this.condition[0].condition);
                } else {
                    if (this.bracket.length > 0) {
                        let last = this.bracket.length -1;
                        obj['$and'] = [];
                        this.createCondition(last, obj['$and']);
                    }
                }
            }
            return obj;
        },
        searchCondition() {
            this.condition = [];
            if (!this.checkCondition()){
                return;
            }
            this.modalSearch = false;
            this.$emit('search', this.getResultCondition());
        },
        createCondition(index, obj) {
            if (index >= 0) {
                let tempObj = {};
                let list = [];
                let str = this.bracket[index];
                let oper = '$or';
                if (str.indexOf('$and') !== -1) {
                    oper = '$and';
                }
                list = str.split(oper);
                if (list.length > 0) {
                    tempObj[oper] = [];
                    list.forEach(el => {
                        if (el) {
                            let temp = el.split('_');
                            tempObj[oper].push(this.condition[Number(temp[1])].condition);
                        }
                    });
                }
                if (index -1 >= 0) {
                    this.createCondition(index-1,tempObj[oper]);
                } 

                obj.push(tempObj);
            } 
        },
        
        checkCondition() {
            this.bracketLeft = 0;
            this.bracketRight = 0;
            let data = this.$refs.grid.getData();
            let result = [];
          
            if (data && data.length > 0) {
                for (let i=0;i<data.length;i++) {
                    if (data[i].bracket_left || data[i].bracket_right) {
                        if (!data[i].field) {
                            this.alert('第'+(i+1)+'行的条件字段为空，请检查');
                            return false;
                        }
                        if (!data[i].editors) {
                            this.alert('第'+(i+1)+'行的值为空，请检查');
                            return false;
                        }
                        if (data[i].bracket_left) {
                            this.bracketLeft = this.bracketLeft + Number(data[i].bracket_left);
                        }
                        if (data[i].bracket_right) {
                            this.bracketRight = this.bracketRight + Number(data[i].bracket_right);
                        }
                    }
                   
                    if (data[i].field && data[i].editors) {
                        if (!data[i].relationship) {
                            this.alert('第'+(i+1)+'行的关系为空，请检查');
                            return false;
                        }
                        result.push(this.$Method.copy(data[i]));
                    }
                }
            }
            if (this.bracketLeft !== this.bracketRight) {
                this.alert('有效条件的左括号('+this.bracketLeft+')与右括号('+this.bracketRight+')的数量不一致，请检查');
                return false;
            }
            if (result.length > 0) {
                let str = '';
                result.forEach((el,j) => {
                    el.condition = this.getConditionValue(el.field,el.editors,el.calculator,this.dataType[el.field]);
                    if (el.bracket_left === '1') {
                        str = str + '(';
                    }
                    if (el.bracket_left === '2') {
                        str = str + '((';
                    }
                    str = str + el.field + '_' + j;
                    if (el.bracket_right === '1') {
                        str = str + ')';
                    }
                    if (el.bracket_right === '2') {
                        str = str + '))';
                    }
                    if (j + 1 < result.length) {
                        if (el.relationship === '1') {
                            str = str + '$and';
                        } 
                        if (el.relationship === '2') {
                            str = str + '$or';
                        } 
                    }
                });
                this.condition = result;
                this.bracket = [];
                if (str) {
                    this.separateBracket(str, this.bracket);
                }
                this.bracket.some(el => {
                    let andIndex = el.indexOf('$and');
                    let orIndex =  el.indexOf('$or');
                    if (andIndex !== -1 && orIndex !== -1) {
                        let oper = '$or';
                        let opername = '或';
                        if (orIndex < andIndex) {
                            oper = '$and';
                            opername = '且';
                        }
                        let list = el.split('_');
                        let index = -1;
                        if (list.length > 0) {
                            list.some(el2 => {
                                if (el2.indexOf(oper) !== -1) {
                                    let tempList= el2.split(oper);
                                    if (tempList.length > 0) {
                                        index = Number(tempList[0]);
                                        return true;
                                    }
                                }
                            });
                        }
                        if (index > -1) {
                            this.alert('第'+(index+1)+'行的关系不能为['+opername+']或请添加括号' );
                            return true;
                        }  
                    }
                });
            }
            return true;
        },
       
        separateBracket (str,obj) {
            let newStr = this.$Method.copy(str);
            let bracket_leftIndex = newStr.lastIndexOf('(');
            let bracket_rightIndex = newStr.indexOf(')');
            if (bracket_leftIndex !== -1 && bracket_rightIndex !== -1) {
                let tempstr = newStr.substring(bracket_leftIndex+1,bracket_rightIndex);
                obj.push(tempstr);
                str = str.replace('('+tempstr+')','');
                if (str) {
                    this.separateBracket(str,obj);
                }
            } else {
                if (newStr) {
                    obj.push(newStr);
                } 
            }       
        },
      
        show() {
            this.modalSearch = true;
        },
        backCondition() {
            this.modalSearch = false;
        }
    },
    mounted () {
        this.clearCondition();
    }
};
</script>
