<template>
    <div
        class="i-table-border list-page-out list-resize bingo-table"
        :style="'height:' + 'calc(100% - ' + sHeight + 'px)'"
        ref="table-list"
        v-resize="handleResize"
        :class="{ fullScreen: fullFlag }"
    >
        <template>
            <bingo-toolbar
                :showNew="showNew"
                :showDelete="showDelete"
                :fullFlag="fullFlag"
                :showRefresh="showRefresh"
                :showAllButton="showAllButton"
                :showOpenButton="showOpenButton"
                @on-new="newClick"
                @on-refresh="onRefresh"
                @on-delete="onDelete"
                @open-full-modal="openFullModal"
                :disabledNew="disabledNew"
                :disabledDelete="disabledDelete"
                :disabledRefresh="disabledRefresh"
                v-if="toolbar"
                ref="toolbar"
            >
                <span slot="toolbar">
                    <slot name="toolbar"></slot>
                    <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 && isShowTableFun" :style="{marginLeft:tableFunML+'px',width: 'calc(100% - '+tableFunML+'px)'}">
            <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 }">
            <Table
                stripe
                v-bind="$attrs"
                v-on="$listeners"
                @on-select="onSelect"
                @on-select-all="onSelectAll"
                @on-sort-change="onSortChange"
                @on-selection-change="onSelectionChange"
                ref="table"
                :disabledHover="disabledHover"
                :columns="columnsList"
                :loading="loading"
                :height="zHeigth"
                :draggable="draggable"
                @on-drag-drop="onDragDrop"
                :data="tableData"
                :border="true"
                :size="size"
                :highlight-row="highlightRow"
            >
                <template
                    slot-scope="{ row, index }"
                    v-for="col in columns"
                    :slot="col.slot"
                >
                    <slot :name="col.slot" :row="row" :index="index"></slot>
                </template>
                <template slot="contextMenu">
                    <slot name="contextMenu"></slot>
                </template>
                <template slot-scope="{ row, index }" slot="action">
                    <div :class="actionClass" :ref="'actionBtns' + index" v-if="!isCustomBtn" v-show="newAddBtns">
                        <Button
                            type="primary"
                            v-if="isEditBtn"
                            size="small"
                            @click="onEditBtn(row)"
                        >
                            <i class="icon iconfont iconbianji"></i
                            ><span class="font">编辑</span></Button
                        >
                        <Button
                            type="error"
                            v-if="isDeleteBtn"
                            size="small"
                            @click="onDeleteBtn(row)"
                        >
                            <i class="icon iconfont iconshanchu"></i
                            ><span class="font">删除</span></Button
                        >
                        <slot :row="row" :index="index" name="action"></slot>
                        <span>
                            <Dropdown
                                class="toolbar-down-button drop-font-icon"
                                placement="left-start"
                                trigger="click"
                                v-if="showFlag[index]"
                            >
                                <span class="font">更多</span>
                                <Icon type="ios-arrow-down" />
                                <Dropdown-menu
                                    slot="list"
                                    :ref="'dropMenu' + index"
                                >
                                    <slot
                                        :row="row"
                                        :index="index"
                                        name="action"
                                    ></slot>
                                </Dropdown-menu>
                            </Dropdown>
                        </span>
                    </div>
                    <template v-else>
                        <slot :row="row" :index="index" name="action"></slot>
                    </template>
                </template>
            </Table>
            <div class="page-wrapper ivu-text-center" v-show="page">
                <Page
                    placement="top"
                    :total="pageSetting.pageTotal"
                    v-bind="$attrs"
                    v-on="$listeners"
                    :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="布局管理"
            @on-cancel="onCancel"
        >
            <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="onCancel"
                    >关闭</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="每页条数"
                                prop="layoutDetail.pageSize"
                                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"
                            @grid-ready="onGridReady_column"
                            :columnDefs="columnDefs_column"
                            :defaultColDef="defaultColDef_column"
                            :rowDragManaged="true"
                            :animateRows="true"
                            :localeText="localeText"
                            :rowData="currentLayout"
                            :modules="modules"
                        ></ag-grid-vue>
                    </div>
                </TabPane>
            </Tabs>
        </bingoModalEdit>
    </div>
