<template>
    <div class="tabChangeBody">
        <div class='tableContent' style="position: relative;overflow: auto;">
            <!--查询表格内容区域-->
            <Table :columns="tableTitle" :data="tableDataNew" :height="tableHeight" style="min-height:400px;max-height:700px;position: absolute;width: auto;max-width:auto"></Table>
        </div>
        <div class="height5"></div>
        <div class="pageContent" v-if="!(pageSet && pageSet.isShowPage == false)">
            <!--分页区域-->
            <Page
                ref="pageContent"
                class='pagePosition'
                :total="totalCount"
                :current='currentPage'
                show-total
                show-elevator
                show-sizer
                :page-size='pageSize'
                :page-size-opts='pageSizeOpts'
                @on-change="onPageNumChange"
                @on-page-size-change="onPageSizeChange"
            />
        </div>
    </div>
</template>
<script>
import QueryUtil from "./queryUtil.js";
export default {
    name: "QueryTabs",
    props: {
        queryBus: {
            type: Object,
            require: true
        },
        groups: {
            type: Array,
            require: true
        },
        //自定义页签对象，个性化需求
        groupCount: {
            type: Object,
            require: false
        },
        content: {
            type: Object,
            require: true
        },
        defaultGroup: {
            type: String,
            default: ""
        },
        isShowTabCountZero: {
            type: Boolean,
            default: true
        },
        queryHandler: {
            type: Object
        },
        tableHeight: {
            type: Number,
            default: 400
        },
        //额外的过滤条件
        extrCondition: {
            type: Array,
            default: function () {
                return new Array();
            }
        },
        dynamicSeniorQueryCondition: {
            type: Array,
            default: function () {
                return new Array();
            }
        },
        // 自定义数据请求接口	add by xiongkang	2019-9-27
        customUrl: {
            type: String,
            required: false,
            default: function () {
                return this.DEFAULT_REQUEST_URL;
            }
        },
        contentIcon: {
            type: String,
            default: ""
        },
        emitFlag: {
            type: String,
            default: ""
        },
        extraActionObject: {
            type: [Object, Array]
        }
    },
    data() {
        // 默认请求数据的接口   add by xiongkang 2019-9-27
        const default_request_url = "/advance/query";
        return {
            summerData: {}, //资产个性化固定的合计信息对象
            DEFAULT_REQUEST_URL: default_request_url,
            isShowBuildData: false, //是否展示无数据
            tagData: [], //查询条件确定后数组信息
            currentPage: 1, //查询当前页码数
            labelStr: "", //当前面板关联的值
            iconColor: "#fff", //图标颜色
            isShowSeniorQueryContent: false, //高级查询图标切换是否展示内容
            toolbar: [], //页签动作配置
            table: {}, //查询元数据中table属性配置信息
            pageSet: {}, //分页默认自定义配置对象
            reqData: {}, //暂无使用变量
            tabIndex: 0, //当前页签指标
            currentTab: {}, //当前页签配置对象
            tableData: [], //查询列表数据
            tableSelection: [], //查询列表选择数据
            /*
             * 选择行记录器，页码对应选项
             * 切换pagesize、tab、执行高级查询就重置
             */
            selectionRecorder: {}, //当前选择的查询数据录入，针对情况分页
            totalCount: 0, //表格数据条数
            singleCount: 0,
            multipleCount: 0,
            judgeCount: 0,
            canChoseCol: [],
            pageSize: 10,
            pageSizeOpts: [10, 20, 40],
            seniorQueryData: [], //高级查询对象
            quickQueryData: [], //快捷查询对象
            GroupInfo: "",
            currentContent: null, //当前页签查询配置内容
            innerScenes: [], //内置查询方案
            scenes: [], //查询方案数组
            currentRole: "", //当前角色权限
            cardInfo: { //资产固定合计信息对象
                shul: 0,
                jiaz: 0.0,
            },
            isShowScenes: true, //展示查询方案
            tableVisible: false, //加载状态
            spinStyle: {
                width: "100%",
                height: window.innerHeight - 300 + "px",
                position: "relative"
            },
            tableTitle: [],
            tableDataNew: []
        };
    },
    created() {
        this.tabOnClick(this.getIndex(this.groups));

    },
    computed: {
        noTabPadding() {
            return this.groups.length == 1 ? true : false;
        },
        haveTabPadding() {
            return this.groups.length > 1 ? true : false;
        }
    },
    watch: {
        "queryBus.config.groups": function (newVal, oldVal) {
            if (newVal == oldVal) {
                return;
            }
            let res = this.queryTabCount();
            res.then(() => {
                if (this.defaultGroup == "" && newVal != oldVal) {
                    this.tabOnClick(this.getIndex(this.groups));
                }
            }).catch((error) => {
                //@king 新加的
                if (this.defaultGroup == "" && newVal != oldVal) {
                    this.tabOnClick(this.getIndex(this.groups));
                }
            });
        },
        isShowSeniorQueryContent() {
            this.isHeight100 = this.isShowSeniorQueryContent ? false : true;
        }
    },
    methods: {
        getIndex(arr) {
            for (let i = 0; i < arr.length; i++) {
                let item = arr[i];
                if (item.count != 0) {
                    return i;
                }
            }
            return 0;
        },
        //控制表格页签中列设置展示
        noShowColSet() {
            this.$refs.toolBar.noShowColSet = false;
        },
        //打开或关闭高级查询触发刷新
        onSeniorQuery() {
            this.buttonRefreshData();
        },
        //清空筛选条件
        closeAllTag() {
            this.$refs.seniorQuery.closeAllTag();
        },
        //删除单个筛选条件
        closeSingleTag(val) {
            this.$refs.seniorQuery.closeSingleTag(val);
        },
        //给条件展示区域数据赋值
        sendTagData(data) {
            this.tagData = data;
        },
        //获取查询页签中数据数量
        queryTabCountOld() {
            let that = this;
            return new Promise((res, rej) => {
                let arr = [];
                //判断每个页签是否含有配置内容，如无则走默认主页签配置内容
                for (var g of this.groups) {
                    if (g.content) {
                        let params = {
                            conditions: []
                        };
                        params.datasource = g.content.datasource;
                        if (that.extrCondition.length > 0) {
                            params.conditions = params.conditions.concat(that.extrCondition);
                        }
                        let customConditions = that.queryBus.customConditions;
                        // 所有页签都用到的过滤条件
                        if (customConditions && customConditions.commons && customConditions.commons.length != 0) {
                            params.conditions = params.conditions ? params.conditions.concat(customConditions.commons) : customConditions.commons;
                            // 自定义页签用到的过滤条件
                            let currGroup = that.queryBus.config.groups[that.tabIndex];
                            if (currGroup) {
                                let groupCustomConditions = customConditions[currGroup.name];
                                if (groupCustomConditions && groupCustomConditions.length != 0) {
                                    params.conditions = params.conditions ? params.conditions.concat(groupCustomConditions) : groupCustomConditions;
                                }
                            }
                        }
                        arr.push(params);
                    } else {
                        let temp = {
                            conditions: []
                        };
                        temp.datasource = that.content.datasource;
                        if (that.extrCondition.length > 0) {
                            temp.conditions = temp.conditions.concat(that.extrCondition);
                        }
                        let customConditions = that.queryBus.customCondition;
                        // 所有页签都用到的过滤条件
                        if (customConditions && customConditions.commons && customConditions.commons.length != 0) {
                            temp.conditions = temp.conditions.concat(customConditions.commons);
                            // 自定义页签用到的过滤条件
                            let currGroup = that.queryBus.config.groups[that.tabIndex];
                            if (currGroup) {
                                let groupCustomConditions = customConditions[currGroup.name];
                                if (groupCustomConditions && groupCustomConditions.length != 0) {
                                    temp.conditions = temp.conditions.concat(groupCustomConditions);
                                }
                            }
                        }
                        arr.push(temp);
                    }
                }
                //@king
                GMS.$http.post(
                    QueryUtil.api.counts,
                    arr
                ).then(function (response) {
                    //@king
                    let values = response.data;
                    for (var i = 0; i < values.length; i++) {
                        that.$set(that.groups[i], "count", values[i] ? values[i] : 0);
                        that.$set(that.groups[i], "countZero", values[i] ? (values[i] == 0 ? false : true) : false)
                    }
                    try {
                        res("getCountSuccess");
                    } catch (e) {
                        console.log(e);
                    }
                }).catch((e) => {
                    rej("getCountError");
                });
            });
        },
        //自定义获取查询页签数据数量
        queryTabCountNew() {
            let that = this;
            return new Promise((res, rej) => {
                let groupNames = [];
                for (var g of this.groups) {
                    groupNames.push(g.name);
                }
                //@king
                // GMS.$http.post(this.rootUrl + "/advance/query/groupCount", {
                GMS.$http.post(
                    QueryUtil.api.groupCount,
                    {
                        groupCount: this.groupCount,
                        groupNames: groupNames
                    }
                ).then(function (response) {
                    let values = response.data;
                    for (var i = 0; i < values.length; i++) {
                        that.$set(that.groups[i], "count", values[i] ? values[i] : 0);
                        that.$set(that.groups[i], "countZero", values[i] ? (values[i] == 0 ? false : true) : false);
                    }
                    res("getCountSuccess");
                }).catch(function (e) {
                    rej("getCountError");
                });
            });
        },
        //获取页签中数据数量
        queryTabCount() {
            if (this.groupCount && this.groupCount.enable) {
                return this.queryTabCountNew();
            } else {
                return this.queryTabCountOld();
            }
        },
        //动态获取面板展示标题和数量的信息，同时支持页签图标配置属性为tabIcon
        getTitleAndCount(tab) {
            let baseLabelContent = tab.count ? tab.title + "(" + tab.count + ")" : tab.title;
            if (tab.tabIcon) {
                return (h) => {
                    return h(
                        "div",
                        {
                            class: "outerDiv"
                        },
                        [
                            h(
                                "span",
                                {
                                    class: "spanTitle"
                                },
                                baseLabelContent
                            ),
                            h(
                                "span",
                                {
                                    class: "spanIcon"
                                },
                                [
                                    h(
                                        "svg",
                                        {
                                            class: "icon",
                                            attrs: {
                                                "aria-hidden": "true"
                                            }
                                        },
                                        [
                                            h("use", {
                                                attrs: {
                                                    "xlink:href": "#icon-_" + tab.tabIcon
                                                }
                                            })
                                        ]
                                    )
                                ]
                            )
                        ]
                    );
                };
            }
            return baseLabelContent;
        },
        //切换高级查询内容是否展开
        toggleShowSeniorQueryContent() {
            this.isShowSeniorQueryContent = !this.isShowSeniorQueryContent;
            this.$emit("toggleShowSeniorQueryContent", this.isShowSeniorQueryContent);
        },
        //关闭高级查询内容展示
        closeSeniorQuery() {
            this.isShowSeniorQueryContent = false;
        },
        //列设置状态改变时触发
        getChangeColData(data) {
            //除ACTION类型，默认查询列都不展示，即selected为false
            for (let i = 0; i < this.table.columns.length; i++) {
                let iBool = this.table.columns[i].type != "ACTION";
                if (iBool && this.table.columns[i].columnType.name == "select") {
                    this.table.columns[i].columnType.data.selected = false;
                }
            }
            //除ACTION类型，将重新选择匹配需展示查询列的selected设为true，匹配条件有一项为title
            for (let j = 0; j < data.length; j++) {
                let jItem = data[j];
                for (let k = 0; k < this.table.columns.length; k++) {
                    let kItem = this.table.columns[k];
                    let kBool = kItem.type != "ACTION";
                    if (kBool && kItem.columnType.name == "select" && jItem == kItem.title) {
                        kItem.columnType.data.selected = true;
                        break;
                    }
                }
            }
            this.refreshData("queryTab-getChangeColData");
        },
        //切换页签时触发更新
        tabOnClick(name) {
            // this.handleClearSelection();
            //可能存在问题？？？是否会影响到查询中心？？？
            // this.tableVisible = true;
            // this.$refs.toolBar.noShowColSet = true;
            // this.isShowSeniorQueryContent = false;
            this.tabIndex = name;
            let currGroup = this.queryBus.config.groups[this.tabIndex];
            this.currentTab = currGroup;
            this.loadContent(currGroup);
            this.refreshData("queryTab-getChangeColData");
        },
        //根据改变页签初始化页签配置内容
        loadContent(currGroup) {
            let currContent = undefined;
            this.queryBus.currGroup = currGroup;
            if (!currGroup.content) {
                currContent = this.queryBus.config.content;
            } else {
                //考虑页签单独配置时的两种情况：需继承主页签部分配置；具有自己单独的配置信息
                currContent = currGroup.content;
                currContent.datasource = currContent.datasource ? currContent.datasource : this.queryBus.config.content.datasource;
                currContent.actions = currContent.actions ? currContent.actions : this.queryBus.config.content.actions;
                currContent.table = currContent.table ? currContent.table : this.queryBus.config.content.table;
                currContent.arguments = currContent.arguments ? currContent.arguments : this.queryBus.config.content.arguments;
                if (!currContent.scenes && this.queryBus.config.content.scenes) {
                    currContent.scenes = this.queryBus.config.content.scenes;
                }
                if (!currContent.page && this.queryBus.config.content.page) {
                    currContent.page = this.queryBus.config.content.page;
                }
            }
            this.queryBus.currGroup.content = JSON.parse(JSON.stringify(currContent));
            this.currentContent = currContent;
            this.table = currContent.table;
            this.pageSet = currContent.page;
            // this.toolbar = currContent.actions;
            this.filterToolActionsByRole(currContent.actions);
            this.seniorQueryData = currContent.arguments ? currContent.arguments.items : [];
            this.quickQueryData = currContent.quickArguments ? currContent.quickArguments.items : [];
            this.queryBus.datasource = currContent.datasource;
            this.queryBus.page.pageNum = 1;
            // this.queryBus.page.pageSize = currContent.table.pageSize;//暂时先这样处理
            /**
             * zjy添加
             */
            this.queryBus.orders = [];
            this.queryBus.groupBy = [];
            this.queryBus.seniorQueryData = [];
            this.currentPage = 1;
            GMS.vbus.$emit("clearQueryConditions", this.emitFlag);
            GMS.vbus.$emit("closeAllTag", this.emitFlag);
            this.loadInnerScene(currContent.scenes);
            this.loadScene();
            let bool = this.judgeCurrentSeniorQueryIsHaveDefaultValue(this.seniorQueryData);
            if (!bool && this.dynamicSeniorQueryCondition.length == 0) {
                this.refreshData("queryTabs-loadContent");
            }
        },
        //判断高级查询条件是否具有默认值
        judgeCurrentSeniorQueryIsHaveDefaultValue(arr) {
            for (let i = 0; i < arr.length; i++) {
                let item = arr[i];
                for (let j = 0; j < item.length; j++) {
                    let jItem = item[j];
                    if (jItem.config.defaultVal) {
                        return true;
                    }
                }
            }
            return false;
        },
        //根据角色权限过滤动作
        filterToolActionsByRole(actions) {
            this.toolbar = [];
            if (this.currentRole && actions && actions.length > 0) {
                for (let i = 0, len = actions.length; i < len; i++) {
                    let action = actions[i];
                    if (!action.children || action.children.length == 0) {
                        if (this.judgeToolActionsEnable(action)) {
                            this.toolbar.push(action);
                        }
                    } else {
                        let childrens = action.children;
                        let temp = [];
                        for (let j = 0, l = childrens.length; j < l; j++) {
                            let children = childrens[j];
                            if (this.judgeToolActionsEnable(children)) {
                                temp.push(children);
                            }
                        }
                        if (temp && temp.length > 0) {
                            action.children = temp;
                            this.toolbar.push(action);
                        }
                    }
                }
            }
        },
        //根据动作的enable属性进行二次过滤
        judgeToolActionsEnable(action) {
            let enableRole = action.enable;
            if (action && enableRole) {
                if (enableRole instanceof Array) {
                    return enableRole.indexOf(this.currentRole) > -1;
                } else {
                    return (enableRole == this.currentRole || enableRole == "ALL");
                }
            }
            return false;
        },
        //循环查询列获取查询字段信息
        forChildren(arr) {
            for (let i = 0; i < arr.length; i++) {
                let item = arr[i];
                if (item.children && item.children.length > 0) {
                    this.forChildren(item.children);
                } else {
                    let itemBool = item.type != "ACTION";
                    if (itemBool && (item.columnType.name == "fixed" || item.columnType.name == "inner" || (item.columnType.name == "select" && item.columnType.data.selected && item.columnType.data.selected != false))) {
                        this.queryBus.queryFields.push(item.key);
                    }
                }
            }
        },
        //获取要查询的字段
        getRequestQueryFields() {
            this.queryBus.queryFields = [];
            let colItem = this.table.columns;
            if (colItem && colItem.length > 0) {
                this.forChildren(colItem);
            }
        },
        //获取要查询的请求体信息
        getRequestInfo() {
            let result = {};
            result.datasource = this.queryBus.datasource;
            result.page = {};
            result.page.pageNum = this.queryBus.page.pageNum;
            result.page.size = (this.pageSet && this.pageSet.isShowPage == false) ? (this.pageSet.defaultQueryNumber ? this.pageSet.defaultQueryNumber : 200) : this.queryBus.page.pageSize;
            result.groupBy = this.queryBus.groupBy;
            result.orders = this.queryBus.orders;
            this.getRequestQueryFields();
            result.queryFields = this.queryBus.queryFields;
            result.conditions = this.getCurrConditions();
            return result;
        },
        //获取当前所有查询条件
        getCurrConditions() {
            let conditions = [];
            conditions = this.extrCondition.length != 0 ? conditions.concat(this.extrCondition) : conditions;
            let fuzzySearchCondition = this.getFuzzySearchCondition();
            conditions = fuzzySearchCondition ? conditions.concat(fuzzySearchCondition) : conditions;
            let seniorCondition = this.getSeniorCondition();
            conditions = seniorCondition && seniorCondition.length > 0 ? conditions.concat(seniorCondition) : conditions;
            let customConditions = this.getCustomConditions();
            conditions = customConditions && customConditions.length > 0 ? conditions.concat(customConditions) : conditions;
            return conditions;
        },
        //获取模糊搜索条件
        getFuzzySearchCondition() {
            if (this.queryBus.fuzzySearch.key && this.queryBus.fuzzySearch.value) {
                let condition = {};
                condition.name = this.queryBus.fuzzySearch.key;
                condition.values = this.queryBus.fuzzySearch.value;
                condition.type = "STRING";
                return condition;
            }
            return null;
        },
        //获取高级查询条件
        getSeniorCondition() {
            if (this.queryBus.seniorQueryData.length == 0) {
                return;
            }
            let conditions = [];
            for (let i = 0; i < this.queryBus.seniorQueryData.length; i++) {
                let condition = {};
                let seniorData = this.queryBus.seniorQueryData[i];
                if (seniorData.name instanceof Object) {
                    for (let key in seniorData.name) {
                        let condition = {};
                        if (seniorData.value[key] == null || seniorData.value[key] == "") {
                            continue;
                        }
                        condition.name = seniorData.name[key];
                        condition.values = seniorData.value[key];
                        condition.type = seniorData.dataType ? seniorData.dataType : null;
                        conditions.push(condition);
                    }
                } else if (Array.isArray(seniorData.value)) {
                    if (seniorData.value.length == 0) {
                        continue;
                    }
                    condition.name = seniorData.name;
                    condition.values = seniorData.value;
                    condition.type = seniorData.dataType ? seniorData.dataType : null;
                    conditions.push(condition);
                } else {
                    if (seniorData.value == "全选") {
                        continue;
                    }
                    condition.name = seniorData.name;
                    condition.values = seniorData.value;
                    condition.type = seniorData.dataType ? seniorData.dataType : null;
                    conditions.push(condition);
                }
            }
            return conditions;
        },
        //获取通用或自定义条件，该条件不在界面展示
        getCustomConditions() {
            let customConditions = this.queryBus.customConditions;
            if (!customConditions) {
                return null;
            }
            let conditions = [];
            // 所有页签都用到的过滤条件
            conditions = customConditions.commons && customConditions.commons.length != 0 ? conditions.concat(customConditions.commons) : conditions;
            // 自定义页签用到的过滤条件
            let currGroup = this.queryBus.config.groups[this.tabIndex];
            if (currGroup) {
                let groupCustomConditions = customConditions[currGroup.name];
                conditions = groupCustomConditions && groupCustomConditions.length != 0 ? conditions.concat(groupCustomConditions) : conditions;
            }
            return conditions;
        },
        //刷新页签动作执行按钮
        buttonRefreshData() {
            this.currentPage = 1;
            this.queryBus.page.pageNum = 1;
            this.refreshData("queryTabs-buttonRefreshData");
        },
        //不同条件下获取数据刷新触发?
        refreshData(whereFrom) {
            switch (whereFrom) {
                case "custom-query-selectall":
                case "queryTabs-buttonRefreshData":
                case "queryTabs--onpagesizechange":
                case "queryTabs--mounted-queryhandler":
                case "queryTabs--custom-query-refresh":
                    this.handleClearSelection();
                    break;
                default:
                    break;
            }
            this.tableData = [];
            this.totalCount = 0;
            let reqData = this.getRequestInfo();
            if (!reqData.page.pageNum && !reqData.page.size) {
                reqData.page.pageNum = 1;
                reqData.page.size = 1000;
            }
            
            let newData = []
            let regString = /[a-zA-Z]+/
            for (let i = 0; i < this.queryBus.queryFields.length; i++) {
                if (regString.test(this.queryBus.queryFields[i])
                    || this.queryBus.queryFields[i].indexOf('id') > -1 || this.queryBus.queryFields[i].indexOf('定义') > -1 || this.queryBus.queryFields[i].indexOf('模板') > -1) {
                } else {
                    let newD = {
                        title: this.queryBus.queryFields[i],
                        key: this.queryBus.queryFields[i],
                        width: '150px',
                        align: 'center'
                    }
                    newData.push(newD)
                }
            }
            this.tableTitle = newData
            
            GMS.$http.post(
                QueryUtil.api.query,
                reqData
            ).then(
                (response) => {
                    let data = response.data;
                    this.tableData = data.rows;
                    if (Object.prototype.hasOwnProperty.call(this.selectionRecorder, this.queryBus.page.pageNum)) {
                        let record = this.selectionRecorder[this.queryBus.page.pageNum];
                        let recordIds = [];
                        for (let r of record) {
                            recordIds.push(r.id);
                        }
                        for (let row of this.tableData) {
                            this.$set(row, "_checked", recordIds.indexOf(row.id) >= 0 ? true : false)
                        }
                    }
                    for (let i = 0;i < this.tableData.length; i++) {
                        for (let j = 0;j < newData.length; j++) {
                            let item = newData[j].title
                            let ty = typeof this.tableData[i][item]
                            if (ty === 'boolean' && 
                                this.tableData[i][item]) {
                                this.tableData[i][item] = '是'
                            } else if (ty === 'boolean' && 
                                !this.tableData[i][item]) {
                                this.tableData[i][item] = '否'
                            } else if (ty === 'number') {
                                let config = "#,###.00"
                                this.tableData[i][item] = QueryUtil.numberFormat(this.tableData[i][item], config)
                            }
                        }
                    }
                    this.tableDataNew = this.tableData
                    if (data.rows.length < 1 && this.queryBus.page.pageNum > 1) {
                        this.onPageNumChange(this.queryBus.page.pageNum - 1);
                        return;
                    }
                    this.totalCount = data.totalCount;
                    this.isShowBuildData = this.totalCount == 0 ? true : false;
                    this.queryBus.currentDataQueryConditionSet = reqData;
                }
            ).catch((error) => {
                this.tableData = [];
                this.totalCount = 0;
            });
            if (this.table.cardTotal && !isSelectAll) {
                this.loadCardTotalInfo();
            }
            if (this.table.total && !isSelectAll) {
                this.loadTotalInfo();
            }
            this.tableVisible = true;
        },
        //触发表格列表全选逻辑，会展示的表格数据
        handleSelectAllData(queryData) {
            this.tableSelection = queryData.rows;
            let records = this.splitArray(this.tableSelection, this.queryBus.page.pageSize);
            if (records.length >= this.queryBus.page.pageNum) {
                for (let row of this.tableData) {
                    this.$set(row, "_checked", true);
                }
            }
            for (var i = 0; i < records.length; i++) {
                let record = records[i];
                let attr = i + 1;
                this.selectionRecorder[attr] = record;
            }
            this.tableVisible = true;
        },
        //清空查询列选择
        handleClearSelection() {
            if (Object.prototype.hasOwnProperty.call(this.selectionRecorder, this.queryBus.page.pageNum)) {
                let record = this.selectionRecorder[this.queryBus.page.pageNum];
                let recordIds = [];
                for (let r of record) {
                    recordIds.push(r.id);
                }
                for (let row of this.tableData) {
                    if (recordIds.indexOf(row.id) >= 0) {
                        this.$set(row, "_checked", false);
                    }
                }
            }
            this.selectionRecorder = {};
            this.tableSelection = [];
        },
        //截取指定长度的数组
        splitArray(arr, size) {
            let objArr = new Array();
            let index = 0;
            let objArrLen = arr.length / size;
            for (let i = 0; i < objArrLen; i++) {
                let arrTemp = new Array();
                for (let j = 0; j < size; j++) {
                    arrTemp[j] = arr[index++];
                    if (index == arr.length) {
                        break;
                    }
                }
                objArr[i] = arrTemp;
            }
            return objArr;
        },
        //查询表格选择状态或数据进行改变时触发
        onSelectionChange(selection) {
            let shouldReturn = false;
            if (Object.prototype.hasOwnProperty.call(this.selectionRecorder, this.queryBus.page.pageNum)) {
                // 在已选项范围内勾选
                let record = this.selectionRecorder[this.queryBus.page.pageNum];
                if (record.length == 0) {
                    // 必然是勾选
                    shouldReturn = this.tableSelection.length >= 1000 || this.tableSelection.length + selection.length >= 1000;
                } else {
                    if (selection.length > record.length) {
                        // 超出原来的选择长度，需要判断最大限制
                        let newLength = this.tableSelection.length + (selection.length - record.length);
                        shouldReturn = newLength >= 1000;
                    }
                }
            } else {
                // 在已选项范围外勾选
                shouldReturn = this.tableSelection.length >= 1000 || this.tableSelection.length + selection.length >= 1000;
            }

            if (shouldReturn) {
                this.$Modal.warning({
                    title: "系统提示",
                    content: "最大仅支持选择1000条，当前已选择" + this.tableSelection.length + "条",
                });
                let rowIds = [];
                for (let row of selection) {
                    rowIds.push(row.id);
                }
                for (let row of this.tableData) {
                    if (rowIds.indexOf(row.id) >= 0) {
                        this.$set(row, "_checked", false);
                    }
                }
                return;
            }

            this.tableSelection = [];
            this.selectionRecorder[this.queryBus.page.pageNum] = selection;
            for (let attr in this.selectionRecorder) {
                this.tableSelection.push(...this.selectionRecorder[attr]);
            }
            this.$emit("onSelectionChange", selection);
        },
        //资产个性化合计值处理逻辑
        loadCardTotalInfo() {
            // return;
            let that = this;
            let params = this.getTotalQueryInfo();
            //@king  这里的合计值资产这边是写死字段的
            GMS.$http.post(
                QueryUtil.api.total,
                params,
                {
                    contentType: "application/json",
                }
            ).then((response) => {
                let data = response.data;
                let info = JSON.parse(data);
                if (data == "{}") {
                    that.cardInfo = {
                        shul: 0,
                        jiaz: 0.0,
                    };
                } else {
                    that.cardInfo = info;
                }
            })
            .catch((error) => {
                that.cardInfo = {
                    shul: 0,
                    jiaz: 0.0,
                };
            });
        },
        //加载合计信息；这个接口暂时没用到
        loadTotalInfo() {
            let that = this;
            let params = this.getTotalQueryInfo();
            //@king
            GMS.$http.post(
                QueryUtil.api.total,
                params,
                {
                    contentType: "application/json",
                }
            ).then((response) => {
                let data = response.data;
                if (data == "{}") {
                    that.summerData = {
                        shul: 0,
                        jiaz: 0.0,
                    };
                } else {
                    that.summerData = JSON.parse(data);
                }
            }).catch((error) => {});
        },
        //获取指定查询字段合计
        getTotalQueryInfo() {
            let result = {};
            result.datasource = this.queryBus.datasource;
            result.groupBy = this.queryBus.groupBy;
            result.conditions = this.getCurrConditions();
            return result;
        },
        //分页页码进行改变时触发
        onPageNumChange(val) {
            this.queryBus.page.pageNum = val;
            this.currentPage = val;
            this.refreshData("queryTabs--onPageNumchange");
            this.$emit("on-querytab-pagechange", val);
        },
        //分页条数进行改变时触发
        onPageSizeChange(val) {
            this.queryBus.page.pageSize = val;
            this.refreshData("queryTabs--onpagesizechange");
            this.$emit("on-querytab-pagesizechange", val);
        },
        //加载已保存的查询场景
        loadScene() {
            let viewName = this.queryBus.config.name;
            let currGroup = this.queryBus.config.groups[this.tabIndex];
            let that = this;
            if (!viewName || !currGroup || !currGroup.name || !this.isShowScenes) {
                this.scenes = [];
                that.sceneAddInner();
                return;
            }
            //@king
            GMS.$http.get(
                QueryUtil.api.sceneQuery + "/" + viewName + "/" + currGroup.name,
                {
                    contentType: "application/json",
                }
            ).then((response) => {
                let data = response.data;
                that.scenes = [];
                that.sceneAddInner();
                //@king
                // let customScene = JSON.parse(data);
                let customScene = data;
                if (customScene.length > 0) {
                    that.scenes.push(customScene);
                }
            }).catch((error) => {
                that.scenes = [];
                that.sceneAddInner();
                this.$Message.error("查询方案获取失败");
            });
        },
        //将需要展示的查询场景存放在查询场景数组中
        sceneAddInner() {
            if (this.innerScenes && this.innerScenes.length > 0) {
                this.scenes.push(this.innerScenes);
            }
        },
        //加载内置查询场景，即默认配置的查询场景
        loadInnerScene(scenes) {
            this.isShowScenes = scenes && (scenes.isShowScenes ? true : false);
            if (!this.isShowScenes) {
                return;
            }
            if (!scenes || !scenes.items || scenes.items.length == 0) {
                this.innerScenes = [];
                return;
            }
            this.innerScenes = [];
            for (let i = 0, len = scenes.items.length; i < len; i++) {
                let item = scenes.items[i];
                let inner = {};
                inner.id = item.name;
                inner.type = "INNER";
                inner.title = item.title;
                inner.content = item.conditions;
                this.innerScenes.push(inner);
            }
        },
        //选择查询方案时触发实现
        selectedScene(val) {
            let conditions = null;
            if (val.type && val.type == "INNER") { //内置场景，默认配置场景
                conditions = JSON.parse(JSON.stringify(val.content));
                let item = {conditions: conditions};
                this.$emit("innerSceneQuery", JSON.parse(JSON.stringify(item)));
            } else { //自定义场景
                conditions = JSON.parse(val.content);
                GMS.vbus.$emit("getQueryPlanData", conditions, this.emitFlag);
            }
        },
        //删除查询方案时实现逻辑
        deleteScene(val) {
            //@king
            GMS.$http.post(
                QueryUtil.api.sceneDelete + "/" + val.id,
                null,
                {
                    contentType: "application/json"
                }
            ).then((response) => {
                this.$Message.success("查询方案删除成功");
                this.loadScene();
            }).catch((error) => {
                this.$Message.error("查询方案删除失败，请重试");
                console.error("自定义查询方案删除失败：" + error);
            });
        },
        async funcQueryTabCount() {
            await this.queryTabCount();
        }
    },
    mounted() {
        var that = this;
        //@king
        // this.currentRole = this.$store.state.role ? this.$store.state.role.name : 'admin';
        this.currentRole = "admin";
        //初始化表格时同时初始化queryHandler对象，增加相关函数属性
        if (this.queryHandler) {
            this.queryHandler.refresh = function () {
                that.refreshData("queryTabs--mounted-queryhandler");
            };
            this.queryHandler.refreshScene = function () {
                that.loadScene();
            };
            this.queryHandler.countRefresh = function () {
                that.funcQueryTabCount();
            };
            this.queryHandler.getCurrentTabIndex = function () {
                return that.tabIndex;
            };
            this.queryHandler.getCurrentTab = function () {
                return that.currentTab;
            };
            this.queryHandler.getQueryParam = function () {
                return that.getRequestInfo();
            };
            this.queryHandler.getTableSelects = function () {
                return that.tableSelection;
            };
            this.queryHandler.getTitle = function () {
                return that.currentTab.title;
            };
            this.queryHandler.handleQuerySelectAll = function () {
                if (that.tableSelection.length > 0) {
                    that.$Modal.confirm({
                        title: "系统提示",
                        content: "全选将覆盖已选项，是否继续？",
                        okText: "继续",
                        onOk: () => {
                            that.refreshData("custom-query-selectall");
                        }
                    });
                } else {
                    that.refreshData("custom-query-selectall");
                }
            };
            this.queryHandler.handleEmptySelectAll = function () {
                that.handleClearSelection();
            };
        }
        GMS.vbus.$on("custom-query-refresh", () => {
            that.refreshData("queryTabs--custom-query-refresh");
        });
        GMS.vbus.$on("custom-query-refresh-scene", () => {
            that.loadScene();
        });
        GMS.vbus.$on("tab-count-refresh", (emitFlag) => {
            if (GMS.util.compareEmitFlag(that.emitFlag, emitFlag)) {
                that.funcQueryTabCount();
            }
        });
        GMS.vbus.$on("custom-query-refresh-button", () => {
            that.buttonRefreshData();
        });
    },
};
</script>
<style lang="less" scoped>
.noTabPadding {
    padding: 10px;
}

