<template>
    <div
        class="i-table-border list-page-out list-resize bingo-advance bingo-table"
        :style="'height:' + 'calc(100% - ' + sHeight + 'px)'"
        ref="table-list"
        v-resize="handleResize"
        :class="{ fullScreen: fullFlag }"
    >
        <template>
            <bingo-toolbar
                v-show="toolbar"
                ref="toolbar"
                :showNew="showNew"
                :showDelete="showDelete"
                :showRefresh="showRefresh"
                :showOpenButton="showOpenButton"
                :showAllButton="showAllButton"
                @on-new="newClick"
                @on-refresh="onRefresh"
                @on-delete="onDelete"
                @open-full-modal="openFullModal"
                :fullFlag="fullFlag"
                :disabledNew="disabledNew"
                :disabledDelete="disabledDelete"
                :disabledRefresh="disabledRefresh"
            >
                <span slot="toolbar">
                    <slot> </slot>
                    <!--<Button type='primary' @click="saveLayout">保存布局</Button>-->
                    <Select
                        v-if="layoutShow"
                        v-model="layoutValue"
                        style="width:150px;margin-left: 5px"
                        placeholder="请选择布局"
                        @on-change="layoutChange"
                    >
                        <Option value="">空模板</Option>
                        <Option
                            v-for="item in layoutList"
                            :value="item.name"
                            :key="item.name"
                            >{{ item.name }}</Option
                        >
                    </Select>
                    <Button
                        v-if="layoutShow"
                        type="primary"
                        @click="openLayout"
                        style="margin-left: 5px"
                        >设置布局</Button
                    >
                </span>
            </bingo-toolbar>
        </template>
        <!-- 表格复选框选中时出现 -->
        <div class="table-head-fun" v-if="isShowHeadFun">
            <span class="f-sel"
                >已选择<em class="f-em">{{ selection.length }}</em
                >项</span
            >
            <span class="f-sel f-pub" @click="onEditBtnAll" v-if="isEditBtnAll"
                ><i class="f-ico icon iconfont iconbianji"></i>编辑</span
            >
            <span class="f-line"></span>
            <span class="f-sel f-auth" @click="onDeleteBtnAll" v-if="isDeleteBtnAll"
                ><i class="f-ico icon iconfont iconshanchu"></i>删除</span
            >
            <slot name="tableFun"></slot>
        </div>
        <div :class="{ 'table-full': fullFlag }" style="height:100%;position:relative">
            <Spin
                size="large"
                fix
                v-if="loading"
                :style="{
                    marginTop: spinMT + 'px',
                    height: 'calc(100% - ' + loadingToB2 + 'px)',
                }"
            >
            </Spin>
            <ag-grid-vue
                class="table ag-theme-alpine"
                rowHeight="36"
                headerHeight="36"
                v-bind="$attrs"
                v-on="$listeners"
                :suppressContextMenu="suppressContextMenu"
                :suppressRowClickSelection="suppressRowClickSelection"
                :style="'height:' + zHeigth + 'px'"
                :rowSelection="rowSelection"
                :height="zHeigth"
                :gridOptions="gridOptions"
                :treeData="treeData"
                :columnDefs="columnDefs"
                :rowData="tableData"
                :rowGroupPanelShow="rowGroupPanelShow"
                :groupDefaultExpanded="groupDefaultExpanded"
                @sort-changed="sortChanged"
                @selection-changed="onSelectionChanged"
                :enableRangeSelection="enableRangeSelection"
                :sorting="true"
                :filter="true"
                :resize="true"
                @gridReady="onGridReady"
                :cellClicked="onCellClicked"
                :defaultColDef="defaultColDef"
                :autoGroupColumnDef="autoGroupColumnDef"
                :getDataPath="getDataPath"
                :components="components"
                :localeText="localeText"
                :dataType="dataType"
                :frameworkComponents="frameworkComponents"
                tooltipShowDelay="0"
                :floatingFilter="false"
                :rowDragManaged="rowDragManaged"
                :suppressMovableColumns="true"
                :modules="modules"
            >
            </ag-grid-vue>
            <div class="page-wrapper ivu-text-center" v-show="page">
                <Page
                    placement="top"
                    :total="pageSetting.pageTotal"
                    :page-size="pageSetting.pageSize"
                    :current.sync="pageSetting.pageNum"
                    :show-sizer="pageSetting.showSizer"
                    :page-size-opts="pageSizeOpts"
                    show-total
                    @on-page-size-change="pagesizechange"
                    @on-change="pageChange"
                ></Page>
            </div>
        </div>
        <bingoModalEdit v-model="layoutModal" :width="860" title="布局管理">
            <span slot="toolbar">
                <Button
                    type="primary"
                    customIcon="iconfont iconxinjian1"
                    @click="addLayout"
                    >新建</Button
                >
                <Button type="primary" icon="md-trash" @click="delLayout"
                    >删除</Button
                >
                <Button
                    type="primary"
                    customIcon="iconfont iconbaocun1"
                    @click="saveLayout"
                    >保存</Button
                >
                <Button
                    type="primary"
                    customIcon="iconfont iconbaocunbingguanbi"
                    @click="saveLayoutClose"
                    >保存并关闭</Button
                >
                <Button
                    type="primary"
                    icon="md-close"
                    @click="layoutModal = false"
                    >关闭</Button
                >
                <!--<Button type='primary' icon='md-close' @click="syncCurrentLayout">同步列表布局</Button>-->
            </span>
            <Tabs value="name1" type="card">
                <TabPane label="基础" name="name1">
                    <bingo-form
                        :col="2"
                        :labelWidth="90"
                        ref="form"
                        :button="false"
                        :rules="rules"
                        :data="layoutDetail"
                    >
                        <bingo-grid-item>
                            <FormItem
                                label="模板名称"
                                prop="name"
                                label-for="layoutName"
                            >
                                <Input v-model="layoutDetail.name" />
                            </FormItem>
                        </bingo-grid-item>
                        <bingo-grid-item>
                            <FormItem label="每页条数" label-for="pageSize">
                                <RadioGroup v-model="layoutDetail.pageSize">
                                    <Radio :label="20">20</Radio>
                                    <Radio :label="40">40</Radio>
                                    <Radio :label="50">50</Radio>
                                    <Radio :label="100">100</Radio>
                                </RadioGroup>
                            </FormItem>
                        </bingo-grid-item>
                        <bingo-grid-item :colspan="2">
                            <FormItem label="默认" label-for="default">
                                <!--<Input v-model="layoutDetail.default"/>-->
                                <RadioGroup v-model="layoutDetail.defaultValue">
                                    <Radio :label="1">是</Radio>
                                    <Radio :label="0">否</Radio>
                                </RadioGroup>
                            </FormItem>
                        </bingo-grid-item>
                        <bingo-grid-item :colspan="2">
                            <FormItem label="备注" label-for="remark">
                                <Input
                                    v-model="layoutDetail.remark"
                                    type="textarea"
                                    :rows="3"
                                    maxlength="500"
                                    show-word-limit
                                />
                            </FormItem>
                        </bingo-grid-item>
                    </bingo-form>
                </TabPane>
                <TabPane label="显示" name="name2">
                    <div style="height: 100%">
                        <ag-grid-vue
                            style="width: 100%; height: 320px"
                            class="table ag-theme-fresh"
                            :gridOptions="gridOptions_column"
                            :tooltipShowDelay="tooltipShowDelay"
                            @grid-ready="onGridReady_column"
                            :columnDefs="columnDefs_column"
                            :defaultColDef="defaultColDef_column"
                            :rowDragManaged="true"
                            :animateRows="true"
                            :localeText="localeText"
                            :rowData="currentLayout"
                        ></ag-grid-vue>
                    </div>
                </TabPane>
            </Tabs>
        </bingoModalEdit>
    </div>