</template>
<script>
    import bingoToolbar from '@/components/bingo-toolbar';
    import Vue from 'vue';
    import * as Api from '@/api/bmsa/account';
    import bingoModalEdit from '@/components/bingo-modal/bingo-modal-edit';
    import bingoForm from '@/components/bingo-form/index.vue';
    import bingoGridItem from '@/components/bingo-grid-item/index.vue';
    import { AgGridVue } from '@ag-grid-community/vue';
    import { AllModules } from '@ag-grid-enterprise/all-modules';
    export default {
        name: 'bingo-table',
        props: {
            layoutShow: {
                type: Boolean,
                default: false
            },
            disabledHover: {
                type: Boolean,
                default: false
            },
            draggable: {
                type: Boolean,
                default: false
            },
            disabledNew: {
                type: Boolean,
                default: false
            },
            disabledDelete: {
                type: Boolean,
                default: false
            },
            disabledRefresh: {
                type: Boolean,
                default: false
            },
            toolbar: {
                type: Boolean,
                default: false
            },
            highlightRow: {
                type: Boolean,
                default: false
            },
            showNew: {
                type: Boolean,
                default: true
            },
            showDelete: {
                type: Boolean,
                default: true
            },
            showOpenButton: {
                type: Boolean,
                default: true
            },
            showRefresh: {
                type: Boolean,
                default: true
            },
            showAllButton: {
                type: Boolean,
                default: true
            },
            query: {
                type: Boolean,
                default: true
            },
            modalTable: {
                type: Boolean,
                default: false
            },
            bill: {
                type: Boolean,
                default: false
            },
            page: {
                type: Boolean,
                default: false
            },
            resizable: {
                type: Boolean,
                default: true
            },
            border: {
                type: Boolean,
                default: false
            },
            layoutName: {
                type: String,
                default: ''
            },
            customHeight: {
                type: Number,
                default: 0
            },
            height: {
                type: Number
            },
            pageSetting: {
                type: Object,
                default () {
                    return {
                        pageNum: 1,
                        pageTotal: 50,
                        pageSize: 40,
                        showSizer: true
                    };
                }
            },
            pageSizeOpts: {
                type: Array,
                default: function () {
                    return [20, 40, 50, 100];
                }
            },
            size: {
                type: String,
                default: 'small'
            },
            columns: {
                type: Array,
                required: true
            },
            // table数据
            data: {
                type: Array,
                default () {
                    return [];
                }
            },
            // 获取数据的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) => {}
            },
            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
            },
            // 已选n项，距左端距离
            tableFunML: {
                type: Number,
                default: 120
            },
            // 是否存在已选n项
            isShowTableFun: {
                type: Boolean,
                default: true
            },
            // 是否自定义按钮
            isCustomBtn: {
                type: Boolean,
                default: false
            }
        },
        components: {
            AgGridVue,
            bingoToolbar,
            bingoModalEdit,
            bingoForm,
            bingoGridItem
        },
        computed: {
            actionClass () {
                return 'action-' + this.showBtnType;
            }
        },
        data () {
            return {
                rules: {
                    name: [
                        {
                            required: true,
                            message: '请输入模板名称',
                            trigger: 'blur'
                        }
                    ]
                },
                layoutValue: '',
                layoutModal: false,
                layoutDetail: {
                    pageSize: 40,
                    defaultValue: 0,
                    name: ''
                },
                layoutList: [],
                fullModal: false,
                loading: false,
                sHeight: 0,
                tHeight: 0,
                zHeigth: 0,
                selection: [],
                orderBy: '',
                fullFlag: false,
                params: {},
                currentLayout: [],
                columnDefs_column: [
                    {
                        field: '移动',
                        width: 50,
                        suppressMenu: true,
                        headerClass: 'header-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, },
                ],
                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'
                },
                defaultColDef_column: { resizable: true },
                modules: AllModules,
                columnsList: [],
                tableData: [],
                isShowHeadFun: false,
                item: [],
                showFlag: [],
                newAddBtns: false
            };
        },
        mounted () {
            if (this.isCustomData) {
                this.tableData = this.data;
            }
            this.changeHeight();
            // if (!this.query) {
            //     this.sHeight = 0;
            // } else {
            //     this.sHeight = 65;
            // }
            this.sHeight = this.topHeight;
            if (this.layoutShow) {
                this.getLayout();
            }
            this.toChangeColumn(this.columns);
            // this.$nextTick(()=>{
            //     this.renderHeaderFilter();
            // })

            this.$on('on-ok-add-confirm', this.onOkAddConfirm);
            this.$on('get-table-data', this.getTableData); // 刷新
            // 获取table数据
            this.getTableData();
        },
        watch: {
            // 监听表格数据
            data (val) {
                this.tableData = val;
            },
            fullFlag () {
                if (this.bill) {
                    if (this.fullFlag) {
                    } else {
                        this.zHeigth = 0;
                    }
                }
            },
            columns () {
                this.toChangeColumn(this.columns);
            },
            fullScreen (val) {
                this.fullFlag = val;
            }
        },
        methods: {
            // 获取table数据
            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) => {
                        this.tableData = res.rows ? res.rows : res;
                        this.pageSetting.pageTotal = res.total;
                        if (
                            this.processData &&
                            typeof this.processData === 'function'
                        ) {
                            this.processData.apply(this, [this.tableData, this]);
                        }
                        this.loading = false;
                        // 操作
                        this.handleMatch();
                    });
                }
            },
            // 操作
            handleMatch () {
                if (this.isCustomBtn) {
                    return false;
                }
                let _this = this;
                setTimeout(function () {
                    for (let k = 0; k < _this.tableData.length; k++) {
                        let ule = _this.$refs[`actionBtns${k}`];
                        if (!ule) {
                            return false;
                        }
                        if (_this.showBtnOutNum < ule.children.length - 1) {
                            _this.$set(_this.showFlag, k, true);
                            _this.$nextTick(() => {
                                let cloneUle = ule.cloneNode(true);
                                let ure = _this.$refs[`dropMenu${k}`].$el;
                                for (
                                    let i = ule.children.length - 2;
                                    i >= _this.showBtnOutNum;
                                    i--
                                ) {
                                    ule.removeChild(ule.children[i]);
                                }
                                if (_this.showBtnOutNum >= 2) {
                                    for (
                                        let i = 0;
                                        i < _this.showBtnOutNum - 2;
                                        i++
                                    ) {
                                        ure.removeChild(ure.children[0]);
                                    }
                                } else {
                                    let arr = [];
                                    for (
                                        let i = cloneUle.children.length - 2;
                                        i >= _this.showBtnOutNum;
                                        i--
                                    ) {
                                        ure.appendChild(cloneUle.children[i]);
                                    }
                                }
                                _this.newAddBtns = true;
                            });
                        } else {
                            _this.newAddBtns = true;
                        }
                    }
                }, 500);
            },
            onOkAddConfirm (cmponent) {
                if (this.onOkAdd && typeof this.onOkAdd === 'function') {
                    let _this = this;
                    this.onOkAdd.call(this, this.tableData, cmponent, function () {
                        _this.getTableData();
                    });
                }
            },
            toChangeColumn (columns) {
                this.columnsList = [];
                if (columns.length > 0) {
                    for (let item of columns) {
                        // if (
                        //     !item.sortable &&
                        //     item.type != "index" &&
                        //     item.title != "操作"
                        // ) {
                        //     item.sortable = true;
                        // }
                        // if (
                        //     this.resizable &&
                        //     item.type != "index" &&
                        //     item.title != "操作"
                        // ) {
                        //     item.resizable = true;
                        // }
                        item.resizable = true;
                        if (item.type == 'selection' || item.type == 'index') {
                            item.width = '42';
                            item.resizable = false;
                            item.sortable = false;
                        }
                        if (item.type == 'index') {
                            item.width = '65';
                            item.resizable = false;
                            item.sortable = false;
                        }
                        if (item.slot == 'action') {
                            item.resizable = false;
                            item.sortable = false;
                            item.fixed = 'right';
                        }
                        // if(!item.filterMethod&&item.type!="index"&&item.title!="操作"){
                        //     item.filters=[]
                        //     item.filterMethod=function (value, row){
                        //         debugger
                        //         return row.address.indexOf(value) > -1;
                        //     }
                        // }
                        if (!item.hide) {
                            this.columnsList.push(item);
                        }
                    }
                }
            },
            onGridReady_column (params) {
                this.gridApi_column = params.api;
                this.gridApi_column.sizeColumnsToFit();
            },
            layoutChange (layoutValue) {
                if (layoutValue && layoutValue != '') {
                    this.getLayoutInfo(layoutValue);
                } else {
                    this.toChangeColumn(this.columns);
                }
            },
            syncCurrentLayout () {
                // this.currentLayout=this.gridApi.columnController.getColumnState()
                for (let item of this.columnsList) {
                    let data = {};
                    if (item.type == 'selection') {
                        data = {
                            aggFunc: null,
                            colId: '多选框',
                            hide: item.hide,
                            pinned: item.fixed,
                            pivotIndex: null,
                            rowGroupIndex: null,
                            width: item.width,
                            sort: item.sort,
                            colName: '多选框'
                        };
                    } else if (item.colId == 'index') {
                        data = {
                            aggFunc: null,
                            colId: '序号',
                            hide: item.hide,
                            pinned: item.fixed,
                            pivotIndex: null,
                            rowGroupIndex: null,
                            width: item.width,
                            sort: item.sort,
                            colName: '序号'
                        };
                    } else {
                        data = {
                            aggFunc: null,
                            colId: item.key,
                            hide: item.hide,
                            pinned: item.fixed,
                            pivotIndex: null,
                            rowGroupIndex: null,
                            width: item.width,
                            sort: item.sort,
                            slot: item.slot,
                            colName: item.title
                        };
                    }

                    this.currentLayout.push(data);
                }
            //  this.rowData_column=this.currentLayout;
            },
            openLayout () {
                this.layoutModal = true;
                if (this.layoutValue && this.layoutValue != '') {
                    this.getLayoutInfo(this.layoutValue);
                } else {
                    this.syncCurrentLayout();
                    this.layoutDetail = {
                        pageSize: 40,
                        defaultValue: 0,
                        name: ''
                    };
                }
            },
            getLayoutInfo (layoutValue) {
                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;
                    for (let column of this.currentLayout) {
                        if (column.colId == '多选框' || column.colId == '0') {
                            column.colId = '0';
                            column.colName = '多选框';
                            column.pinned = 'left';
                            column.flag = '0';
                        } else if (
                            column.colName == '序号' ||
                            column.colId == '1'
                        ) {
                            column.colId = '1';
                            column.colName = '序号';
                            column.pinned = 'left';
                        } else if (
                            column.colId == '"action"' ||
                            column.colName == '操作'
                        ) {
                            column.pinned = 'left';
                            column.flag = '0';
                        }
                        for (let item of this.columns) {
                            if (column.colId == item.key) {
                                column.colName = item.title;
                            }
                        }
                        console.log(column, this.columnsList);
                    }

                    // this.gridApi.columnController.setColumnState(this.currentLayout)
                    this.orderBy = '';
                    for (let item of this.currentLayout) {
                        if (item.sort) {
                            this.orderBy = item.colId + ' ' + item.sort;
                            item.sortType = item.sort;
                            debugger;
                            break;
                        }
                    }
                    console.log(this.orderBy);
                    if (this.layoutDetail.pageSize) {
                        this.pageSetting.pageSize = this.layoutDetail.pageSize;
                    }
                    let data = {};
                    let list = [];
                    for (let item of this.currentLayout) {
                        if (
                            item.colId == '多选框' ||
                            item.colId == '0' ||
                            item.colName == '多选框'
                        ) {
                            data = {
                                type: 'selection',
                                title: item.colName,
                                key: item.colId,
                                width: item.width,
                                slot: item.slot,
                                fixed: item.pinned,
                                align: item.colName,
                                hide: item.hide,
                                sort: item.sort
                            };
                        } else if (
                            item.colId == '序号' ||
                            item.colId == '1' ||
                            item.colName == '序号'
                        ) {
                            data = {
                                type: 'index',
                                title: item.colName,
                                key: item.colId,
                                width: item.width,
                                slot: item.slot,
                                fixed: item.pinned,
                                align: item.colName,
                                hide: item.hide,
                                sort: item.sort
                            };
                        } else {
                            data = {
                                title: item.colName,
                                key: item.colId,
                                width: item.width,
                                sortType: item.sortType,
                                slot: item.slot,
                                fixed: item.pinned,
                                align: item.align,
                                hide: item.hide,
                                sort: item.sort
                            };
                        }
                        list.push(data);
                    }
                    this.toChangeColumn(list);
                    // this.$emit('getData');
                });
            },
            getLayout () {
                let params = {
                    userId: this.$store.state.admin.user.info.data.userId,
                    tableName: this.layoutName
                };
                Api.getUserLayout(params).then((res) => {
                    this.layoutList = res.data;
                    for (let item of this.layoutList) {
                        if (item.defaultValue == 1 || item.defaultValue == '1') {
                            this.layoutValue = item.name;
                            this.getLayoutInfo(this.layoutValue);
                        }
                    }
                });
            },
            delLayout () {
                if (this.layoutValue == '') {
                    this.$Message.warning('不能删除默认布局');
                    return;
                }
                let params = { id: this.layoutDetail.id };
                Api.delLayoutSave(params).then((res) => {
                    this.$Message.success('删除成功');
                    this.layoutModal = false;
                    this.getLayout();
                });
            },
            addLayout () {
                (this.layoutDetail = {
                    pageSize: 40,
                    defaultValue: 0,
                    name: ''
                }),
                (this.layoutList = []);
            },
            saveLayout () {
                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.getLayout();
                        this.layoutValue = '';
                    }
                // this.layoutList = res.data;
                });
            },
            saveLayoutClose () {
                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 = '';
                    }
                });
            },
            onCancel () {
                this.layoutModal = false;
                if (this.layoutValue == '' || !this.layoutValue) {
                    this.syncCurrentLayout();
                }
            },
            renderHeaderFilter () {
                let allHeader = document.querySelectorAll(
                    '.ivu-table-header .ivu-table-cell'
                );
                console.log(allHeader);

                allHeader.forEach((element) => {
                    let createNew = document.createElement('div');
                    createNew.classList.add('vue-header-filter');
                    createNew.innerHTML =
                        ' <Poptip trigger="click">\n' +
                        '        <i class="ivu-icon ivu-icon-md-settings"></i>\n' +
                        '    </Poptip>';
                    element.appendChild(createNew);
                // new Vue({
                //     render(h){
                //         return h(TableHeaderFilter,{
                //             props:{}
                //         })
                //     }
                // }).$mount(createNew);
                });
            },
            getParams () {
                let orderBy = {},
                    pageParams = {};
                if (
                    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 () {
                this.loading = !this.loading;
            },
            handleResize () {
                this.changeHeight();
            },
            changeHeight () {
                if (this.toolbar) {
                    this.tHeight =
                        this.$refs['table-list'].offsetHeight -
                        this.$refs['toolbar'].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.pageSetting.pageNum = page;
                this.getTableData();
            // this.$emit("getData");
            },
            pagesizechange (pageSize) {
                this.pageSetting.pageSize = pageSize;
                this.pageChange(1);
            },
            // 选中某一项
            onSelect (selection, row) {
                this.selection = selection;
            },
            onSelectCancel (selection, row) {
                this.$emit('on-select-cancel', selection, row);
            },
            onSelectAll (selection) {
                this.selection = selection;
            },
            onSelectAllCancel (selection) {
                this.$emit('on-select-all-cancel', selection);
            },
            onSelectionChange (selection) {
                if (selection.length > 0) {
                    this.isShowHeadFun = true;
                } else {
                    this.isShowHeadFun = false;
                }
                this.selection = selection;
                this.$emit('on-selection-change', selection);
            },
            // 新建
            newClick (selection) {
                this.$emit('on-new');
            },
            // 刷新
            // onRefresh () {
            //     this.$emit('getData');
            // },
            // getData (searchObj) {
            //     this.$emit('getData');
            // },
            onRowClick (row) {
                this.$emit('on-row-click', row);
            },
            onDelete (selection) {
                this.$emit('on-delete');
            },
            onSortChange (data) {
                if (data.order == 'normal') {
                    this.orderBy = '';
                } else {
                    this.orderBy = data.key + ' ' + data.order;
                }
                // this.$emit('getData');
            },
            // 全屏
            openFullModal (fullFlag) {
                this.fullFlag = fullFlag;
                // this.fullFlag = !this.fullFlag;
                this.$emit('open-full-modal', this.fullFlag);
            },
            onCurrentChange (newValue, oldValue) {
                this.$emit('on-current-change', newValue, oldValue);
            },
            // onDragDrop(a, b) {
            //     this.$parent("onDragDrop", a, b);
            // },
            // 拖拽换位置
            onDragDrop (first, end) {
                // console.log(first)
                // this.onDragResult(this.tableData,first,end)
            },
            // onDragResult(data,first,end){
            //     data.splice(
            //         end,
            //         1,
            //         ...data.splice(first, 1, data[end])
            //     );
            //     this.tableData.forEach(item=>{
            //         if(item.children){
            //             this.onDragResult(item.children,first,end)
            //         }
            //     })
            // },
            // --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;
            // })
            },
            // 单个编辑
            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');
                        });
                    }
                });
            },
            // 批量删除
            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');
                        });
                    }
                });
            }
        }
    };
</script>
