<script>
import { deepCopy } from '../../utils/assist';
import Base from './basegrid.vue';
import elementResizeDetectorMaker from 'element-resize-detector';
import {gzip} from 'pako';
export default {
    name: 'viewgridbase',
    extends: Base,
    data () {
        return {
            myConfig:{
                resources:'',
                method:'',
                response:'',
                searchParam:null,
                readOnly:true,
                multiSelect:true,
                bindSearchParam:'ph_key',
                showAll:false,
                exportMethod:'exportExcel',
                separator:'::',
                exportType:'2',
                overrideData:'',
                headStyle:'padding-bottom: 10px;padding-top: 10px;',
                multiSelectGrid:false,
                multiGridCol:11,
                multiGridTitle:'已选择',
                gridTitle:'待选择',
                highLightRow:true,
                dynamicColumnFlag:false,
                dynameicColumnConfig: {
                    groupColumns:[],
                    dynameicColumnName:'',
                    dynameicColumnValue:'',
                    dynameicColumnValueTitle:'',
                    dynameicColumnValuePro:{},
                    dynameicColumnSumLable:'动态合计'
                }
            },
            multiGridCol:11,
            gridCol:11,
            editRowFlag:false,
            singleData:{},
            searchBeforeSearchParam:{},
            order_field:'',
            order_direction:'',
            rightActive:false,
            leftActive:false,
            multiSelectData:[],
            multiTableColumns:[],
            dynamicColumnItems:[],
            tempMultiSelectData:[],
            multiSoltTableColumns:[],
            showHelpBtn:false
        };
    },
    computed:{
        makeTableColumns() {
            if (this.myConfig.dynamicColumnFlag) {
                return [];
            } else {
                return this.initColumn();
            }
        }
    },
    methods: {
        customInit() {
            if (this.isPop) {
                if (!this.myConfig.showCheckBox) {
                    if (this.myConfig.multiSelect) {
                        this.myConfig.showCheckBox = true;
                    }
                }
                if (this.myConfig.multiGridCol) {
                    this.multiGridCol = Number(this.myConfig.multiGridCol);
                    this.gridCol = 24 - 2 - this.multiGridCol;
                }
                this.myConfig.tableSize = 'small';
                this.myConfig.headStyle = '';
                this.myConfig.showBorder = false;
                this.myConfig.headStyle = '';
                this.myConfig.pageSize = 'small';
                if (this.myConfig.height === undefined) {
                    this.myConfig.height = 360;
                }
                if (!this.myConfig.pageSizeNum) {
                    this.myConfig.pageConfig.page_size = 50;
                }
            }

            if (this.myConfig.pageSizeNum) {
                this.myConfig.pageConfig.page_size = Number(this.myConfig.pageSizeNum);
            }
            this.myConfig.items.forEach(el => {
                if (el.resizable  === undefined) {
                    el.resizable  = true;
                }
                if (!el.width && !el.minWidth) {
                    el.minWidth = 60;
                }
            });
            if (this.myConfig.multiSelectGrid) {
                this.multiTableColumns = this.multiInitColumn();
            }
            if (this.myConfig.gridType === 'billGrid') {
                this.getModuleMethod();
            }
            if (this.myConfig.dynamicColumnFlag) {
                this.myConfig.showPage = false;
            }
            let self = this;
            this.curHelpUrl = this.OmdUrl.getCurHelpUrl(self);
            if (this.curHelpUrl) {
                this.showHelpBtn = true;
            } else {
                this.showHelpBtn = false;
            }
        },
        conditionAction(temp) {
            let data = [];
            switch (temp.action) {
                case 'condition_search' :
                    if (temp.para) {
                        this.conditionSearchParam = this.$Method.copy(temp.para);
                    }
                    this.refurbish();
                    break;
                case 'condition_clear' :
                    this.conditionSearchParam = {};
                    break;
                case 'condition_ok' :
                    if (this.myConfig.multiSelect) {
                        data = this.getSelection();
                    } else {
                        if (this.singleData.currentRow) {
                            data.push(this.singleData.currentRow);
                        }
                    }
                    if (data.length === 0) {
                        this.alert('请选择');
                    } else {
                        temp.rows = data;
                        this.$emit('conditionAction',temp);
                    }
                    break;
                case 'condition_cancel' :
                    this.$emit('conditionAction',temp);
                    break;
            }
        },
        getSearchParam(obj, flag) {
            let searchParam =Object.assign({},this.myConfig.searchParam,this.searchBeforeSearchParam);
            if (!searchParam) {
                searchParam = {};
            }
            if (this.myConfig.response === 'report') {
                searchParam = Object.assign({},searchParam,this.conditionSearchParam);
            } else {
                let tempSearchParam = {};
                for (let el in searchParam) {
                    if (this.conditionSearchParam[el]) {
                        tempSearchParam[el]={'$and':[]};
                        let temp = {};
                        temp[el] = searchParam[el];
                        tempSearchParam[el]['$and'].push(temp);
                        let temp2 = {};
                        temp2[el] = this.conditionSearchParam[el];
                        tempSearchParam[el]['$and'].push(temp2);
                    }
                }
                searchParam = Object.assign({},searchParam,this.conditionSearchParam);
                for (let el in tempSearchParam) {
                    searchParam['$and'] = this.$Method.copy(tempSearchParam[el]['$and']);
                    delete searchParam[el];
                }
            }

            if (this.myConfig.showPage) {
                if (!flag) {
                    this.myConfig.pageConfig.page_no = 1;
                    searchParam.page_no  = 1;
                    this.culPage = 1;
                } else {
                    if (this.myConfig.pageConfig.page_no) {
                        searchParam.page_no = this.myConfig.pageConfig.page_no;
                    } else {
                        searchParam.page_no  = 1;
                    }
                }
                searchParam.page_size = this.myConfig.pageConfig.page_size;
            }
            if (this.order_field) {
                searchParam.order_field = this.order_field;
                if (this.order_direction) {
                    searchParam.order_direction = this.order_direction;
                }
            }
            if (obj) {
                searchParam =Object.assign({},searchParam,obj);
            }
            if (!this.myConfig.dynamicColumnFlag) {
                if (this.summaryColumn && this.summaryColumn.length > 0) {
                    searchParam.summary_fld = this.summaryColumn.join(',');
                }
            }
            if (this.myConfig.showSumGroup) {
                searchParam.sumgroups = this.myConfig.sumgroups;
            }
            if (this.myConfig.overrideSearchParam) {
                return this.myConfig.overrideSearchParam(searchParam);
            } else {
                return searchParam;
            }

        },
        setWhereParam(obj) {
            this.conditionSearchParam = this.$Method.copy(obj);
        },
        refurbish(obj,flag) {
            this.loading = true;
            let self = this;
            this.singleData = {};
            self.data = [];
            self.asyncPost(self.myConfig.resources,self.myConfig.method,self.getSearchParam(obj,flag),function(data) {
                self.dynamicInitData = data;
                if (self.myConfig.dynamicColumnFlag) {
                    self.makeDynamicColumn();
                } else {
                    self.refurbishSucceedDefault();
                }
                self.loading = false;
            },function(e) {
                self.loading = false;
                self.$nextTick(() => {
                    setTimeout(() => {
                        self.alert(e, null, 2);
                    }, 1000);
                });
            });
        },
        changePage (para) {
            let old = this.myConfig.pageConfig.page_no;
            if (this.myConfig.refurbishCheck) {
                this.myConfig.refurbishCheck(para,old,this.callBackChangePage);
            } else {
                this.myConfig.pageConfig.page_no = para;
                this.refurbish(null, true);
            }

        },
        refurbishSucceedDefault () {
            this.sumGroupNum = 0;
            if (this.dynamicInitData  && this.dynamicInitData[this.myConfig.response]) {
                if (this.myConfig.showAll) {
                    if (this.myConfig.rowAll) {
                        this.dynamicInitData[this.myConfig.response].splice(0,0,this.myConfig.rowAll);
                    }
                }
                let data = [];
                if (this.myConfig.overrideData) {
                    data = this.myConfig.overrideData(this.dynamicInitData[this.myConfig.response]);
                } else {
                    data = this.dynamicInitData[this.myConfig.response];
                }
                if (this.dynamicInitData.sumgroups) {
                    data = this.doSumgroups(data, this.dynamicInitData.sumgroups);
                }
                this.data = data;
                this.tempData = this.$Method.copy(data);
            }
            if (this.dynamicInitData.total_results !== undefined) {
                this.myConfig.pageConfig.total_results= Number(this.dynamicInitData.total_results);
            }
            if (this.dynamicInitData.total_summary !== undefined) {
                this.total_summary = Object.assign({}, {}, this.dynamicInitData.total_summary);
                if (!this.myConfig.showSummary) {
                    Object.assign(this.myConfig,{'showSummary':true});
                }
            } else {
                if (this.myConfig.showSummary) {
                    Object.assign(this.myConfig,{'showSummary':false});
                }
            }
        },
        callBackChangePage(flag ,newvalue, oldvale)  {
            if (!flag) {
                this.$nextTick(() => {
                    this.myConfig.pageConfig.page_no = oldvale;
                    this.myConfig.showPage = false;
                    this.myConfig = Object.assign({},this.myConfig);
                    this.$nextTick(() => {
                        this.myConfig.showPage = true;
                        this.myConfig = Object.assign({},this.myConfig);
                    });
                });
            } else {
                this.myConfig.pageConfig.page_no = newvalue;
                this.refurbish(null,true);
            }
        },
        callBackChangePageSize(flag ,newvalue, oldvale)  {
            if (!flag) {
                this.$nextTick(() => {
                    this.myConfig.pageConfig.page_size = oldvale;
                    this.myConfig.showPage = false;
                    this.myConfig = Object.assign({},this.myConfig);
                    this.$nextTick(() => {
                        this.myConfig.showPage = true;
                        this.myConfig = Object.assign({},this.myConfig);
                    });
                });
            } else {
                this.myConfig.pageConfig.page_size = newvalue;
                this.refurbish(null,true);
            }
        },
        changePageSize (para) {
            let old = this.myConfig.pageConfig.page_size;
            if (this.myConfig.refurbishCheck) {
                this.myConfig.refurbishCheck(para,old,this.callBackChangePageSize);
            } else {
                this.myConfig.pageConfig.page_size = para;
                if (this.data && this.data.length  > 0) {
                    this.refurbish(null, true);
                }
            }
        },
        sortChagne (para) {
            this.order_field = '';
            this.order_direction = '';
            let tempField = [];
            let tempDirection = [];
            /*
            沿用老版本，丢弃searchParam中的
            if (this.config.searchParam) {
                if (this.config.searchParam.order_field) {
                    tempField = this.config.searchParam.order_field.split(',');
                    if (this.config.searchParam.order_direction) {
                        tempDirection = this.config.searchParam.order_direction.split(',');
                        let tempDirectionNum = tempDirection.length;
                        for (let i=tempDirectionNum;i<tempField.length;i++) {
                            tempDirection.push('asc');
                        }
                    } else {
                        for (let i=0;i<tempField.length;i++) {
                            tempDirection.push('asc');
                        }
                    }
                }
            }*/
            if (para.order !== 'normal') {
                let index = tempField.findIndex(el => el === para.key);
                if (index > -1) {
                    tempDirection.splice(index, 1, para.order);
                } else {
                    tempField.push(para.key);
                    tempDirection.push(para.order);
                }
            }
            if (tempField.length > 0) {
                this.order_field = tempField.join();
                this.order_direction = tempDirection.join();
            }

            if (this.data && this.data.length  > 0) {
                this.refurbish();
            }
        },
        onCurrentChange(currentRow,oldCurrentRow) {
            this.singleData = {};
            this.singleData.currentRow= currentRow;
            this.singleData.oldCurrentRow= oldCurrentRow;
            if (this.myConfig.onSingleChange) {
                this.myConfig.onSingleChange();
            }
            if (this.myConfig.showCheckBox) {
                if (this.myConfig.onSetRowCheck) {
                    this.myConfig.onSetRowCheck(currentRow._customIndex,true);
                } else {
                    this.setRowCheck(currentRow._customIndex,true);
                }
            }

        },
        onSelect(rows,curRow) {
            if (this.myConfig.onSelect) {
                this.myConfig.onSelect(rows,curRow);
            }
        },
        onSelectCancel(rows,curRow) {
            if (this.myConfig.onSelectCancel) {
                this.myConfig.onSelectCancel(rows,curRow);
            }
        },
        OnSelectionChange(row) {
            this.$nextTick(() => {
                if (this.myConfig.onSelectionChange) {
                    this.myConfig.onSelectionChange(row);
                }
                if (row && row.length > 0) {
                    this.leftActive = true;
                } else {
                    this.leftActive = false;
                }
                let data = this.$Method.copy(this.data);
                let flag = false;
                data.forEach((el,index) => {
                    flag = false;
                    row.forEach(el2 => {
                        if (index === el2._customIndex) {
                            flag = true;
                            return true;
                        }
                    });
                    el._checked = flag;
                })
                this.data = data;
                this.tempData = this.$Method.copy(data);
                /*if (this.data.length === row.length) {
                    if (!this.isAll) {
                        this.$refs.table.selectAll(true);
                        this.isAll = true;
                    } else {
                        this.isAll = false;
                    }
                }*/
            });
        },
        OnMultiSelectionChange (row) {
            this.$nextTick(() => {
                let data = this.$Method.copy(this.tempMultiSelectData);
                let flag = false;
                data.forEach((el,index) => {
                    flag = false;
                    row.forEach(el2 => {
                        if (index === el2._customIndex) {
                            flag = true;
                            return true;
                        }
                    });
                    el._checked = flag;
                })
                this.tempMultiSelectData = data;
                if (row && row.length > 0) {
                    this.rightActive = true;
                } else {
                    this.rightActive = false;
                }
            });
        },
        removeRow(index) {
            this.data.splice(index, 1);
        },
        doBatchAction(obj) {
            if (obj.name !== 'addData') {
                let data = this.getSelection();
                if (data.length  === 0) {
                    this.alert('请至少选择一行');
                    return;
                }
                obj.data= data;
            }
            this.$emit('doAction', obj);
        },
        add() {
            let obj = {};
            obj.name ='addData';
            this.$emit('doAction', obj);
        },
        setSearchBeforeSearchParam(obj) {
            this.searchBeforeSearchParam = Object.assign({},{},obj);
        },
        clearSearchBeforeSearchParam() {
            this.searchBeforeSearchParam = {};
        },
        popValueChanged (para) {
            let reData = [];
            let self = this;
            let searchParam = Object.assign({},self.getSearchParam(),para);
            self.synchroPost(self.myConfig.resources,self.myConfig.method,searchParam,function(data) {
                if (data && data[self.myConfig.response]) {
                    reData = data[self.myConfig.response];
                }
            },null);
            return reData;
        },
        getTotalCount() {
            let total_results = '';
            if (this.myConfig.pageConfig.total_results !== undefined) {
                total_results = this.myConfig.pageConfig.total_results;
            }
            return  total_results;
        },
        export(asyncExport,afterFun) {
            if(this.data.length == 0){
                this.alert('请先查询数据');
                return;
            }
            let _param = this.getSearchParam();
            if (this.OmdUrl.maxRowNum) {
                _param.maxrownum = this.OmdUrl.maxRowNum;
            }

            if (this.OmdUrl.maxDataNum) {
                _param.maxdatanum = this.OmdUrl.maxDataNum;
            }
            let  modulecode = this.getModulecode();
            if (modulecode) {
                _param.modulecode = modulecode;
            }
            let dict = {};
            dict.dictdata = {};
            _param.fields =this.$Method.getGridField(this.myConfig.items,this.myConfig.separator,this.dictData, dict.dictdata);
            if (!_param.fields) {
                _param.fields = '';
            }
            // 添加总数
            let totalCount = this.getTotalCount();
            if (totalCount) {
                _param.fields += ',totalCount'+ this.myConfig.separator + totalCount;
            }
            // 添加模块号
            if (modulecode) {
                _param.fields += ',modulecode'+ this.myConfig.separator + modulecode;
            }
            let exportMethod  = this.myConfig.exportMethod;
            if (asyncExport) {
                exportMethod = 'asyncExport';
            }
            let _baseUrl = this.myConfig.resources.replace('rest', exportMethod);
            let  _self  = this;
            const encodedArray =this.zip(JSON.stringify(dict.dictdata));
            _param.dictdata = encodeURIComponent(encodedArray);
            if (asyncExport) {
                this.asyncExport(_baseUrl,this.myConfig.method,_param,afterFun);
            } else {
                this.doExportExcel(_baseUrl, this.myConfig.method, _param,this.myConfig.exportType, _self);
            }
        },
        zip (str) {
            let  binaryString = gzip(str, { to: 'string' });
            return btoa(binaryString);
        },
        asyncExport(_baseUrl,method, _param,afterFun) {
            let self = this;
            self.synchroPost(_baseUrl,method,_param,function(data) {
                if (data.flag === '1') {
                    if (afterFun) {
                        afterFun();
                    } else {
                        this.alert('文件正在生成，请稍后');
                    }
                }
            },null);
        },
        initAsynExportConfig(columns,headname,newColumns) {
            for (let i = 0; i < columns.length; i++) {
                    let column = this.$Method.copy(columns[i]);
                    if (column.visible !== false && column.isExport !== false) {
                        if (column.name) {
                            column.label = headname + column.label;
                            newColumns.push(column);
                        }
                        if (column.children) {
                            let culhead = headname +  '(' + column.label + ')';
                            this.initAsynExportConfig(column.children,culhead,newColumns);
                        }
                    }
                }
        },
        setRowHighlight(index , flag) {
            if (index > -1) {
                let newRow = Object.assign({},this.data[index],{});
                newRow._highlight = flag;
                this.$nextTick(() => {
                    this.data.splice(index,1,newRow);
                    this.tempData.splice(index,1,newRow);
                    if (!this.myConfig.multiSelect) {
                        this.singleData.currentRow = this.$Method.copy(this.data[index]);
                    }
                });
            }
        },
        getSelection() {
            if (this.myConfig.multiSelect === false) {
                if (this.singleData.currentRow) {
                    return  [this.singleData.currentRow];
                } else {
                    return [];
                }
            } else {
                if (this.myConfig.multiSelectGrid) {
                    return this.$Method.copy(this.multiSelectData);
                } else {
                    return this.$refs.table.getSelection();
                }
            }
        },
        setSelection(data) {
            if (this.myConfig.multiSelectGrid) {
                this.multiSelectData = [];
                this.$nextTick(() => {
                    this.multiSelectData = data;
                    this.tempMultiSelectData = this.$Method.copy(this.multiSelectData);
                });
            }
        },
        moveToLeft() {
            let data = this.$refs.multiSelectTable.getSelection();
            if (data && data.length > 0) {
                data.forEach(el => {
                    let index = this.multiSelectData.findIndex(el2 => el2[this.myConfig.responseId] === el[this.myConfig.responseId]);
                    if (index > -1) {
                        this.multiSelectData.splice(index, 1);
                    }
                });
            }
            this.tempMultiSelectData = this.$Method.copy(this.multiSelectData);
            this.rightActive = false;
        },
        moveToRight() {
            let data = this.$refs.table.getSelection();
            if (data && data.length > 0) {
                data.forEach(el => {
                    if (this.myConfig.multiCheck) {
                        if (this.myConfig.multiCheck(this.multiSelectData, el)) {
                            delete el._customIndex;
                            delete el._checked;
                            this.multiSelectData.push(el);
                        }
                    } else {
                        let index = this.multiSelectData.findIndex(el2 => el2[this.myConfig.responseId] === el[this.myConfig.responseId]);
                        if (index === -1) {
                            delete el._customIndex;
                            delete el._checked;
                            this.multiSelectData.push(el);
                        }
                    }
                });
            }
            this.tempMultiSelectData = this.$Method.copy(this.multiSelectData);
        },
        multiInitColumn () {
            let columns = [];
            let items = this.myConfig.items;
            if (this.myConfig.multiItems) {
                items = this.myConfig.multiItems;
            }
            if (!items || items.length === 0) {
                return columns;
            }
            this.initCheckColumn(columns);
            this.initMultiIndexColumn(columns);
            const length = items.length;
            for (let i = 0; i < length; i++) {
                if (items[i].visible !== false) {
                    //this.setColumn(i);
                    // 添加复杂列项的支持
                    this.initCommonColumn(items[i],columns);
                }
            }
            this.initExpandColumn(columns);
            this.initOperColumn(columns);
            let multiSoltTableColumns = [];
            this.getSoltTableColumns(columns, multiSoltTableColumns);
            this.multiSoltTableColumns = multiSoltTableColumns;
            return columns;
        },
        customClearData() {
            this.multiSelectData = [];
            this.rightActive = false;
            this.leftActive = false;
            if (this.myConfig.dynamicColumnFlag) {
                this.tableColumns = [];
                this.soltTableColumns = [];
                this.newRow = {};
                this.total_summary = {};
                if (this.myConfig.showSummary) {
                    Object.assign(this.myConfig,{'showSummary':false});
                }
            }
        },
        clearCondition() {
            if (this.$refs.condition && this.$refs.condition.clear) {
                this.$refs.condition.clear();
            }
        },
        clearCurrentRow() {
            if (this.$refs.table) {
                this.$refs.table.clearCurrentRow();
            }
        },
        delRow(index) {
            this.data.splice(index, 1);
            this.tempData = this.data;
        },
        updataRow(index,para) {
            let row = Object.assign({}, this.data[index], para);
            this.data.splice(index,1,row);
            this.tempData = this.data;
        },
        initMultiIndexColumn(columns) {
            let index = {};
            index.type = 'index';
            index.key = 'index';
            index.width = 45;
            index.title = '行号';
            index.align = 'center';
            columns.push(index);
        },
        makeDynamicColumn()  {
            let initData = [];
            this.tableColumns = [];
            this.soltTableColumns = [];
            this.total_summary = {};
            if (this.dynamicInitData && this.dynamicInitData[this.myConfig.response]) {
                initData = this.$Method.copy(this.dynamicInitData[this.myConfig.response]);
                let groupColumns = [];
                groupColumns = this.$Method.copy(this.myConfig.dynameicColumnConfig.groupColumns);

                let dynameicColumnNames = [];
                if (this.myConfig.dynameicColumnConfig.dynameicColumnName) {
                    dynameicColumnNames = this.myConfig.dynameicColumnConfig.dynameicColumnName.split(',');
                }
                let dynameicColumnValue = [];
                if (this.myConfig.dynameicColumnConfig.dynameicColumnValue) {
                    dynameicColumnValue = this.myConfig.dynameicColumnConfig.dynameicColumnValue.split(',');
                }
                let dynameicColumnValueTitle = [];
                if (this.myConfig.dynameicColumnConfig.dynameicColumnValueTitle) {
                    dynameicColumnValueTitle = this.myConfig.dynameicColumnConfig.dynameicColumnValueTitle.split(',');
                }
                let fatherTemp = [];
                dynameicColumnNames.forEach(el2 => {
                    let tmp = {};
                    tmp.name = el2;
                    fatherTemp.push(tmp);
                });
                let obj = {};
                let endNodes = {};
                let num = 0;
                initData.forEach(el => {
                    let groupId = '';
                    groupColumns.forEach(el2 => {
                        groupId = groupId + el[el2] + '-' ;
                    });
                    if (groupId) {
                        groupId = groupId.substring(0,groupId.length - 1);
                    }
                    let dyId = '';
                    let fatherId = '';
                    dynameicColumnNames.forEach((el2,index) => {
                        dyId = dyId + el[el2] + '-';
                        if (!fatherTemp[index][el[el2]]) {
                            fatherTemp[index][el[el2]] = {};
                            fatherTemp[index][el[el2]].fatherId = fatherId;
                            fatherTemp[index][el[el2]].label=el[el2];
                        }
                        fatherId = el[el2];
                        if (index === dynameicColumnNames.length -1) {
                            fatherTemp[index][el[el2]].id = dyId.substring(0,dyId.length - 1);
                        }
                    });
                    if (dyId) {
                        dyId = dyId.substring(0,dyId.length - 1);
                    }

                    if (!obj[groupId]) {
                        obj[groupId] = {};
                        obj[groupId].data = {};
                        groupColumns.forEach(el2 => {
                            obj[groupId].data[el2] = el[el2];
                        });
                        obj[groupId].columns = {};
                    }
                    if (!obj[groupId].columns[dyId]) {
                        if (dynameicColumnValue.length > 1) {
                            obj[groupId].columns[dyId] = {};
                            dynameicColumnValue.forEach(elv => {
                                obj[groupId].columns[dyId][elv] = el[elv];
                            });
                        } else {
                            obj[groupId].columns[dyId] = el[this.myConfig.dynameicColumnConfig.dynameicColumnValue];
                        }
                    }
                    if (!endNodes[dyId]) {
                        endNodes[dyId] = {};
                        endNodes[dyId].name = 'dy_col_' + num;
                        if (dynameicColumnValue.length > 1) {
                            endNodes[dyId].sum = {};
                            dynameicColumnValue.forEach(elv => {
                                endNodes[dyId].sum[elv] = el[elv];
                            });
                        } else {
                            endNodes[dyId].sum = 0;
                        }
                        num++;
                    }
                    if (dynameicColumnValue.length > 1) {
                        dynameicColumnValue.forEach(elv => {
                            endNodes[dyId].sum[elv] =  Number(endNodes[dyId].sum[elv]) + Number(el[elv]) ;
                        });
                    } else {
                        endNodes[dyId].sum  = Number(endNodes[dyId].sum)+ Number(el[this.myConfig.dynameicColumnConfig.dynameicColumnValue]);
                    }
                });
                let data = [];
                for (let pro in obj) {
                    let tempData = {};
                    Object.assign(tempData, obj[pro].data);
                    let dynamic_sum = 0;
                    for (let pro2 in endNodes) {
                        if (dynameicColumnValue.length > 1) {
                            if (obj[pro].columns[pro2] !== undefined) {
                                dynameicColumnValue.forEach(el => {
                                    let tmpname = endNodes[pro2].name + '_' +el;
                                    tempData[tmpname] = obj[pro].columns[pro2][el];
                                    dynamic_sum = dynamic_sum + Number(tempData[tmpname]);
                                });
                            } else {
                                dynameicColumnValue.forEach(el => {
                                    let tmpname = endNodes[pro2].name + '_' +el;
                                    tempData[tmpname] = 0;
                                    dynamic_sum = dynamic_sum + Number(tempData[tmpname]);
                                });
                            }
                        } else {
                            if (obj[pro].columns[pro2] !== undefined) {
                                tempData[endNodes[pro2].name] = obj[pro].columns[pro2];
                                dynamic_sum = dynamic_sum + Number(tempData[endNodes[pro2].name]);
                            } else {
                                tempData[endNodes[pro2].name] = 0;
                                dynamic_sum = dynamic_sum + Number(tempData[endNodes[pro2].name]);
                            }
                        }
                    }
                    tempData.dynamic_sum = dynamic_sum;
                    data.push(tempData);
                }

                let columnsList = [];
                this.makeDynamicColumnConfig(fatherTemp, 0, '', columnsList, endNodes,dynameicColumnValue,dynameicColumnValueTitle);

                let temp = {};
                if (this.myConfig.dynameicColumnConfig.dynameicColumnSumLable) {
                    temp.label = this.myConfig.dynameicColumnConfig.dynameicColumnSumLable;
                } else {
                    temp.label = '动态合计';
                }
                temp.type='NumberBox';
                temp.contentAlign = 'right';
                temp.summary = true;
                temp.name = 'dynamic_sum';
                let width = this.$Method.getTextWidth(temp.label);
                temp.width = width;
                Object.assign(temp, this.myConfig.dynameicColumnConfig.dynameicColumnValuePro);
                columnsList.push(temp);
                let tableColumns  = this.myConfig.items.concat(columnsList);
                this.dynamicColumnConfig = this.$Method.copy(tableColumns);
                this.initDynamicColumn(tableColumns);
                let total_summary = {};
                let dynamic_sum = 0;
                for (let pro in endNodes) {
                    if (dynameicColumnValue.length > 1) {
                         dynameicColumnValue.forEach(el => {
                            let tmpName =endNodes[pro].name + '_' + el;
                            total_summary[tmpName] =  endNodes[pro].sum[el];
                            dynamic_sum = dynamic_sum + Number(endNodes[pro].sum[el]);
                         });
                     } else {
                        total_summary[endNodes[pro].name] =  endNodes[pro].sum;
                        dynamic_sum = dynamic_sum + Number(endNodes[pro].sum);
                     }
                }
                total_summary.dynamic_sum = dynamic_sum;

                let summaryColumn = [];
                this.summaryColumn.forEach(el => {
                    if (total_summary[el] === undefined) {
                        summaryColumn.push(el);
                    }
                });
                if (summaryColumn.length > 0) {
                    data.forEach(el => {
                        summaryColumn.forEach(el2 => {
                            if (!total_summary[el2]) {
                                total_summary[el2] = 0;
                            }
                            total_summary[el2] = total_summary[el2] + Number(el[el2]);
                        });
                    });
                }
                this.data = data;
                this.tempData = this.$Method.copy(data);
                this.total_summary = Object.assign({}, {}, total_summary);
                if (!this.myConfig.showSummary) {
                    Object.assign(this.myConfig,{'showSummary':true});
                }
            } else {
                if (this.myConfig.showSummary) {
                    Object.assign(this.myConfig,{'showSummary':false});
                }
            }
        },
        initDynamicColumn(tableColumns) {
            let newRow = {};
            let summaryColumn = [];
            let columns = [];
            this.initCheckColumn(columns);
            this.initOperColumn(columns);
            this.initIndexColumn(columns);
            const length = tableColumns.length;
            for (let i = 0; i < length; i++) {
                if (tableColumns[i].visible !== false) {
                    //this.setColumn(i);
                    // 添加复杂列项的支持
                    this.initCommonColumn(tableColumns[i],columns,summaryColumn,newRow);
                } else {
                    if (tableColumns[i].defaultValue !== undefined) {
                        if (tableColumns[i].name) {
                            newRow[tableColumns[i].name] = tableColumns[i].defaultValue;
                        }
                        if (tableColumns[i].sname) {
                            newRow[tableColumns[i].sname] = tableColumns[i].defaultValue;
                        }
                        if (tableColumns[i].ename) {
                            newRow[tableColumns[i].ename] = tableColumns[i].defaultValue;
                        }
                    }
                }
            }
            this.total_summary = {};
            this.newRow = deepCopy(newRow);
            summaryColumn.push('dynamic_sum');
            this.summaryColumn = deepCopy(summaryColumn);
            this.tableColumns = deepCopy(columns);
            let soltTableColumns = [];
            this.getSoltTableColumns(columns,soltTableColumns);
            this.soltTableColumns = soltTableColumns;
            this.dynamicColumnItems = tableColumns;
        },
        makeDynamicColumnConfig (fatherTemp, index, id, items, endNodes,dynameicColumnValue,dynameicColumnValueTitle) {
            let fahter = fatherTemp[index];
            if (index === fatherTemp.length -1) {
                for (let pro in fahter) {
                    if (pro === 'name') {
                        continue;
                    }
                    let temp = {};
                    temp.label = fahter[pro].label;
                    if (dynameicColumnValue.length > 1) {
                        temp.align = 'center';
                        temp.children = [];
                        dynameicColumnValue.forEach((el,index) => {
                            let temp2 = {};
                            temp2.type='NumberBox';
                            temp2.align = 'center';
                            temp2.contentAlign = 'right';
                            temp2.summary = true;
                            Object.assign(temp2, this.myConfig.dynameicColumnConfig.dynameicColumnValuePro);
                            temp2.label = dynameicColumnValueTitle[index];
                            let width = this.$Method.getTextWidth(temp2.label);
                            temp2.width = width;
                            temp2.name = endNodes[fahter[pro].id].name + '_' + el;
                            temp.children.push(temp2);
                        });
                    } else {
                        temp.type='NumberBox';
                        temp.align = 'center';
                        temp.contentAlign = 'right';
                        temp.summary = true;
                        let width = this.$Method.getTextWidth(temp.label);
                        temp.width = width;
                        if (endNodes[fahter[pro].id]) {
                            temp.name  = endNodes[fahter[pro].id].name;
                        }
                        Object.assign(temp, this.myConfig.dynameicColumnConfig.dynameicColumnValuePro);
                    }

                    if (id) {
                        if (fahter[pro].fatherId === id) {
                            items.push(temp);
                            items.sort((a, b) => {
                                return a > b;
                            });
                        }
                    }  else {
                        items.push(temp);
                        items.sort((a, b) => {
                            return a > b;
                        });
                    }
                }

            } else {
                for (let pro in fahter) {
                    if (pro === 'name') {
                        continue;
                    }
                    let temp = {};
                    temp.label = fahter[pro].label;
                    temp.align = 'center';
                    if (id) {
                        if (fahter[pro].fatherId === id) {
                            temp.children = [];
                            this.makeDynamicColumnConfig(fatherTemp, index+1, pro, temp.children, endNodes,dynameicColumnValue,dynameicColumnValueTitle);
                            items.push(temp);
                            items.sort((a, b) => {
                                return a > b;
                            });
                        }
                    } else {
                        temp.children = [];
                        this.makeDynamicColumnConfig(fatherTemp, index+1, pro, temp.children, endNodes,dynameicColumnValue,dynameicColumnValueTitle);
                        items.push(temp);
                        items.sort((a, b) => {
                            return a > b;
                        });
                    }

                }

            }
        },
        handleSummary({ columns }) {
            let sums = {};
            for (let tmp in this.newRow) {
                sums[tmp]={key:tmp,value:''};
            }
            let index = columns.findIndex(el => el.type === 'index');
            if (index > -1) {
                sums.index = {key:'index',value:''};
            }
            let index2 = columns.findIndex(el => el.type === 'selection');
            if (index2 > -1) {
                sums.selection = {key:'selection',value:''};
            }
            let items = [];
            if (this.myConfig.dynamicColumnFlag) {
                items = this.dynamicColumnItems;
            } else {
                items  = this.config.items;
            }
            for (let pro in this.total_summary) {
                let configItems = {};
                this.findItemByName(items, pro, configItems);
                if (configItems.name) {
                    let tmpValue = this.total_summary[pro];
                    if (configItems.format !== undefined) {
                        tmpValue = this.$Method.formatNumber(tmpValue,configItems.format,configItems.notzero);
                    }
                    sums[pro]={key:pro,value:tmpValue};
                }
            }
            let firstkey = this.findFirst(columns);
            sums[firstkey] = {key:firstkey,value:this.myConfig.sumText};
            if (this.myConfig.customSummary){
                return this.myConfig.customSummary(sums);
            } else {
                return sums;
            }
        },
        findFirst(columns) {
            let key = '';
            columns.some(el => {
                if (el.key !== 'selection' && el.key !== 'index' &&  el.key !== 'sumindex') {
                    key = el.name;
                    return true;
                }
            });
            return key;
        },
        findItemByName(items, name, config) {
            if (items instanceof Array) {
                let flag = false;
                items.some(el => {
                    if (el.children && el.children.length > 0) {
                        flag = this.findItemByName(el.children, name, config);
                        if (flag)  {
                            return true;
                        }
                    } else {
                        if (el.name) {
                            if (el.name === name) {
                                Object.assign(config, el);
                                flag = true;
                                return true;
                            }
                        }
                    }
                });
                return flag;
            } else {
                if (items.name) {
                    if (items.name === name) {
                        Object.assign(config, items);
                        return true;
                    }
                }
            }
            return false;
        },
        dynamicExportExcel() {
            let dynameicColumnNames = [];
            if (this.myConfig.dynameicColumnConfig.dynameicColumnName) {
                dynameicColumnNames = this.myConfig.dynameicColumnConfig.dynameicColumnName.split(',');
            }
            let headNum = dynameicColumnNames.length;
            let modulecode = this.$Method.getUrlParam('modulecode');
            if (!modulecode) {
                modulecode = this.$Method.getUrlParam('billmoduleid');
            }
            let fileName = this.$Method.formatDate(new Date(),'yyyyMMddhhmmss') +'(合计' + this.data.length+'条).xlsx';
            if (modulecode) {
                fileName = modulecode + '_' + fileName;
            }
            let tmpData = this.$Method.copy(this.data);
            this.dynamicColumnConfig.forEach(el => {
                if (el.type === 'ComboBox') {
                    let valueField = 'code';
                    let textField  = 'name'
                    if (el.valueField) {
                        valueField = column.valueField;
                    }
                    if (el.textField) {
                        textField = column.textField;
                    }
                    tmpData.forEach(el2 => {
                        if (el2[el.name]) {
                            if (el.data) {
                                let index = el.data.findIndex(el3 => el3[valueField] === el2[el.name]);
                                if (index > -1) {
                                    if (el.codeWithName === false) {
                                        el2[el.name] = el.data[index][textField];
                                    } else {
                                        el2[el.name] = '[' + el.data[index][valueField] + ']' + el.data[index][textField];
                                    }
                                }
                            }
                        }
                    });
                }
            });
            let newConfig = [];
            this.initAsynExportConfig(this.dynamicColumnConfig,'',newConfig);
            this.$Method.exportExcelStyle(newConfig,tmpData,headNum,fileName);
        },
        formatValue(index, column) {
            let value = '';
            let row = this.$Method.copy(this.tempData[index]);
            if (column.name) {
                value = row[column.name];
            }
            let config = column;
            let valueFormat = this.$Method.formatValue(value, row, config);
            let obj = {};
            obj.value = value;
            obj.row = row;
            obj.config = config;
            obj.valueFormat = valueFormat;
            if (column.formatValue) {
                return column.formatValue(obj);
            } else if (this.myConfig.formatValue) {
                return this.myConfig.formatValue(obj);
            } else {
                return valueFormat;
            }
        },
        formatMulValue(index, column) {
            let value = '';
            let row = this.$Method.copy(this.tempMultiSelectData[index]);
            if (column.name) {
                value = row[column.name];
            }
            let config = column;
            return this.$Method.formatValue(value, row, config);
        },
        setCustomColumn(column) {
            column.slot = column.key;
        },
        onLinkTo(obj) {
            const column = this.findColumnConfig (obj.name,this.myConfig.items);
            this.addRowInfo(obj, column);
            return column.onLinkTo(obj);
        },
        addRowInfo(obj, column) {
            let index = obj.rowIndex;
            obj.rowinfo = {};
            obj.rowinfo.column = column;
            obj.rowinfo.index = index;
            if (index > -1) {
                obj.rowinfo.row = this.data[index];
            }
            let that = this;
            obj.rowinfo.gridObject = that;
        },
        doSumgroups(data,Sumgroups) {
            let tmp = [];
            Sumgroups.forEach(el => {
                if (el.data && el.data.length > 0) {
                    let groupstr = el.group.split(',');
                    let culkey='';
                    let key = '';
                    data.forEach((el2,index) => {
                        key = '';
                        groupstr.forEach(el3 => {
                            key = key + el2[el3];
                        });
                        if (!culkey) {
                            culkey = key;
                        }
                        if (culkey !== key) {
                            let sumdata = el.data.find(el4 => {
                                let key2 = '';
                                groupstr.forEach(el5 => {
                                    key2 = key2 + el4[el5];
                                });
                                return key2 === culkey;
                            });
                            let tmpObj = {};
                            tmpObj.index = index;
                            tmpObj.sum = sumdata;
                            if (el.showgroup) {
                                let showgroup = el.showgroup.split(',');
                                tmpObj.showgroup = showgroup;
                            }
                            tmpObj.group = groupstr;
                            tmp.push(tmpObj);
                            culkey = key;
                        }
                    });
                }
            });
            if (tmp.length > 0) {
                let tmpData = [];
                data.forEach((el,index) => {
                    let sumindex  = index + 1;
                    if (this.myConfig.showPage) {
                        sumindex  = sumindex + (this.myConfig.pageConfig.page_no - 1) * this.myConfig.pageConfig.page_size;
                    }
                    el.sumindex = sumindex + '';
                    let tmpObj = tmp.find(el2 => el2.index === index);
                    if (tmpObj) {
                        if (this.myConfig.customSummaryGroup){
                            tmpObj = this.myConfig.customSummaryGroup(tmpObj);
                        }
                        if (tmpObj.showgroup) {
                            tmpObj.group.forEach(el2 => {
                                let tmpIndex = tmpObj.showgroup.findIndex(el3 => el2 === el3);
                                if (tmpIndex === -1) {
                                    tmpObj.sum[el2] = '';
                                }
                            });
                        }
                        tmpObj.sum.sumindex = '';
                        tmpData.push(tmpObj.sum);
                        tmpData.push(el);
                    } else {
                        tmpData.push(el);
                    }
                });
                return tmpData;
            } else {
                return data;
            }
        }
    },
    mounted () {
        this.observer = elementResizeDetectorMaker();
        if (this.$refs.head) {
            this.observer.listenTo(this.$refs.head, this.setExtraHeight);
        }
        if (this.$refs.page) {
            this.observer.listenTo(this.$refs.page, this.setExtraHeight);
        }
    },
    beforeUnmount() {
        if (this.$refs.head) {
            this.observer.removeListener(this.$refs.head, this.setExtraHeight);
        }
        if (this.$refs.page) {
            this.observer.removeListener(this.$refs.page, this.setExtraHeight);
        }
    }
};
</script>
