
<template>
    <div v-loading="loading" style="position:relative">
        <div style="position:absolute;left:2px;top:0px;z-index:100" v-if="$store.state.superFlag">
            <el-popover placement="bottom-start" width="920" trigger="manual" popper-class="mt100 ml20 bgcolor-blue" 
                :visible-arrow="false" v-model="isColInfoVisible" v-if="isShowColInfo">
                <template >
                    <exTable ref="colTable" :data="colList" :height="400" class="small-table-class" v-if="colList.length>0">
                        <exColumn width="220" label="字段名称" prop="_fullLabel" align="right" fixed="left"></exColumn>
                        <exColumn width="160" label="字段编码" prop="__prop"></exColumn>
                        <exColumn width="80" label="是否显示">
                            <template slot-scope="s">
                                <exSwitch v-model="s.row.__show" size="mini" @change="onChangeColShow(s.row)"></exSwitch>
                            </template>
                        </exColumn>
                        <exColumn width="80" label="默认设置">
                            <template slot-scope="s">
                                <exSwitch v-model="s.row.__defShow" size="mini" :disabled="true"></exSwitch>
                            </template>
                        </exColumn>
                        <exColumn width="80" label="仅自营角色显示">
                            <template slot-scope="s">
                                <exSwitch v-model="s.row.__selfShow" size="mini" @change="onChangeColShow(s.row)"></exSwitch>
                            </template>
                        </exColumn>
                        <exColumn width="120" label="宽度调整">
                            <template slot-scope="s">
                                <el-input-number v-model="s.row.__exWidth" :step="5" :max="1000" size="mini"></el-input-number>
                            </template>
                        </exColumn>

                        
                        <template v-if="showCodeConfig">
                            <exColumn width="90" :label="item.name" v-for="(item,idx) in envList" :key="idx">
                                <template slot-scope="s">
                                    <exSwitch v-model="s.row.envFlag[item.flag]"></exSwitch>
                                </template>
                            </exColumn>
                        </template>
                        <exColumn prop="propDesc" width="130" label="字段说明"></exColumn>
                    </exTable>
                    <el-row style="padding-left:20px;margin-top:10px;">
                        <el-button type="success" size="mini" @click="savePageSetting">保存配置</el-button>
                        <el-button type="primary" size="mini" @click="selAllCol" class="ml20">全选</el-button>
                        <!-- <el-button type="primary" size="mini" @click="cloneCurSetting" class="ml20">获取当前配置</el-button> -->
                        <el-button type="primary" size="mini" @click="changeDefSetting" class="ml20">显示默认配置</el-button>
                        <el-button type="primary" size="mini" @click="checkHideCol" class="ml20">检查非空隐藏列</el-button>
                        <el-button type="primary" size="mini" @click="clearColWidth" class="ml20">清空列宽设置</el-button>
                        <el-button type="primary" size="mini" @click="reLoadTable" class="ml20">应用</el-button>
                        <el-button type="warning" size="mini" @click="isColInfoVisible = ! isColInfoVisible" class="ml20">隐藏面板</el-button>
                    </el-row>
                </template>
                <i class="el-icon-s-operation red" slot="reference" @click = " isColInfoVisible = ! isColInfoVisible "></i>
            </el-popover>
            <i v-else style="display:inline-block;width:15px;height:15px;border:0px red solid;" @click="clickCount"></i>

        </div>
        <exTable ref="curTable" v-if="isShowTable" v-bind="$attrs" v-on="$listeners" :data="filterList" :diffHeight="diffHeight"  @sort-change="handleSortChange"
                :summary-method="getSummaries" class="small-table-class"
            >
            <el-table-column type="index" v-if="tableCfg.showIndex"  :index="indexMethod" width="60"></el-table-column>
            <slot name="before"></slot>
            <exColumn v-for="(col,idx) in cols" :key="'col1'+idx" v-bind="col" @quickModify="quickModify"></exColumn>
            <slot></slot>
            <exColumn v-for="(col,idx) in cols2" :key="'col2'+idx" v-bind="col" @quickModify="quickModify"></exColumn>
            <slot name="after"></slot>
            <el-table-column prop="__toper" :label="tableCfg.operColLabel || labelCfg.operColLabel || '操作'" v-if="tableCfg.canModify || tableCfg.btns.length>0 || tableCfg.createUrl || tableCfg.deleteUrl" min-width="125" :width="isMobile?'80px':btnsWidth" :fixed="tableCfg.btnFixed">
                <template v-slot="s">
                    <template v-if="tableCfg.canModify || s.row.isNew">
                        <span class="btnspan" v-if="!s.row.editing && !s.row.isNew">
                            <template v-if="(!tableCfg.isShowModify || tableCfg.isShowModify(s))">
                                <el-button type="text" @click="doEditing(s.row)" size="mini">{{tableCfg.editBtnName || labelCfg.editBtnName || '编辑'}}</el-button>
                            </template>
                        </span>
                        <template v-else>
                            <span class="btnspan"><el-button type="text" @click="saveRow(s)" size="mini">{{tableCfg.saveBtnName || labelCfg.saveBtnName || '保存'}}</el-button></span>
                            <span class="btnspan"><el-button type="text" @click="cancelRow(s)" size="mini">{{labelCfg.cancelBtnName || '取消'}}</el-button></span>
                        </template>
                    </template>
                    <template v-if="tableCfg.btns && tableCfg.btns.length>0 && !s.row.editing">
                        <span v-for="(btn,idx) in tableCfg.btns" :key="idx" class="btnspan">
                            <el-button type="text" @click="btn.handle(s)" size="mini" v-if="!btn.isShow || btn.isShow(s)">{{getBtnName(btn)}}</el-button>
                        </span>
                    </template>
                    <template v-if="tableCfg.deleteUrl  && !s.row.editing && (!tableCfg.isShowDel || tableCfg.isShowDel(s))">
                        <el-button type="text" @click="deleteRow(s)" size="mini">{{ labelCfg.deleteBtnName || '删除'}}</el-button>
                    </template>
                </template>
            </el-table-column>
        </exTable>
        
        <el-pagination v-if="tableCfg.usePage" ref="pageEl"
            @current-change="changepage"
            @size-change="handleSizeChange"
            :current-page="pinfo.page"
            :page-sizes="[10, 15, 20, 30, 50, 100, 200]"
            :page-size="pinfo.size"
            :layout="layout || 'total, sizes, prev, pager, next, jumper'"
            :total="pinfo.total">
        </el-pagination>
    </div>