</template>
<script>
    import Vue from 'vue';
    import { AgGridVue } from '@ag-grid-community/vue';
    import { AllModules, TemplateService } from '@ag-grid-enterprise/all-modules';
    import * as Api from '@/api/bmsa/account';
    import bingoModalEdit from '@/components/bingo-modal-edit';
    import actionComponent from './action';
    import { on, off } from 'view-design/src/utils/dom';
    import emitter from '@/mixins/emitter'
    export default {
        name: 'bingo-advance-table',
        props: {
            autoGetData: {
                type: Boolean,
                default: true
            },
            autoFitWdith: {
                type: Boolean,
                default: true
            },
            suppressRowClickSelection: {
                type: Boolean,
                default: true
            },
            // loading距顶端距离
            spinMT: {
                type: Number,
                default: 38
            },
            // loading高度计算
            loadingToB: {
                type: Number,
                default: 70
            },
            disabledNew: {
                type: Boolean,
                default: false
            },
            enableRangeSelection: {
                type: Boolean,
                default: true
            },
            disabledDelete: {
                type: Boolean,
                default: false
            },
            disabledRefresh: {
                type: Boolean,
                default: false
            },
            rowSelection: {
                type: String,
                default: 'multiple'
            },
            layoutShow: {
                type: Boolean,
                default: false
            },
            groupDefaultExpanded: {
                type: String
            },
            treeColumn: {
                type: String
            },
            columns: {
                type: Array
            },
            data: {
                type: Array,
                default () {
                    return [];
                }
            },
            dataType: {
                type: String,
                default: 'arr'
            },
            rowGroupPanelShow: {
                type: String
            },
            toolbar: {
                type: Boolean,
                default: false
            },
            treeData: {
                type: Boolean,
                default: false
            },
            showNew: {
                type: Boolean,
                default: true
            },
            showDelete: {
                type: Boolean,
                default: true
            },
            suppressContextMenu: {
                type: Boolean,
                default: true
            },
            bill: {
                type: Boolean,
                default: false
            },
            showRefresh: {
                type: Boolean,
                default: true
            },
            showAllButton: {
                type: Boolean,
                default: true
            },
            autoGroupColumnDef: {
                type: Object
            },
            query: {
                type: Boolean,
                default: false
            },
            showOpenButton: {
                type: Boolean,
                default: true
            },
            modalTable: {
                type: Boolean,
                default: false
            },
            page: {
                type: Boolean,
                default: false
            },
            border: {
                type: Boolean,
                default: false
            },
            customHeight: {
                type: Number,
                default: 0
            },
            height: {
                type: Number
            },
            layoutName: {
                type: String,
                default: ''
            },
            frameworkComponents: {
                type: Object
            },
            pageSetting: {
                type: Object,
                /* zdj */
                default () {
                    return {
                        pageNum: 1,
                        pageTotal: 50,
                        pageSize: 40,
                        showSizer: true,
                        pageSizeOpts: [20, 40, 50, 100]
                    };
                }
            },
            pageSizeOpts: {
                type: Array,
                default: function () {
                    return [20, 40, 50, 100];
                }
            },
            size: {
                type: String,
                default: 'small'
            },
            // 获取数据的api
            dataApi: {
                type: Object,
                default: function () {
                    return null;
                }
            },
            // 是否显示编辑
            isEditBtn: {
                type: Boolean,
                default: true
            },
            // 是否显示删除
            isDeleteBtn: {
                type: Boolean,
                default: true
            },
            // 是否显示批量编辑
            isEditBtnAll: {
                type: Boolean,
                default: false
            },
            // 是否显示批量删除
            isDeleteBtnAll: {
                type: Boolean,
                default: true
            },
            // 显示按钮形式font只显示文字，icon只显示图标，all显示图标和文字
            showBtnType: {
                type: String,
                default: 'all'
            },
            // 更多之外显示的按钮个数
            showBtnOutNum: {
                type: Number,
                default: 2
            },
            processData: {
                // 处理数据的方法
                type: Function,
                default: (data) => {}
            },
            rowDragManaged: {
                type: Boolean,
                default: false
            },
            onOkAdd: {
                type: Function,
                default: (data1, data2, callback) => {
                    callback();
                }
            },
            // 编辑操作之前
            beforeEditBtn: {
                type: Function,
                default: (data1, callback) => {
                    callback();
                }
            },
            // 删除操作之前
            beforeDeleteBtn: {
                type: Function,
                default: (data1, callback) => {
                    callback();
                }
            },
            // 批量删除操作之前
            beforeDeleteBtnAll: {
                type: Function,
                default: (data1, callback) => {
                    callback();
                }
            },
            // 搜索对象
            searchObj: {
                type: Object
            },
            // table上部内容的高度
            topHeight: {
                type: Number,
                default: 0
            },
            // 是否全屏显示
            fullScreen: {
                type: Boolean,
                default: false
            },
            // 是否自定义data
            isCustomData: {
                type: Boolean,
                default: false
            }
        },
        data () {
            return {
                rules: {
                    name: [
                        {
                            required: true,
                            message: '请输入模板名称',
                            trigger: 'blur'
                        }
                    ]
                },
                pageChangeFlag: false,
                tooltipShowDelay: null,
                loading: false,
                layoutDetail: {
                    pageSize: 40,
                    defaultValue: 0,
                    name: ''
                },
                currentLayout: [],
                addValue: '',
                layoutValue: '',
                layoutList: [],
                layoutList2: [],
                layoutModal: false,
                layoutModal2: false,
                getDataPath: null,
                fullModal: false,
                sHeight: 0,
                tHeight: 0,
                zHeigth: 0,
                selection: [],
                orderBy: '',
                fullFlag: false,
                params: {},
                columnDefs: [],
                columnDefs_column: [
                    {
                        field: '移动',
                        width: 38,
                        suppressMenu: true,
                        headerClass: 'header-center',
                        cellStyle: { 'text-align': 'center' },
                        rowDrag: true
                    },
                    { field: 'colName', headerName: '列名', width: 150 },
                    {
                        field: 'width',
                        headerName: '宽度',
                        width: 80,
                        editable: true
                    },
                    {
                        field: 'hide',
                        headerName: '是否显示',
                        width: 120,
                        editable: true,
                        cellEditor: 'agRichSelectCellEditor',
                        cellRenderer: function (params) {
                            if (!params.value || params.value == false) {
                                return '显示';
                            } else {
                                return '隐藏';
                            }
                        },
                        cellEditorParams: {
                            cellRenderer: function (params) {
                                if (!params.value || params.value == false) {
                                    return '显示';
                                } else {
                                    return '隐藏';
                                }
                            },
                            values: [true, false]
                        }
                    },
                    {
                        field: 'sort',
                        headerName: '排序',
                        width: 80,
                        editable: true,
                        cellEditor: 'agRichSelectCellEditor',
                        cellRenderer: function (params) {
                            if (params.value == 'asc') {
                                return '正序';
                            } else if (params.value == 'desc') {
                                return '倒序';
                            } else {
                                return '无排序';
                            }
                        },
                        cellEditorParams: {
                            cellRenderer: function (params) {
                                if (params.value == 'asc') {
                                    return '正序';
                                } else if (params.value == 'desc') {
                                    return '倒序';
                                } else {
                                    return '无排序';
                                }
                            },
                            values: ['asc', 'desc', '']
                        }
                    },
                    {
                        field: 'pinned',
                        headerName: '是否锁定',
                        width: 120,
                        editable: true,
                        cellEditor: 'agRichSelectCellEditor',
                        cellRenderer: function (params) {
                            if (params.value == 'left') {
                                return '靠左锁定';
                            } else {
                                return '不锁定';
                            }
                        },
                        cellEditorParams: {
                            cellRenderer: function (params) {
                                if (params.value == '1' || params.value == 'left') {
                                    return '靠左锁定';
                                } else {
                                    return '不锁定';
                                }
                            },
                            values: ['left', '']
                        }
                    }
                // { field: 'filter', headerName:'过滤条件', width:150, editable: true, },
                ],
                rowData_column: [],
                defaultColDef: { resizable: true },
                defaultColDef_column: { resizable: true },
                gridOptions: {},
                gridOptions_column: {},
                components: {},
                localeText: {
                    page: '页',
                    more: '更多',
                    to: '到',
                    of: 'of',
                    next: '下一页',
                    last: '上一页',
                    first: '首页',
                    previous: '上一页',
                    loadingOoo: '加载中...',
                    selectAll: '查询全部',
                    searchOoo: '查询...',
                    blanks: '空白',
                    filterOoo: '过滤...',
                    applyFilter: 'daApplyFilter...',
                    equals: '相等',
                    notEqual: '不相等',
                    lessThan: '小于',
                    greaterThan: '大于',
                    lessThanOrEqual: '小于等于',
                    greaterThanOrEqual: '大于等于',
                    inRange: '范围',
                    contains: '包含',
                    notContains: '不包含',
                    startsWith: '开始于',
                    endsWith: '结束于',
                    group: '组',
                    columns: '列',
                    filters: '筛选',
                    rowGroupColumns: 'laPivot Cols',
                    rowGroupColumnsEmptyMessage: 'la drag cols to group',
                    valueColumns: 'laValue Cols',
                    pivotMode: 'laPivot-Mode',
                    groups: 'laGroups',
                    values: '值',
                    pivots: 'laPivots',
                    valueColumnsEmptyMessage: 'la drag cols to aggregate',
                    pivotColumnsEmptyMessage: 'la drag here to pivot',
                    toolPanelButton: 'la tool panel',
                    noRowsToShow: '暂无数据',
                    pinColumn: '列定位',
                    valueAggregation: 'laValue Agg',
                    autosizeThiscolumn: '自动调整该列大小',
                    autosizeAllColumns: '自动调整所有列大小',
                    groupBy: '排序',
                    ungroupBy: '不排序',
                    resetColumns: '重置列',
                    expandAll: '展开全部',
                    collapseAll: '关闭',
                    toolPanel: '工具面板',
                    export: '导出',
                    csvExport: '导出为CSV格式文件',
                    excelExport: '导出到Excel',
                    pinLeft: '靠左 &lt;&lt;',
                    pinRight: '靠右 &gt;&gt;',
                    noPin: '清除定位 &lt;&gt;',
                    sum: '总数',
                    min: '最小值',
                    max: '最大值',
                    none: '无',
                    count: '总',
                    average: '平均值',
                    copy: '复制',
                    copyWithHeaders: '携带表头复制',
                    ctrlC: 'ctrl + C',
                    paste: '粘贴',
                    ctrlV: 'ctrl + V'
                },
                rowData: [],
                modules: AllModules,
                baselayoutInfo: null,
                tableData: [],
                isShowHeadFun: false,
                loadingToB2: this.loadingToB
            };
        },
        components: {
            AgGridVue,
            actionComponent: actionComponent,
            bingoModalEdit
        },
        created () {},
        mounted () {
            this.changeHeight();
            // if (!this.query) {
            //     this.sHeight = 10;
            // } else {
            //     //this.sHeight=55;
            //     this.sHeight = 65;
            // }

            this.sHeight = this.topHeight;
            this.toColumn(this.columns);
            this.gridApi = this.gridOptions.api;
            // this.gridApi.copySelectedRangeToClipboard();
            // 组件触发事件注册
            // this.initData();
            if (this.layoutShow) {
                this.getLayout();
            }
            this.tooltipShowDelay = 0;

            this.$on('on-ok-add-confirm', this.onOkAddConfirm); // 新建
            this.$on('on-edit-btn-s', this.onEditBtn); // 编辑
            this.$on('on-delete-btn-s', this.onDeleteBtn); // 删除
            this.$on('get-table-data', this.getTableData); // 刷新

            // 获取table数据--add
            this.getTableData();
        },
        beforeMount () {
            this.gridOptions.context = {
                componentParent: this.$parent.$parent
            };

            this.getDataPath = (data) => {
                return data[this.treeColumn];
            };
        },
        watch: {
            // 监听表格数据--add
            data (val) {
                this.tableData = val;
            },
            fullFlag () {
                if (this.bill) {
                    if (this.fullFlag) {
                    } else {
                        this.zHeigth = 0;
                    }
                }
            },
            fullScreen (val) {
                this.fullFlag = val;
                if (val == true) {
                    this.loadingToB2 = 127;
                } else {
                    this.loadingToB2 = 70;
                }
            }
        },
        methods: {
            // 获取table数据--add
            getTableData (searchObj) {
                if (this.isCustomData) {
                    return false;
                } else {
                    this.loading = true;
                    let dataParams = {};
                    let pageParams = {
                        pageNum: this.pageSetting.pageNum,
                        pageSize: this.pageSetting.pageSize
                    };
                    if (this.page == true) {
                        dataParams = Object.assign(dataParams, pageParams);
                    }
                    if (searchObj) {
                        dataParams = Object.assign(dataParams, searchObj);
                    } else {
                        dataParams = Object.assign(dataParams, this.searchObj);
                    }
                    this.dataApi.tableList(dataParams).then((res) => {
                        let data = res.rows ? res.rows : res;
                        this.tableData = [];
                        if (this.treeColumn) {
                            this.initData(data);
                        } else {
                            this.tableData = data;
                        }
                        this.pageSetting.pageTotal = res.total;
                        if (
                            this.processData &&
                            typeof this.processData === 'function'
                        ) {
                            this.processData.apply(this, [this.tableData]);
                        }
                        this.loading = false;
                    });
                }
            },
            // 编辑
            onEditBtn (row) {
                let _this = this;
                if (this.beforeEditBtn && (typeof this.beforeEditBtn === 'function')) {
                    this.beforeEditBtn.apply(this, [row, function () {
                        _this.$emit('on-edit-btn', row.id);
                    }])
                }
            },
            // 批量编辑
            onEditBtnAll () {
                this.$emit('on-edit-btn-all');
            },
            // 删除按钮
            onDeleteBtn (row) {
                let _this = this;
                if (this.beforeDeleteBtn && (typeof this.beforeDeleteBtn === 'function')) {
                    this.beforeDeleteBtn.apply(this, [row, function () {
                        _this.deleteBtnSure(row);
                    }])
                }
            },
            // 删除按钮确认
            deleteBtnSure (row) {
                this.$Modal.confirm({
                    title: '请确认',
                    content: '<p>是否确认删除?</p>',
                    onOk: () => {
                        this.dataApi.deleteTable(row.id).then((res) => {
                            this.$Message.success('删除成功');
                            if (
                                this.tableData.length == 1 &&
                                this.pageSetting.pageNum > 1
                            ) {
                                this.pageSetting.pageNum--;
                            }
                            this.$emit('onRefresh')
                            this.$emit('on-delete-btn');
                        });
                    }
                });
            },
            // 添加确认
            onOkAddConfirm (cmponent) {
                if (this.onOkAdd && typeof this.onOkAdd === 'function') {
                    let _this = this;
                    this.onOkAdd.call(this, this.tableData, cmponent, function () {
                        _this.getTableData();
                    });
                }
            },
            // 批量删除
            onDeleteBtnAll () {
                let _this = this;
                let idArr = [];
                for (let data of this.selection) {
                    idArr.push(data.id);
                }
                idArr = idArr.join(',');
                if (this.beforeDeleteBtnAll && (typeof this.beforeDeleteBtnAll === 'function')) {
                    this.beforeDeleteBtnAll.apply(this, [idArr, function () {
                        _this.deleteBtnSureAll(idArr);
                    }])
                }
            },
            // 批量删除按钮确认
            deleteBtnSureAll (idArr) {
                this.$Modal.confirm({
                    title: '请确认',
                    content: '<p>是否确认删除?</p>',
                    onOk: () => {
                        this.dataApi.deleteTableAll(idArr).then((res) => {
                            this.$Message.success('删除成功');
                            if (
                                this.tableData.length == 1 &&
                                this.pageSetting.pageNum > 1
                            ) {
                                this.pageSetting.pageNum--;
                            }
                            this.getTableData();
                            this.$emit('on-delete-btn-all');
                        });
                    }
                });
            },
            layoutChange (layoutValue) {
                if (layoutValue && layoutValue != '') {
                    this.getLayoutInfo(layoutValue);
                } else if (this.baselayoutInfo.length != 0) {
                    this.gridApi.columnController.setColumnState(
                        this.baselayoutInfo
                    );
                    this.orderBy = '';
                    this.$emit('getData');
                }
            },
            syncCurrentLayout () {
                if (this.rowData_column.length == 0) {
                    this.rowData_column = this.gridApi.columnController.getColumnState();
                }
                this.currentLayout = [];
                for (let column of this.rowData_column) {
                    for (let item of this.columnDefs) {
                        if (column.colId == item.field) {
                            column.colName = item.headerName;
                        }
                    }
                    if (column.colId == '0' || column.colId == '多选框') {
                        column.colId = '多选框';
                        column.colName = '多选框';
                    } else if (column.colId == '1' || column.colId == '序号') {
                        column.colId = '序号';
                        column.colName = '序号';
                    } else if (column.colId == 'action') {
                    } else {
                        this.currentLayout.push(column);
                    }
                }
            // this.rowData_column=this.currentLayout;
            },
            openLayout () {
                this.layoutModal = true;

                if (this.layoutValue && this.layoutValue != '') {
                    this.getLayoutInfo(this.layoutValue);
                } else {
                    this.layoutDetail = {
                        pageSize: 40,
                        defaultValue: 0,
                        name: ''
                    };
                    this.syncCurrentLayout();
                }
            },
            getLayoutInfo (layoutValue, flag) {
                let params = {
                    userId: this.$store.state.admin.user.info.data.userId,
                    layoutName: layoutValue,
                    tableName: this.layoutName
                };
                Api.getUserLayoutInfo(params).then((res) => {
                    this.layoutDetail = res.data.info;
                    this.currentLayout = res.data.list;
                    let list = [];
                    // this.currentLayout = res.data.list;
                    for (let column of this.columnDefs) {
                        if (column.type == 'selection') {
                            column.colId = '0';
                            column.colName = '多选框';
                            column.pinned = 'left';
                            column.flag = '0';
                            list.push(column);
                        } else if (
                            column.type == 'index' ||
                            column.headerName == '序号'
                        ) {
                            column.colId = '1';
                            column.colName = '序号';
                            column.pinned = 'left';
                            list.push(column);
                        } else if (column.field == 'action') {
                            column.colId = 'action';
                            column.colName = '操作';
                            list.push(column);
                        }
                    }
                    for (let item of res.data.list) {
                        list.push(item);
                    }
                    for (let column of this.currentLayout) {
                        if (
                            column.colId == '"action"' ||
                            column.colName == '操作'
                        ) {
                            column.pinned = 'left';
                            column.flag = '0';
                        }
                    }
                    this.gridApi.columnController.setColumnState(list);
                    this.orderBy = '';
                    for (let item of this.currentLayout) {
                        if (item.sort) {
                            this.orderBy = item.colId + ' ' + item.sort;
                            break;
                        }
                    }
                    if (this.layoutDetail.pageSize) {
                        this.pageSetting.pageSize = this.layoutDetail.pageSize;
                    }
                    if (this.autoGetData) {
                        this.loading = false;
                    }
                    if (!flag) {
                        this.$emit('getData');
                    }
                });
            },
            getLayout () {
                let params = {
                    userId: this.$store.state.admin.user.info.data.userId,
                    tableName: this.layoutName
                };
                if (this.autoGetData) {
                    this.loading = true;
                }
                Api.getUserLayout(params).then((res) => {
                    this.layoutList = res.data;
                    this.baselayoutInfo = this.gridApi.columnController.getColumnState();
                    for (let item of this.layoutList) {
                        if (item.defaultValue == 1 || item.defaultValue == '1') {
                            this.layoutValue = item.name;
                            if (!this.autoGetData) {
                                this.getLayoutInfo(this.layoutValue, true);
                            } else {
                                this.getLayoutInfo(this.layoutValue, false);
                            }
                        }
                    }
                    if (this.autoGetData) {
                        this.loading = false;
                    }
                    if (this.layoutValue == '' && this.autoGetData) {
                        this.$emit('getData');
                    }
                });
            },
            delLayout () {
                this.$Modal.confirm({
                    title: '请确认',
                    content: '<p>是否确认删除？</p>',
                    onOk: () => {
                        if (this.layoutValue == '') {
                            this.$BMessage.warning('请选择要删除的布局');
                            // this.$Message.warning('请选择要删除的布局');
                            return;
                        }
                        let params = { id: this.layoutDetail.id };
                        Api.delLayoutSave(params).then((res) => {
                            this.$Message.success('删除成功!');
                            this.layoutModal = false;
                            this.getLayout();
                        });
                    },
                    onCancel: () => {}
                });
            },
            addLayout () {
                this.layoutDetail = {
                    pageSize: 40,
                    defaultValue: 0,
                    name: ''
                };
                this.syncCurrentLayout();
                this.orderBy = '';
            },
            saveLayout () {
                this.$refs.form.$refs.form.validate((valid) => {
                    if (valid) {
                        let dataDD = [];
                        this.gridApi_column.forEachNode(function (node, index) {
                            dataDD.push(node.data);
                        });
                        let params = {};
                        // Object.assign(params, this.gridApi.columnController.getColumnState(),this.layoutDetail);
                        params.info = this.layoutDetail;
                        params.info.tableName = this.layoutName;
                        params.info.userId = this.$store.state.admin.user.info.data.userId;
                        params.list = dataDD;
                        Api.userLayoutSave(params).then((res) => {
                            if (res.code == '200') {
                                this.$Message.success('保存成功!');
                                this.layoutDetail = res.data.info;
                                this.getLayout();
                                this.layoutValue = this.layoutDetail.layoutName;
                            }
                        // this.layoutList = res.data;
                        });
                    }
                });
            },
            saveLayoutClose () {
                this.$refs.form.$refs.form.validate((valid) => {
                    if (valid) {
                        let dataDD = [];
                        this.gridApi_column.forEachNode(function (node, index) {
                            dataDD.push(node.data);
                        });
                        let params = {};
                        params.info = this.layoutDetail;
                        params.info.tableName = this.layoutName;
                        params.info.userId = this.$store.state.admin.user.info.data.userId;
                        params.list = dataDD;
                        Api.userLayoutSave(params).then((res) => {
                            if (res.code == '200') {
                                this.$Message.success('保存成功!');
                                this.layoutModal = false;
                                this.getLayout();
                                this.layoutValue = '';
                            }
                        });
                    }
                });
            },
            sortChanged (data) {
                let columns = data.columnApi.columnController.gridColumns;
                for (let column of columns) {
                    for (let col in column) {
                        if (col == 'sort' && column[col]) {
                            this.orderBy = column.colId + ' ' + column.sort;
                        }
                    }
                }
                // console.log(this.orderBy);
                this.$emit('getData');
            },
            initData (data) {
                let arr = [];
                function getArrList (data) {
                    data.forEach((it) => {
                        arr.push(it);
                        if (it.children) {
                            getArrList(it.children);
                        }
                    });
                }
                getArrList(data);
                this.toChangeData(arr);
            },
            // 获取树形数据
            toChangeData (data) {
                function getName (item, obj) {
                    if (item.parentId && item.parentId != 0) {
                        data.forEach((it) => {
                            if (it.id == item.parentId) {
                                obj.nameCn.unshift(it.nameCn);
                                getName(it, obj);
                            }
                        });
                    }
                }
                data.forEach((item) => {
                    let obj = JSON.parse(JSON.stringify(item));
                    obj.nameCn = [obj.nameCn];
                    getName(item, obj);
                    this.tableData.push(obj);
                });
            },
            getParams () {
                let orderBy = {},
                    pageParams = {};
                if (
                    !this.pageChangeFlag &&
                    this.$parent.$parent.$refs.query &&
                    JSON.stringify(this.$parent.$parent.$refs.query.getParams()) !=
                    '{}'
                ) {
                    this.pageSetting.pageNum = 1;
                }
                if (this.page) {
                    pageParams = {
                        pageNum: this.pageSetting.pageNum,
                        pageSize: this.pageSetting.pageSize
                    };
                }
                if (this.orderBy && this.orderBy != '') {
                    orderBy = { orderBy: this.orderBy };
                }
                return Object.assign(orderBy, pageParams);
            },
            setCustomHeight (customHeight) {
                this.sHeight = this.sHeight + customHeight;
            },
            setLoading () {
                if (this.loading) {
                    this.pageChangeFlag = false;
                }
                this.loading = !this.loading;
            },
            handleResize () {
                this.changeHeight();
            },
            changeHeight () {
                if (this.toolbar) {
                    this.tHeight =
                        this.$refs['table-list'].offsetHeight -
                        this.$refs['toolbar'].$el.offsetHeight -
                        30;
                } else {
                    if (this.page == true) {
                        this.tHeight = this.$refs['table-list'].offsetHeight - 30;
                    } else {
                        this.tHeight = this.$refs['table-list'].offsetHeight;
                    }
                }
                if (this.height) {
                    this.zHeigth = this.height;
                } else {
                    this.zHeigth = this.tHeight;
                }
                if (this.fullFlag) {
                    this.zHeigth = document.body.clientHeight - 120;
                }
                if (this.bill && this.fullFlag) {
                    this.zHeigth = document.body.clientHeight - 180;
                }
            },
            pageChange (page) {
                this.pageChangeFlag = true;
                this.pageSetting.pageNum = page;
                this.getTableData();
            // this.$emit('getData');
            },
            pagesizechange (pageSize) {
                this.pageSetting.pageSize = pageSize;
                this.pageChange(1);
            },
            onSelectionChanged () {
                let selection = this.gridApi.getSelectedRows();
                if (selection.length > 0) {
                    this.isShowHeadFun = true;
                } else {
                    this.isShowHeadFun = false;
                }
                this.selection = selection;
                this.$emit('on-selection-change', selection);
            },
            onSelect (selection, row) {
                this.selection = selection;
            },
            onSelectAll (selection) {
                this.selection = selection;
            },
            onSelectionChange (selection) {
                this.$emit('on-selection-change', selection);
            },
            // 新建
            newClick (selection) {
                this.$emit('on-new');
            },
            // 刷新
            onRefresh () {
                this.$emit('getData');
            },
            getData () {
                this.$emit('getData');
            },
            // --add 导出
            exportFile () {
                this.$emit('exportFile');
            // let exportParam = {
            //     all: true,
            //     name: 'exploreData',
            //     metadata: []
            // }
            // for (let data of this.columns) {
            //     let item={
            //         field:data.key,
            //         name:data.title
            //     }
            //     exportParam.metadata.push(item);
            // }
            // Api.exportExcel(exportParam).then(res => {
            //     // window.location.href = res.data.filePath;
            //     window.location.href = setting.apiBaseURL+'/docservice/'+res.data.filePath;
            // })
            },
            onDelete (selection) {
                this.$emit('on-delete');
            },
            openFullModal (fullFlag) {
                this.fullFlag = fullFlag;
                if (this.autoFitWdith) {
                    this.gridApi.sizeColumnsToFit();
                }
                this.$emit('open-full-modal', this.fullFlag);
            },
            onGridReady (params) {
                this.gridApi = params.api;
                this.columnApi = params.columnApi;
                if (this.autoFitWdith) {
                    this.gridApi.sizeColumnsToFit();
                }
                this.syncCurrentLayout();
            },
            onGridReady_column (params) {
                this.gridApi_column = params.api;
                this.columnApi_column = params.columnApi;
                this.gridApi_column.sizeColumnsToFit();
            },
            onCellClicked (cell) {
                console.log(cell);
                // 获取选中的单元格的数据
                console.log(cell.value);
                // 获取选中的单元格所在的行号，从0开始
                console.log(cell.rowIndex);
                // 获取选中的单元格所在行的所有数据
                console.log(cell.data);
                // 获取选中的单元格所在列的表头的headerName 和 field
                console.log(cell.colDef);
            },
            onModelUpdated (param) {
                console.log('onModelUpdated');
                console.log(param);
            },
            toColumn (columns) {
                this.columnDefs = [];
                let data = {};
                for (let column of columns) {
                    if (column.type == 'selection') {
                        data = {
                            field: column.key,
                            type: column.type,
                            headerName: column.title,
                            suppressMenu: true,
                            editable: false,
                            pinned: 'left',
                            headerCheckboxSelection: true,
                            headerCheckboxSelectionFilteredOnly: true,
                            checkboxSelection: true,
                            width: 65,
                            headerClass: 'header-center',
                            resizable: false
                        };
                    } else if (column.type == 'index') {
                        data = {
                            headerName: '序号',
                            suppressMenu: true,
                            sortable: false,
                            pinned: 'left',
                            width: column.width,
                            headerClass: 'header-center',
                            cellClass: 'cell-center',
                            resizable: false,
                            valueGetter: (params) => params.node.rowIndex + 1
                        };
                    } else if (column.title == '操作') {
                        data = {
                            cellRendererFramework: column.slot
                                ? column.slot
                                : 'actionComponent',
                            headerName: column.title,
                            pinned: 'right',
                            width: column.width,
                            minWidth: column.minWidth,
                            headerClass: column.headerClass,
                            resizable: false
                            // width: 230
                        };
                    } else {
                        data = {
                            field: column.key,
                            pinned: column.fixed,
                            width: column.width,
                            minWidth: column.minWidth,
                            type: column.type,
                            rowGroup: column.rowGroup,
                            enableRowGroup: column.enableRowGroup,
                            headerName: column.title,
                            headerClass: column.headerClass,
                            headerComponent: column.headerComponent,
                            cellRendererFramework: column.slot,
                            cellEditorFramework: column.cellEditorFramework,
                            editable: column.editable,
                            cellEditorSelector: column.cellEditorSelector,
                            cellEditor: column.cellEditor,
                            cellEditorParams: column.cellEditorParams,
                            cellRenderer: column.cellRenderer,
                            keyCreator: column.keyCreator,
                            hide: column.hide,
                            valueFormatter: column.valueFormatter,
                            headerTooltip: column.headerTooltip,
                            tooltipComponent: column.tooltipComponent,
                            sort: column.sort,
                            cellStyle: column.cellStyle,
                            filter: 'agTextColumnFilter',
                            suppressMenu: column.suppressMenu,
                            sortable: column.sortable,
                            /* zdj */
                            checkboxSelection: column.checkboxSelection,
                            headerCheckboxSelection: column.headerCheckboxSelection,
                            rowDrag: column.rowDrag
                        };
                    }
                    this.columnDefs.push(data);
                }
            }
        }
    };
</script>