.haveTabPadding {
    padding: 15px;
}

.tabChangeBody {
    // padding: 15px;
    background: #ffffff;
    // border: 1px solid #e8e8e8;
    // position: relative;
    height: 100%;

    .contentIcon {
        position: absolute;
        top: -8px;
        left: 15px;
    }

    .spaceLine {
        height: 20px;
        position: relative;
        margin-bottom: 10px;

        .positionRight {
            position: absolute;
            right: 0px;
            top: -5px;
        }
    }

    .tableContent {
        min-height: 400px;
        max-height: 700px;

        .buildPosition {
            position: absolute;
            top: 40%;
            left: 45%;
        }
    }

    .pageContent {
        height: 36px;
        position: relative;

        .pagePosition {
            position: absolute;
            top: 0;
            right: 0;
        }
    }

    /deep/.ivu-tabs-bar {
        margin-bottom: 0;
    }

    .height15 {
        height: 15px;
    }

    .height10 {
        height: 10px;
    }

    .height5 {
        height: 5px;
    }

    /deep/.ivu-page {
        height: 34px;
    }

    .query-scene-button {
        display: inline-block;
        position: relative;
        top: 5px;
    }

    .space {
        display: inline-block;
        width: 20px;
    }

    .seniorQueryFlag {
        display: inline-block;
        position: relative;
        top: 5px;
        height: 23px;
        line-height: 23px;
        cursor: pointer;

        .seniorQueryText {
            font-family: Microsoft YaHei;
            font-size: 14px;
            color: #3477cb;
            text-align: justify;
        }

        .seniorQueryIcon {
            box-sizing: border-box;
            display: inline-block;
            border-radius: 2px;
            padding: 1px;
            width: 14px;
            height: 14px;
            background: #3477cb;
            vertical-align: middle;
            line-height: 12px;
            position: relative;
            bottom: 1px;
        }
    }
}
</style>