</template>


<script>

import validUtil from '../lib/valid.vue';
import exSwitch from './exSwitch.vue';

export default {
  components: { exSwitch },
    props:["cfg","exData","defPageSize","qryArgs","layout","autoQry","tableLabelCfg","isCk"],
    
    inject: ['__menuId',"__menuName"],
    data() {
        var pinfo = {
                size: this.defPageSize || 20,
                total : 0,
                page : 1,
            };
        if(this.cfg) Object.assign(pinfo,this.cfg.pinfo)
        var sumText = "合计";
        if(this.$store && this.$store.state.lang){
            var tempcfg = {};
            if(this.tableLabelCfg){
                tempcfg = this.tableLabelCfg;
            }else if(this.globalLyExFnCfg){
                tempcfg = this.globalLyExFnCfg["tableLabelCfg"+this.$store.state.lang] || this.globalLyExFnCfg.tableLabelCfg || {};
            }
            sumText = tempcfg.sumText || sumText;
        }
        return {
            isShowTable : true,
            isShowColInfo : false,
            isColInfoVisible : false,
            loading : false,
            curAttrs: {},
            dataList : this.exData || [],
            useServerSort : false,  //服务端排序
            sortType: "",
            sortBy: "",
            pinfo:pinfo,
            defTableCfg: {
                tableId : "", //表格的唯一标识,不同页面不能重复
                sumText : sumText,
                usePage : false,
                localPage : false,
                canModify: false,
                refreshAfterCommit: false,
                noRefreshAfterAdd: false,
                autoSum : false, //自动进行 行合计
                                //在column中配置 autoSum:{totalCol:"costTotal",exCol:[],sumCols:[]} totalCol:合计数据目标列,exCol:排除不合计的列,sumCols:要合计的列
                // setInfoSpan(list){},  //设置分页区展示的额外信息
                dataNode : ["pageInfo"], //数据节点
                //defBean: {}, //默认值设置
                // sortNotToLine: false ,  排序字段不转下划线
                // sumNode : ["pageInfo","total"], //汇总数据节点
                // queryUrl : `${config.api}/game/gOperateEnslotActivity/list`,
                // createUrl : `${config.api}/game/gOperateEnslotActivity/updateEnslotActivity`,
                // updateUrl : `${config.api}/game/gOperateEnslotActivity/updateEnslotActivity`,
                // deleteUrl : `${config.api}/game/gOperateEnslotActivity/updateEnslotActivity`,
                // isShowDel : (s) =>{},
                // saveRow:({$index,row})=>{
                // },
                // tranData:(retdata)=>{

                // },
                // tranDataList:(list)=>{

                // },
                // tranDataItem:(item,idx)=>{

                // },
                // tranCommitData:(data)=>{  //转换提交之前的数据

                // },
                // dataFilter:(list)=>{} //数据过滤
                // btnswidth: 100,  //按钮区宽度
                btns:[ ],
                columns: [
                    // {prop:"sysId",label:"标识",width:100,
                    // tips:"提示测试",  表头提示文本
                    // sumType:"add", 增加合计方式
                    // rateBy : "", 增加占比计算
                    // formatter(row,col,val,idx){ return `<span class="red">${val}</span>(${idx})`} //增加数据格式化
                    //    ,link:(row)=>{  return { code: 66, name: "xxxx", initParam: row } },link1:{code:66,name:"用户活动"}}, //增加链接
                    // {prop:"activityName",label:"活动名称",width:"",
                    // edittype:"input",  编辑类型
                    // quickMode:true},  快捷编辑
                    // {prop:"activityGroupId",label:"活动组别标识",width:"",edittype:"number"},
                    // {prop:"activityTime",label:"活动持续时间(分)",width:"",edittype:"number"},
                    // {prop:"status",label:"状态",width:"",dictCode:"openStatus",edittype:"radio"},
                    // {prop:"openTime",label:"每天开启的时间",width:195,edittype:"datetime"},
                    // {prop:"updateTime",label:"更新时间",width:150},
                    // {prop:"createTime",label:"创建时间",width:150},
                ],
                columns2:[],
                validCfg: {
                    // activityGroupId: [ "required","aboveZero(0)" ],
                    // activityTime : ["required","aboveZero(1)"],
                    // status : ["required"],
                    // openTime : ["required"],
                }
            },
            colList:[],
            groupKey: "web",
            keyName : "tableCol",
            colConfig : {},
            showCodeConfig : false,
            goldFlagList : [],
        }
    },
    mounted() {
        this.curAttrs = this.$attrs;
        this.setColList()
        if(this.dataList.length>0){
            this.tranDataGoldBet(this.dataList)
        }
        this.getPageSetting();
        
        var methods = ["clearSelection","toggleRowSelection","toggleAllSelection","toggleRowExpansion",
            "setCurrentRow","clearSort","clearFilter","doLayout","sort"];
        methods.map((item)=>{
            // this[item] = this.$refs.curTable[item];
            this[item] = (a,b,c,d,e,f,g)=>{
                this.$refs.curTable[item](a,b,c,d,e,f,g)
            };
        });
        this.$nextTick(()=>{
            if(this.tableCfg.usePage && this.tableCfg.setInfoSpan){
                var pageel = this.$refs.pageEl.$el;
                pageel.insertAdjacentHTML("beforeend","<div class='infospan'></div>")
            }
            if(this.tableCfg.autoQry){
                this.reQuery({noInitPage:true});
            }
        });
    },
    computed: {
        labelCfg(){
            var cfg = {};
            if(this.tableLabelCfg){
                cfg = this.tableLabelCfg;
            }else if(this.globalLyExFnCfg){
                if(this.$store && this.$store.state.lang){
                    cfg = this.globalLyExFnCfg["tableLabelCfg"+this.$store.state.lang] || this.globalLyExFnCfg.tableLabelCfg || {};
                }else{
                    cfg = this.globalLyExFnCfg.tableLabelCfg || {};
                }
            }
            return cfg;
        },
        cols(){
            if(this.tableCfg){
                return this.tableCfg.columns.map(col => {
                    // 如果 col 对象中存在 fixed 属性,则将其删除
                    const { fixed, ...rest } = col;
                    return this.isMobile?rest:col;
                });
            }
            return [];
        },
        cols2(){
            if(this.tableCfg && this.tableCfg.columns2){
                return this.tableCfg.columns2;
            }
            return [];
        },
        tableCfg(){
            return this.extend({},this.defTableCfg,this.cfg);
        },
        qryParam(){
            return this.qryArgs;
        },
        diffHeight(){
            if(this.curAttrs.diffHeight){
                return  this.curAttrs.diffHeight 
            }else if(this.tableCfg.usePage){
                return 50
            }else {
                return ""
            }
        },
        btnsWidth(){
            return this.tableCfg.btnsWidth
        },
        filterList(){
            var list = this.dataList;
            if(this.tableCfg.usePage && this.tableCfg.localPage && this.dataList){
                var min = this.pinfo.size * (this.pinfo.page-1);
                var max = this.pinfo.size * this.pinfo.page;

                if(this.tableCfg.localPage && this.sortType){
                    list = list.sort((a,b)=>{
                        var val1 = a[this.sortBy], val2 = b[this.sortBy];
                        if(val1 == val2) return 0
                        if(this.sortType=="asc"){
                            return val1>val2? 1:-1
                        }else{
                            return val1>val2? -1:1
                        }
                    });
                }
                    
                list = list.filter((item,idx)=>{
                    return (idx>=min && idx<max)
                });
            }else if(this.tableCfg.dataFilter){
                list= this.tableCfg.dataFilter.call(this.$parent,this.dataList);
            }
            this.setInfoSpan(list);
            return list;
        },
        isMobile() {
            return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
        }
    },
    watch: {
        exData(newdata){
            this.tranDataGoldBet(newdata)
            this.dataList = newdata;
            if(this.tableCfg.autoSum){
                this.setAutoSum(this.dataList)
            }
            this.$nextTick(()=>{
                if(this.$refs.curTable.doLayout){
                    this.$refs.curTable.doLayout();
                }
            })
        }
    },

    methods: {
        getBtnName(btn){
            if(this.$store && this.$store.state.lang){
                return  btn["name"+this.$store.state.lang] || btn.name;
            }else{
                return btn.name;
            }
        },
        setColWidth(){
            if(!this.__menuId || !this.getSetting){
                return;
            }
            if(!this.$store.state.envCfg){
                return;
            }
            if(!this.isShowColInfo) return;
            for(var i=0;i<this.colList.length;i++){
                var colrow = this.colList[i];
                if(colrow.__preWidth)  colrow.width = (colrow.__preWidth||0) + colrow.__exWidth;
            }

        },
        clearColWidth(){
            for(var i=0;i<this.colList.length;i++){
                var colrow = this.colList[i];
                colrow.__exWidth = 0;
                if(colrow.__preWidth) colrow.width =  (colrow.__preWidth||0) + colrow.__exWidth;
            }
        },
        reLoadTable(){
            this.setParentNodeShow();
            this.setColWidth();
            this.isShowTable = false;
            this.$nextTick(()=>{
                this.isShowTable = true;
                this.$nextTick(()=>{
                    this.reRender();
                })
            })
            // this.tableCfg.columns.push({})
            // this.tableCfg.columns.pop()
        },
        checkHideCol(){
            var msg = [];
            this.colList.map(item=>{
                if(!item.__show){
                    for(var i=0;i<this.dataList.length;i++){
                        let row = this.dataList[i];
                        if(row[item.prop]){
                            msg.push(`${item._fullLabel}(${item.__prop})`);
                            break;
                        }
                    }
                }
            })
            if(msg.length>0){
                msg.push("状态为隐藏,且存在非空数据");
                this.$message.warning(msg.join(","));
            }else{
                this.$message.info("不存在非空数据的隐藏列");
            }
        },
        onChangeColShow(row){
            if(this.setEnvFlagByRoleFlag(row)) return;
            var curEnvFlag = this.$store.state.envCfg.envFlag;
            row.envFlag[curEnvFlag] = row.__show;
        },
        setEnvFlagByRoleFlag(row){
            var curEnvFlag = this.$store.state.envCfg.envFlag;
            if(row.__selfShow && !this.$store.state.roleFlag){
                row.envFlag[curEnvFlag] = false;
                return true;
            }
            return false;
        },
        changeDefSetting(){
            this.showCodeConfig = ! this.showCodeConfig;
            this.$nextTick(()=>{
                this.$refs.colTable.doLayout();
            })
        },
        cloneCurSetting(){
            var curEnvFlag = this.$store.state.envCfg.envFlag;
            this.colList.map(item=>{
                if(item.envFlag && !item.envFlag[curEnvFlag]){
                    item.__show = false;
                }else{
                    item.__show = true;
                }
            })
            this.$refs.colTable.doLayout();
        },
        selAllCol(){
            this.colList.map(item=>{
                item.__show = true;
            })
            this.$refs.colTable.doLayout();
        },
        setParentNodeShow(){ //子级节点都被隐藏了,父级也要隐藏
            if(this.tableCfg && this.tableCfg.columns){
                this.getParentNodeShow(this.tableCfg.columns)
            }
            if(this.tableCfg && this.tableCfg.columns2){
                this.getParentNodeShow(this.tableCfg.columns2)
            }
        },
        getParentNodeShow(colList){
            if(!this.$store.state.envCfg){
                return true;
            }
            var curEnvFlag = this.$store.state.envCfg.envFlag;
            var isShow = false;
            colList.map(item=>{
                if(item.columns && item.columns.length>0){
                    if(typeof(item.isShow)=="function") return true;
                    var tmp = this.getParentNodeShow(item.columns)
                    if(tmp){
                        isShow = true;
                        item.isShow = undefined;
                    }else{
                        item.isShow = false;
                    }
                }else{
                    if(!item.envFlag && item.isShow!==false){
                        isShow = true;
                    }else if(item.envFlag && item.envFlag[curEnvFlag]){
                        isShow = true;
                    }
                }
            })
            return isShow;
        },
        getPageSetting(){
            if(!this.__menuId || !this.getSetting){
                return;
            }
            if(!this.$store.state.envCfg){
                return;
            }
            var curEnvFlag = this.$store.state.envCfg.envFlag;
            this.getSetting.call(this,this.groupKey,this.keyName,this.__menuId,(list)=>{
                if(list.length>0){
                    this.isShowColInfo = true;
                    this.colConfig = list[0];
                    var tableconfig = JSON.parse(this.colConfig.content);
                    var tmpmap = {};
                    tableconfig.col.map((item)=>{
                        tmpmap[item.code] = item;
                    })
                    for(var i=0;i<this.colList.length;i++){
                        var colrow = this.colList[i];
                        var cfg = tmpmap[colrow.__prop];
                        if(cfg){
                            colrow.__show = cfg.isShow;
                            colrow.__selfShow = cfg.isSelfShow;
                            colrow.__exWidth = cfg.exWidth;
                            colrow.extips = cfg.tips;

                            if(colrow.__preWidth) colrow.width=  (colrow.__preWidth||0) + colrow.__exWidth;
                            colrow.envFlag[curEnvFlag] = colrow.__show;
                            this.setEnvFlagByRoleFlag(colrow)
                        }
                    }
                }else{

                }
                this.reLoadTable();
            });
        },
        savePageSetting(){
            if(!this.__menuId) return;
            if(!this.saveSetting) return;
            var tableconfig = {
                col:[],
            }
            this.colList.map(item=>{
                if(item.__show!=item.__defShow || item.__selfShow || item.__exWidth){
                    var row = {
                        code: item.__prop,
                        name : item._fullLabel,
                        isShow : item.__show?true:false,
                        isSelfShow : item.__selfShow?true:false,
                        exWidth : item.__exWidth || 0,
                        tips : item.extips || "",
                    }
                    tableconfig.col.push(row);
                }
            })
            this.saveSetting.call(this,
                {
                    id:this.colConfig.id||"",
                    groupKey:this.groupKey,
                    keyName:this.keyName,
                    key1:this.__menuId,
                    content : JSON.stringify(tableconfig),
                    remark:this.__menuName
                },(data)=>{
                    if(data && data.id){
                        this.colConfig.id = data.id;
                    }
                    this.$message.success("配置保存成功");
                    this.reLoadTable();
                });
        },
        setColList(){
            var list = [];
            this.goldFlagList = [];
            if(this.tableCfg && this.tableCfg.columns){
                this.getColList(this.tableCfg.columns,list)
            }
            if(this.tableCfg && this.tableCfg.columns2){
                this.getColList(this.tableCfg.columns2,list)
            }
            this.setParentNodeShow();
            this.$set(this,"colList",list);
            // this.colList = list;
        },
        getColList(colList,list,preName){
            if(!this.$store.state.envCfg) return;
            var curEnvFlag = this.$store.state.envCfg.envFlag;
            var defEnvFlag = {};
            var envlist = [];
            try{
                envlist = this.envlist || [];
                envlist.map(item=>{
                    defEnvFlag[item.flag] = true;
                })
            }catch(ex){

            }
            colList.map(item=>{
                this.$set(item,"__exWidth",0)
                if(!isNaN(item.width)){
                    item.__preWidth = item.width;
                }
                if(item.isShow===false){
                    if(item.goldFlag){
                        this.goldFlagList.push(item);
                    }
                    return;
                }
                item.label = this.$dict.tranByPubMap(item.label)
                var label = preName?preName+"-"+item.label:item.label;
                if(item.columns && item.columns.length>0){
                    this.getColList(item.columns,list,label)
                }else if(item.prop){
                    if(!item.envFlag){
                        item.envFlag=JSON.parse(JSON.stringify(defEnvFlag));
                    }else{
                        this.isShowColInfo = true;
                        envlist.map(envitem=>{
                            if(item.envFlag[envitem.flag]==undefined){
                                item.envFlag[envitem.flag]=item.envFlag.def || false;
                            }
                        })
                    }
                    if(item.goldFlag){
                        this.goldFlagList.push(item);
                    }
                    item.__prop = item.propName || item.prop;
                    item._fullLabel=label;
                    item.__show = item.envFlag[curEnvFlag];
                    item.__defShow = item.__show;
                    item.extips = "";
                    list.push(item)
                }
            })
        },
        setInfoSpan(list){
            if(!this.tableCfg.setInfoSpan) return;
            this.$nextTick(()=>{
                var infoSpan = this.getInfoSpan();
                if(infoSpan){
                    infoSpan.innerHTML="";
                    var cont = this.tableCfg.setInfoSpan.call(this.$parent,list,this.dataList);
                    if(cont) infoSpan.innerHTML=cont;
                }
            })
        },
        getCurDataList(){
            return this.filterList
        },
        indexMethod(index){
            return (this.pinfo.page-1)*this.pinfo.size+index+1;
        },
        getColnameMap(){
            if(this.colnameMap) return this.colnameMap;
            this.colnameMap = {};
            this.eachColumn(this.tableCfg.columns,(item)=>{
                this.colnameMap[item.prop] = item.label;
            });
            this.eachColumn(this.tableCfg.columns2,(item)=>{
                this.colnameMap[item.prop] = item.label;
            });
            return this.colnameMap;
        },
        getColMap(){
            if(this.colMap) return this.colMap;
            this.colMap = {};
            this.eachColumn(this.tableCfg.columns,(item)=>{
                this.colMap[item.prop] = item;
            });
            this.eachColumn(this.tableCfg.columns2,(item)=>{
                this.colMap[item.prop] = item;
            });
            return this.colMap;
        },
        eachColumn(list,cb){
            if(list && list.map){
                list.map(item=>{
                    if(cb && item.prop){
                        cb(item);
                    }
                    if(item.columns){
                        this.eachColumn(item.columns,cb);
                    }
                })
            }
        },
        quickModify(scope,args){    //快捷修改
            this.saveRow(scope,true,args)
        },
        addNewRecord(newitem,idx){
            if(newitem){
                if(!this.tableCfg.noRefreshAfterAdd){
                    var newrow = this.dataList.find(a=>{return a.isNew==true})
                    if(newrow){
                        this.$message.error(this.labelCfg.canNotAddMult ||"不能同时添加多条");
                        return;
                    }
                }
            }else{
                if(!this.tableCfg.noRefreshAfterAdd){
                    if(this.dataList.length>0 && this.dataList[0].isNew){
                        this.$message.error(this.labelCfg.canNotAddMult ||"不能同时添加多条");
                        return;
                    }
                }
                newitem = this.tableCfg.defBean;
                if(newitem){
                    newitem = JSON.parse(JSON.stringify(newitem))
                }else{
                    newitem = {};
                }
            }
            newitem.isNew = true;
            newitem.editing = true;
            if(idx){
                this.dataList.splice(idx,0,newitem)
            }else{
                this.dataList.splice(0,0,newitem)
            }
        },
        doEditing(row){
            if(this.tableCfg.onEditing){
                var is_continue = this.tableCfg.onEditing.call(this.$parent,row);
                if(!is_continue) return;
            }
            
            delete row.__bakData;
            delete row.editing;
            row.__bakData = JSON.parse(JSON.stringify(row));
            row.editing=true;
            this.reRender();
        },
        saveRow(scope,noConfim,args){  //点击保存按钮
            var row = scope.row;
            args = args || {};
            var tempValidCfg = null;
            if(this.$store.state.envCfg){
                tempValidCfg = this.tableCfg["validCfg"+this.$store.state.envCfg.envFlag];
                if(!tempValidCfg){
                    tempValidCfg = this.tableCfg.validCfg;
                }
            }
            if(tempValidCfg){
                var validData = row;
                if(this.$store.state.envCfg && this.$store.state.envCfg.goldBet!=1){
                    validData = JSON.parse(JSON.stringify(row));
                    this.goldFlagList.map(item=>{
                        var val = validData[item.prop];
                        if(val && this.reTranGold){
                            validData[item.prop] = this.reTranGold(val)
                        }
                    })
                }

                var errMsg = validUtil.validObj(validData,tempValidCfg,this.getColnameMap());
                if(errMsg){
                    this.$message.error(errMsg);
                    return;
                }
            }
            if(row.isNew && this.tableCfg.createUrl){
                this.commitEditRow(row,noConfim);
            }else if(args.saveFun){//单列自定义的修改函数
                args.saveFun(row,noConfim,scope);
            }else if(args.updateUrl){//单列自定义的修改地址
                this.commitEditRow(row,noConfim,args);
            }else if(this.tableCfg.updateUrl){
                this.commitEditRow(row,noConfim);
            }else if(this.tableCfg.saveRow){
                this.tableCfg.saveRow.call(this.$parent,scope,noConfim,()=>{
                    this.updateRow(scope.row);
                })
            }else{
                this.updateRow(scope.row);
            }
        },
        updateRow(row){
            delete row.editing;
            delete row.isNew;
            this.reRender();
        },
        cancelRow({row,$index}){
            if(row.isNew){
                this.dataList.splice($index,1)
                return;
            }
            if(row.__bakData){
                var bak = row.__bakData;
                for(var key in bak){
                    row[key] = bak[key];
                }
            }
            delete row.__bakData;
            delete row.editing;
            this.reRender();
        },
        reRender(){
            var that = this;
            setTimeout(function(){
                that.dataList.push({});
                that.dataList.pop();
                // that.dataList.splice(that.dataList.length-1,1)
            },100);
        },
        changepage(page){
            this.pinfo.page = page;
            if(this.tableCfg.localPage){

            }else{
                if(this.tableCfg.onPageChange){
                    var pinfo = JSON.parse(JSON.stringify(this.pinfo))
                    if(this.tableCfg.onPageChange(pinfo)){
                        this.getDataList(page);
                    }
                }else{
                    this.getDataList(page);
                }
            }
        },
        setPageSize(val){
            this.pinfo.size = val;
        },
        handleSizeChange(val){
            this.pinfo.size = val;
            if(this.tableCfg.localPage){

            }else{
                if(this.tableCfg.onPageChange){
                    var pinfo = JSON.parse(JSON.stringify(this.pinfo))
                    if(this.tableCfg.onPageChange(pinfo)){
                        this.getDataList();
                    }
                }else{
                    this.getDataList();
                }
            }
        },
        clear(){
            if(this.tableCfg.usePage){
                this.pinfo.page = 1;
                this.pinfo.total = 0;
            }
            this.dataList = [];
            this.sumInfo = null;
        },
        reQuery(param){
            param = param || {};
            if(this.tableCfg.usePage && !param.noInitPage){
                this.pinfo.page = 1;
                this.pinfo.total = 0;
            }
            if(this.tableCfg.useServerSort && !param.noClearSort){
                this.sortType = "";
                this.sortBy = "";
                this.$refs.curTable.clearSort();
            }
            this.$nextTick(()=>{
                this.getColMap();
                this.getColnameMap();
                this.getDataList();
            })
        },
        getInfoSpan(){
            if(this.tableCfg.usePage){
                var infospanEl = this.$refs.pageEl.$el.querySelectorAll(".infospan");
                if(infospanEl.length>0){
                    return infospanEl[0];
                }
            }
            return null;
        },
        getDataList(page) {
            if(!page){
              this.pinfo.page = 1
            }
            this.dataList = [];
            this.sumInfo = null;
            this.$emit("getDataList",this.pinfo);
            if(!this.tableCfg.queryUrl) return;
            this.loading = true;
            var args= (this.tableCfg.queryUrl.indexOf("?")!=-1) ? "&" : "?&";
            if(this.tableCfg.usePage){
                args += `page=${this.pinfo.page}&size=${this.pinfo.size}&sortType=${this.sortType}&sortBy=${this.sortBy}`;
            }
            if(this.qryParam){
                args+=this.qryParam;
            }
            while(args!=args.replace(/&[a-zA-Z0-9_]+=(&|$)/g,"&")){
                args = args.replace(/&[a-zA-Z0-9_]+=(&|$)/g,"&");
            }
            let url = this.tableCfg.queryUrl;
            if(this.isCk && this.isCk == 1){
                url = url.replace(/\/fjtx\//g, '/busi/');
            }
            this.$axios.get(url + args)
            .then((res) => {
                this.loading = false;
                if (res.data.code == 200) {

                    try {
                        if(this.tableCfg.tranData){ //将返回的原始数据回传
                            var tmpdata = this.tableCfg.tranData.call(this.$parent,res.data.data,this.pinfo)
                            if(tmpdata){
                                res.data.data = tmpdata;
                            }
                        }
                    }catch(ex){
                        console.log(ex)
                        this.$message.error("exPubTable.getDataList.tranData Error / "+ex.message);
                    }
                    var retdata = res.data.data;

                    if(this.tableCfg.sumNode){
                        var sumInfo = retdata;
                        this.tableCfg.sumNode.map(item=>{
                            if(sumInfo && sumInfo[item]){
                                sumInfo = sumInfo[item]
                            }
                        })
                        if(sumInfo){
                            
                            this.tranDataGoldBet([sumInfo]);
                            this.sumInfo = sumInfo;
                        }
                    }
                    
                    this.tableCfg.dataNode.map((item)=>{
                        if(retdata && retdata[item]){
                            retdata = retdata[item]
                        }
                    });

                    if(this.tableCfg.usePage && !this.tableCfg.localPage){
                        this.dataList = retdata.records;
                        if(retdata.total) this.pinfo.total = retdata.total;
                        else this.pinfo.total = this.dataList.length;
                    }else {
                        if(retdata.records){
                            this.dataList = retdata.records;
                        }else {
                            this.dataList = retdata;
                        }
                        if(this.tableCfg.localPage){
                            this.pinfo.total = this.dataList.length;
                        }
                    }
                    try {
                        if(this.tableCfg.autoSum){
                            this.setAutoSum(this.dataList)
                        }
                        if(this.tableCfg.tranDataList){
                            this.tableCfg.tranDataList.call(this.$parent,this.dataList)
                        }
                        if(this.tableCfg.tranDataItem){
                            this.dataList.map((item,idx)=>{
                                this.tableCfg.tranDataItem.call(this.$parent,item,idx)
                            });
                        }
                        this.tranDataGoldBet(this.dataList);
                    }catch(ex){
                        console.log(ex)
                        this.$message.error("exPubTable.getDataList.tranData Error / "+ex.message);
                    }
                    this.$nextTick(()=>{
                        if(this.$refs.curTable.doLayout){
                            this.$refs.curTable.doLayout();
                        }
                    })
                    this.$emit("afterQuery",true);
                } else {
                    this.$message.error(res.data.message);
                    this.$emit("afterQuery",false);
                }
            }).catch(err=>{
                this.loading = false;
                this.$emit("afterQuery",false);
            })

        },
        tranDataGoldBet(list){
            if(this.$store.state.envCfg && this.$store.state.envCfg.goldBet!=1){
                list.map((row,idx)=>{
                    if(row.__goldTraned) return;
                    this.goldFlagList.map(item=>{
                        var val = row[item.prop];
                        if(val && this.tranGold){
                            row[item.prop] = this.tranGold(val);
                        }
                    });
                    row.__goldTraned = true;
                })
            }
        },
        setAutoSum(list,isSum){
            list.map(item=>{
                this.setAutoSumByCol(item,this.cols,isSum);
                this.setAutoSumByCol(item,this.cols2,isSum);
            })
        },
        setAutoSumByCol(data,cols,isSum){
            cols.map((col)=>{
                if(col.columns){
                    this.setAutoSumByCol(data,col.columns,isSum);
                }
                if(col.autoSum){
                    if(col.autoSum.totalCol){
                        if(isSum && col.autoSum.totalCol) return;  //已经有值了就不需要再计算
                        var total = 0;
                        if(col.columns){
                            this.eachColumn(col.columns,(item)=>{
                                if(col.autoSum.exCol && col.autoSum.exCol.findIndex(exitem=>{return item.prop==exitem})!=-1){
                                    return;
                                }
                                total += data[item.prop] || 0;
                            });
                        }
                        data[col.autoSum.totalCol] = total;
                    }else if(col.autoSum.sumCols){
                        if(isSum && data[col.prop]) return;  //已经有值了就不需要再计算(sumType计算)
                        var total = 0;
                        var sumColsTips = "";
                        col.autoSum.sumCols.map(item=>{
                            total += data[item] || 0;
                            if(this.tableCfg.sumColsTips && data[item]){
                                sumColsTips += `field: ${item} type:sum val: ${data[item]}\n`;
                            }
                        })
                        
                        if(col.autoSum.subCols){
                            col.autoSum.subCols.map(item=>{
                                total -= data[item] || 0;
                                if(this.tableCfg.sumColsTips && data[item]){
                                    sumColsTips += `field: ${item} type:sub val: ${data[item]}\n`;
                                }
                            })
                        }
                        data[col.prop] = total;
                        if(sumColsTips) data[col.prop+"__Tips"] = sumColsTips;
                    }
                }
            })
        },
        commitEditRow(row,noConfim,args){
            var commitdata = JSON.parse(JSON.stringify(row));
            if(this.tableCfg.checkCommitData){
                if(this.tableCfg.checkCommitData.call(this.$parent,commitdata)===false) return;
            }
            if(noConfim){
                this.doCommit(row,commitdata,args)
            }else {
                this.$confirm(this.labelCfg.txtConfirmForSave || '确认要保存？', this.labelCfg.txtTips || '提示', {
                    confirmButtonText: this.labelCfg.txtConfirm || '确定',
                    cancelButtonText: this.labelCfg.txtCancel ||'取消',
                    type: 'warning'
                }).then(() => {
                    this.doCommit(row,commitdata,args)
                });
            }
        },
        doCommit(row,commitdata,args){
            args = args || {};
            try {
                if(this.tableCfg.tranCommitData){
                    this.tableCfg.tranCommitData.call(this.$parent,commitdata)
                    
                    if(this.$store.state.envCfg && this.$store.state.envCfg.goldBet!=1){
                        this.goldFlagList.map(item=>{
                            var val = commitdata[item.prop];
                            if(val && this.reTranGold){
                                commitdata[item.prop] = this.reTranGold(val)
                            }
                        })
                    }
                }
            }catch(ex){
                this.$message.error("exPubTable.commitEditRow.tranData Error / "+ex.message);
            }
            var requrl = this.tableCfg.updateUrl;
            if(row.isNew && this.tableCfg.createUrl){
                requrl = this.tableCfg.createUrl;
            }else if(args.updateUrl){
                requrl = args.updateUrl;
            }
            this.$axios.post(requrl,commitdata)
            .then((res) => {
                if (res.data.code == 200) {
                    this.$message.success(this.labelCfg.txtModifySucc || '修改成功')
                    if((row.isNew && !this.tableCfg.noRefreshAfterAdd) || this.tableCfg.refreshAfterCommit){  //新增需要刷新列表
                        this.getDataList();
                    }else {
                        this.updateRow(row)
                    }
                    this.$emit("afterModify",true);
                } else {
                    this.$message.error(res.data.message);
                }
            })
            .catch((error)=> {
                var resp = JSON.stringify(error);
                this.$message.error((this.labelCfg.txtCommitFail || "提交失败,返回信息: ")+resp);
            });
        },
        deleteRow(s){
            this.$confirm(this.labelCfg.txtConfirmForDelete || '确认要删除？', this.labelCfg.txtTips || '提示', {
                confirmButtonText: this.labelCfg.txtConfirm || '确定',
                cancelButtonText: this.labelCfg.txtCancel ||'取消',
                type: 'warning'
            }).then(() => {
                let reqdata = ''
                try{
                    if(this.tableCfg.delDataDef){ // 自定义删除参数
                        reqdata = this.tableCfg.delDataDef.call(this.$parent,s.row)
                    }
                }catch(ex){
                    console.log(ex)
                    this.$message.error("exPubTable.getSummaries.tranData Error / "+ex.message);
                }

                this.$axios.post(this.tableCfg.deleteUrl, reqdata || s.row)
                .then((res) => {
                    if (res.data.code == 200) {
                        this.$message.success(this.labelCfg.txtDeleteSucc || '删除成功')
                        this.getDataList();
                        this.$emit("afterModify",true);
                    } else {
                        this.$message.error(res.data.message);
                    }
                })
                .catch((error)=> {
                    var resp = JSON.stringify(error);
                    this.$message.error((this.labelCfg.txtDeleteFail || "删除失败,返回信息: ")+resp);
                });
            });
        },
        handleSortChange({ column, prop, order }){
            if(this.$listeners["sort-change"]){
                return;
            }
            if(this.tableCfg.useServerSort || this.tableCfg.localPage){
                if(!order){
                    this.sortType = "";
                    this.sortBy="";
                    this.getDataList();
                    return;
                }
                if(order=="descending"){
                    this.sortType = "desc";
                }else {
                    this.sortType = "asc";
                }
                if(this.tableCfg.localPage){
                    this.sortBy=prop;
                    this.reRender(); 
                }else{
                    if(!this.tableCfg.sortNotToLine){
                        this.sortBy=this.toLine(prop);
                    }else {
                        this.sortBy=prop;
                    }
                    this.getDataList();
                }
            }
            
        },
        getSummaries(param) {
            if(this.curAttrs.getSummaries){
                return;
            }
            const { columns, data } = param;
            
            const sums = [];
            if(data.length==0){
                sums[0] = this.tableCfg.sumText;
                return sums;
            }

            var totalinfo = {};
            if(this.tableCfg.sumNode){
               totalinfo = this.sumInfo || {};
            }else {
                this.initTotalInfo(totalinfo,this.tableCfg.columns);
                this.initTotalInfo(totalinfo,this.tableCfg.columns2);
                for(var i=0;i<data.length;i++){
                    var row = data[i];
                    for (var key in totalinfo) {
                        // 使用for in会遍历数组所有的可枚举属性，包括原型。
                        if (Object.prototype.hasOwnProperty.call(totalinfo, key)) {
                            var tmpval = row[key];
                            if(!isNaN(tmpval)){
                                totalinfo[key] += tmpval*1;
                            }
                        }
                    }
                }
            }
            try{
                if(this.tableCfg.autoSum){
                    this.setAutoSum([totalinfo],true)
                }
                if(this.tableCfg.tranDataList){
                    this.tableCfg.tranDataList.call(this.$parent,[totalinfo],true) //第三个参数表示为合计
                }
                if(this.tableCfg.tranDataItem){
                    this.tableCfg.tranDataItem.call(this.$parent,totalinfo,-1,true)
                }
            }catch(ex){
                console.log(ex)
                this.$message.error("exPubTable.getSummaries.tranData Error / "+ex.message);
            }
            if(!this.$refs.curTable) return;
            var sumEl = this.$refs.curTable.$el.querySelectorAll(".el-table__footer");
            var cells = sumEl[0].querySelectorAll("div.cell");
            cells.forEach((item,idx)=>{
                var cont = item.innerHTML;
                if(cont.indexOf("<")!=-1){
                    item.innerHTML = "";
                }
            });

            var colMap = this.getColMap();
            columns.forEach((column, index) => {
                if (index === 0) {
                    sums[index] = this.tableCfg.sumText;
                    return;
                }
                if(data.length==0) return;
                sums[index] = "";
            });

            this.$nextTick(()=>{
                cells.forEach((item,idx)=>{
                    if(idx==0){
                        item.innerHTML=this.tableCfg.sumText;

                        //存在固定列时需要设置固定列
                        var fixedEl = this.$refs.curTable.$el.querySelectorAll(".el-table__fixed .el-table__footer div.cell");
                        if(fixedEl.length>0){
                            fixedEl[0].innerHTML=this.tableCfg.sumText;
                        }
                        return;
                    }
                    // if(idx==3){
                    //     debugger;
                    // }
                    var column = columns[idx];
                    if(!column || !column.property) return;
                    var curval = totalinfo[column.property];
                    var cont = "";
                    var colCfg = colMap[column.property];
                    if(column.formatter && (curval || curval===0)){
                        try{
                            cont = column.formatter.call(this.$parent,totalinfo,column,curval,0,true);
                            // sums[index] = this.replaceHtmlTag(sums[index]);
                        }catch(ex){
                            this.$message.error("exPubTable.getSummaries.column.formatter Error / col: "+column.property+"/"+ex.message);
                            cont = curval;
                        }
                    }else {
                        cont = curval;
                    }
                    if(cont && colCfg){
                        cont += colCfg["endStr"] || "";
                        if (colCfg.rateBy && totalinfo[colCfg.rateBy]) {
                            cont+= " ("+this.rateFormat(curval,totalinfo[colCfg.rateBy])+")";
                        }else if (colCfg.wrapBy && totalinfo[colCfg.wrapBy]) {
                            var wrapText = totalinfo[colCfg.wrapBy];
                            if(colCfg.wrapFormat){
                                wrapText= colCfg.wrapFormat.call(this.$parent,totalinfo,column,wrapText,0,true)
                            }
                            cont+= " ("+wrapText+")";
                        }
                        
                        if(colCfg.getContentTitle){
                            var title=colCfg.getContentTitle.call(this.$parent,totalinfo);
                            if(title){
                                cont = `<span title="${title}">${cont}</span>`;
                            }
                        }
                    }
                    if(cont===undefined) cont="";
                    if(cont && cont.indexOf && cont.indexOf("<")!=-1){
                        item.innerHTML = cont;
                    }else{
                        item.innerText = cont;
                    }
                });

            });
            return sums;
        },
        initTotalInfo(totalinfo,columns){

            columns.map(item=>{
                if(!item.sumType && item.sumType!==undefined) item.sumType="add";
                if(item.sumType!==undefined && item.prop){
                    totalinfo[item.prop] = 0;
                }
                if(item.columns){
                    this.initTotalInfo(totalinfo,item.columns);
                }
            });
        },
        replaceHtmlTag(text) {
            var reg = /<[^<>]+>/g;//1、全局匹配g肯定忘记写,2、<>标签中不能包含标签实现过滤HTML标签
            text = text.replace(reg, ' ');//替换HTML标签
            // text = text.replace(/&nbsp;/ig, '');//替换HTML空格
            return text;
        },
        clickCount(){
            clearTimeout(this.__clickTimer);
            this.__clickCnt = this.__clickCnt || 0;
            this.__clickCnt++;
            if(this.__clickCnt>5){
                this.isShowColInfo = true;
            }
            this.__clickTimer=setTimeout(()=>{
                this.__clickCnt = 0;
            },1000)
        },
        copyTabelData(){
            var rowarr = [];
            var headarr = []
            this.colList.map(item=>{
                if(item.isShow===false) return;
                if(item.isShow && !item.isShow(item)) return;
                if(item.prop){
                    headarr.push(item.label)
                }
            })
            rowarr.push(headarr.join("\t"));
            
            var data = this.getCurDataList();
            data.map((row,idx)=>{
                var rowitem=[];

                this.colList.map(item=>{
                    if(item.isShow===false) return;
                    if(item.isShow && !item.isShow(item)) return;
                    if(item.prop){
                        var text = row[item.prop]
                        if(!text && text!==0){
                            rowitem.push("")
                        }else{
                            if(item.dictCode){
                                text = this.$dict.tranDict(item.dictCode,text)
                            }else if(item.formatter){
                                text = item.formatter.call(this,row,item,row[item.prop],idx)
                            }
                            rowitem.push(text)
                        }
                    }
                })
                rowarr.push(rowitem.join("\t"))
            })
            var result = rowarr.join("\r\n");
            this.copy(result)
        }
    }
}
</script>

<style lang="less" scoped>

.btnspan{
    display: inline-block;
    button{
        margin-right: 10px;
    }
    button.el-button--text{
        padding: 0 2px; 
    }
}

</style>