<template>
    <div>
        <slot name="header">
        </slot>
        <Form v-if="tableView.filterEnable"
            :model="filter"
            :label-width="120"
            label-colon="："
            class="filter"
            @submit.native.prevent>
            <Row :gutter="24"
                type="flex"
                justify="end">
                <slot name="filter"
                    :table="this"
                    :filter="filter">
                    <slot name="customFilter">
                    </slot>
                    <table-filter :data="filter"
                        :columns="filterColumns"
                        :keywordEnable="tableView.keywordEnable"
                        @on-keyup="onKeyup" />
                    <Col v-bind="grid6">
                    <FormItem :label-width="0">
                        <Button type="info"
                            v-if="tableView.keywordEnable||filterColumns.length>0"
                            custom-icon="fa fa-search"
                            @click="loadData()"
                            size="small">查询</Button>
                        <Button type="primary"
                            v-if="tableView.createEnable"
                            custom-icon="fa fa-plus"
                            @click="create()"
                            size="small">新建</Button>
                        <slot name="filterCommand"></slot>
                        <Dropdown v-if="tableView.exportEnable||tableView.exportPdfEnable||tableView.printEnable"
                            style="margin-left: 4px"
                            @on-click="moreClick">
                            <Button type="info"
                                size="small">
                                更多...
                                <Icon type="ios-arrow-down" />
                            </Button>
                            <DropdownMenu slot="list">
                                <DropdownItem v-if="tableView.exportEnable"
                                    name="exportExcel">导出 Excel</DropdownItem>
                                <DropdownItem v-if="tableView.exportPdfEnable"
                                    name="exportPdf">导出 PDF</DropdownItem>
                                <DropdownItem v-if="tableView.printEnable"
                                    name="print">打印</DropdownItem>
                            </DropdownMenu>
                        </Dropdown>
                        <Button type="error"
                            title="筛选设置"
                            custom-icon="fa fa-filter"
                            size="small"
                            v-if="settingEnable && allow('permission/tableView')"
                            @click="filterSettingOpen" />
                    </FormItem>
                    </Col>
                </slot>
            </Row>
        </Form>
        <div class="i-table-no-border">
            <Table class=""
                ref="table"
                size="small"
                stripe
                row-key="id"
                :indent-size="18"
                :update-show-children="treeEnable"
                :columns="columns"
                :data="data"
                :max-height="maxHeight"
                :load-data="onLoadData"
                no-data-text="暂无数据..."
                @on-column-width-resize="columnWidthResize"
                @on-sort-change="sortChange"
                @on-select="select"
                @on-select-cancel="selectCancel"
                @on-select-all="selectAll"
                @on-select-all-cancel="selectAllCancel">
                <template slot-scope="{ row, column, index }"
                    slot="normal">
                    <template v-if="column.controlType === 'Label'">
                        <div v-html="showData(row, column.code, column.dataType, column.displayFormat)"></div>
                    </template>
                    <template v-else-if="column.controlType === 'TextInput'">
                        <Input type="text"
                            size="small"
                            :value="parseData(data[index], column.code)"
                            @input="($event)=>setData(data[index], column.code, $event)"
                            :style="{ width: column.controlWidth == null ? null : ((column.controlWidth - 36) + 'px') }"
                            :maxlength="column.maxLength"
                            :pattern="column.pattern"
                            :placeholder="column.description"
                            @on-change="onDataChange(column)" />
                    </template>
                    <template v-else-if="column.controlType === 'NumberInput'">
                        <Input type="number"
                            size="small"
                            number
                            :value="parseData(data[index], column.code)"
                            @input="($event)=>setData(data[index], column.code, $event)"
                            :style="{ width: column.controlWidth == null ? null : ((column.controlWidth - 36) + 'px') }"
                            :placeholder="column.description"
                            @on-change="onDataChange(column)" />
                    </template>
                    <template v-else-if="column.controlType === 'Select'">
                        <Select size="small"
                            :value="parseData(data[index], column.code)"
                            @input="($event)=>setData(data[index], column.code, $event)"
                            :style="{ width: column.controlWidth == null ? null : ((column.controlWidth - 36) + 'px') }"
                            :placeholder="column.description"
                            :transfer="true"
                            @on-change="onDataChange(column)">
                            <Option v-for="item in getDataSource(data[index], column)"
                                :key="item.id"
                                :value="item.id">{{ item.name }}</Option>
                        </Select>
                    </template>
                    <template v-else-if="column.controlType === 'ComboSelect'">
                        <Select size="small"
                            :value="parseData(data[index], column.code)"
                            @input="($event)=>setData(data[index], column.code, $event)"
                            clearable
                            filterable
                            remote
                            :remote-method="(search)=>loadOption(data[index], column, search)"
                            :style="{ width: column.controlWidth == null ? null : ((column.controlWidth - 36) + 'px') }"
                            :placeholder="column.description"
                            :transfer="true"
                            @on-change="onDataChange(column)">
                            <Option v-for="item in getDataSource(data[index], column)"
                                :key="item.id"
                                :value="item.id">{{ item.name }}</Option>
                        </Select>
                    </template>
                    <template v-else-if="column.controlType === 'DialogSelect'">
                        <Input size="small"
                            type="text"
                            readonly
                            clearable
                            :value="showSelected(data[index], column)"
                            :style="{ width: column.controlWidth == null ? null : ((column.controlWidth - 36) + 'px') }"
                            @on-focus="dialogSelectOpen(data[index], column)"
                            @on-clear="dialogSelectRemove(data[index], column)">
                        <Button slot="prepend"
                            custom-icon="fa fa-search"
                            @click="dialogSelectOpen(data[index], column)"></Button>
                        </Input>
                    </template>
                    <template
                        v-else-if="column.controlType === 'Date' || column.controlType === 'DateTime' || column.controlType === 'Year' || column.controlType === 'Month' || column.controlType === 'DateRange'">
                        <DatePicker size="small"
                            :type="column.controlType.toLowerCase()"
                            :value="parseData(data[index], column.code)"
                            @input="($event)=>setData(data[index], column.code, $event)"
                            :placeholder="column.description"
                            :style="{ width: column.controlWidth == null ? null : ((column.controlWidth - 36) + 'px') }"
                            :transfer="true"
                            @on-change="onDataChange(column)"></DatePicker>
                    </template>
                    <template v-else-if="column.controlType === 'Time'">
                        <TimePicker size="small"
                            type="time"
                            :value="parseData(data[index], column.code)"
                            @input="($event)=>setData(data[index], column.code, $event)"
                            :placeholder="column.description"
                            :style="{ width: column.controlWidth == null ? null : ((column.controlWidth - 36) + 'px') }"
                            :transfer="true"
                            @on-change="onDataChange(column)"></TimePicker>
                    </template>
                    <template v-else-if="column.controlType === 'Check'">
                        <Checkbox :value="!!parseData(data[index], column.code)"
                            @input="($event)=>setData(data[index], column.code, $event)"
                            @on-change="onDataChange(column)" />
                    </template>
                    <template v-else-if="column.controlType === 'Switch'">
                        <Switch :value="!!parseData(data[index], column.code)"
                            @input="($event)=>setData(data[index], column.code, $event)"
                            @on-change="onDataChange(column)" />
                    </template>
                    <template v-else-if="column.controlType === 'Radio'">
                        <RadioGroup :value="parseData(data[index], column.code)"
                            @input="($event)=>setData(data[index], column.code, $event)"
                            @on-change="onDataChange(column)">
                            <Radio v-for="item in getDataSource(data[index], column)"
                                :key="item.id"
                                :label="item.id">
                                <span>{{ item.name }}</span>
                            </Radio>
                        </RadioGroup>
                    </template>
                    <template v-else-if="column.controlType === 'CheckGroup'">
                        <CheckboxGroup :value="parseData(data[index], column.code)"
                            @input="($event)=>setData(data[index], column.code, $event)"
                            @on-change="onDataChange(column)">
                            <Checkbox v-for="item in getDataSource(data[index], column)"
                                :key="item.id"
                                :label="item.id">
                                <span>{{ item.name }}</span>
                            </Checkbox>
                        </CheckboxGroup>
                    </template>
                    <template v-else-if="column.controlType === 'TextArea'">
                        表格中不支持此控件
                    </template>
                    <template v-else-if="column.controlType === 'RichEditor'">
                        表格中不支持此控件
                    </template>
                    <template v-else-if="column.controlType === 'Attachment'">
                        表格中不支持此控件
                    </template>
                    <template v-else-if="column.controlType === 'Image'">
                        表格中不支持此控件
                    </template>
                    <template v-else-if="column.controlType === 'Slider'">
                        <Slider :value="parseData(data[index], column.code)"
                            @input="($event)=>setData(data[index], column.code, $event)"
                            show-input
                            :style="{ width: column.controlWidth == null ? null : ((column.controlWidth - 36) + 'px') }"
                            :max="column.MaxValue"
                            :min="column.MinValue" />
                    </template>
                    <template v-else-if="column.controlType === 'Placeholder'">
                    </template>
                </template>
                <div slot-scope="{ row, index }"
                    slot="command">
                    <Button v-if="tableView.editEnable"
                        size="small"
                        title="编辑"
                        type="primary"
                        custom-icon="fa fa-edit"
                        @click="edit(row, index)"></Button>
                    <Button v-if="tableView.removeEnable"
                        size="small"
                        title="删除"
                        type="warning"
                        custom-icon="fa fa-trash-alt"
                        @click="remove(row)"></Button>
                    <slot name="command"
                        :row="row"
                        :index="index"></slot>
                </div>
                <div slot-scope="{ index }"
                    slot="sn">
                    {{ size * (current - 1) + index + 1 }}
                </div>
            </Table>
            <div class="ivu-mt ivu-text-right">
                <Button class="ivu-fr"
                    type="error"
                    title="设置"
                    custom-icon="fa fa-cog"
                    v-if="settingEnable && allow('permission/tableView')"
                    @click="tableSettingOpen">
                </Button>
                <Page show-sizer
                    show-total
                    :current.sync="current"
                    :page-size="size"
                    :page-size-opts="[10, 20, 50, 100]"
                    :total="total"
                    v-if="tableView.pageEnable"
                    @on-change="loadData()"
                    @on-page-size-change="pageSizeChange" />
            </div>
            <modal-table ref="dialogTable"
                v-if="dialogActive">
                <template slot-scope="{ row }"
                    slot="command">
                    <Button size="small"
                        title="选择"
                        type="primary"
                        custom-icon="fa fa-check-square-o"
                        @click="dialogCheck(row)"></Button>
                </template>
            </modal-table>
            <table-setting ref="tableSetting"
                v-if="tableSettingActive"
                :is-setting="true"
                @on-change="(viewCode)=>init(viewCode)" />
            <filter-setting ref="filterSetting"
                v-if="filterSettingActive"
                @on-change="(viewCode)=>init(viewCode)" />
        </div>
    </div>
</template>
<script>
    import { mapActions } from 'vuex';
    import modelApi from '../../api/model';
    import customModelApi from '../../api/customModel';
    import dataSourceApi from '../../api/dataSource';
    import dataViewApi from '../../api/dataView';
    import mixinPage from '../../mixins/page';
    import mixin from './mixin';
    import tableSetting from './table-setting';
    import filterSetting from './filter-setting';
    import tableFilter from './table-filter';

    export default {
        mixins: [mixin, mixinPage],
        components: { tableFilter, tableSetting, filterSetting },
        data() {
            return {
                inited: false,
                size: 10,
                orderBy: null,
                tableView: {},
                columns: [],
                viewFilter: {},
                filterColumns: [],
                data: [],
                staticData: [],
                selectedData: [],
                current: 1,
                total: 0,
                setting: false,
                dialogActive: false,
                tableSettingActive: false,
                filterSettingActive: false
            };
        },
        async created() {
            // 默认视图代码
            if (this.viewCode) {
                // 初始化
                await this.init(this.viewCode);

                this.$emit('after-init');
            }

            if (this.viewCode && this.autoLoad) {
                this.loadData();
            }
        },
        activated() {
            if (this.viewCode && this.autoLoad) {
                this.loadData();
            }
        },
        props: {
            // 视图代码
            viewCode: {
                type: String
            },
            // 是否静态数据
            static: {
                type: Boolean,
                default: false
            },
            // 筛选
            filter: {
                type: Object,
                default() {
                    return {};
                }
            },
            // 是否允许配置界面
            settingEnable: {
                type: Boolean,
                default: true
            },
            // 自动加载
            autoLoad: {
                type: Boolean,
                default: true
            },
            // 是否允许选择
            selectEnable: {
                type: Boolean,
                default: false
            },
            // 是否允许树展开
            treeEnable: {
                type: Boolean,
                default: false
            },
            // 树展开动作
            treeLoad: {
                type: Function
            },
            // 树包含子项
            hasChildren: {
                type: Function
            },
            // 高度
            height: {
                type: Number,
                default: null
            }
        },
        computed: {
            // 表格最大高度，固定表头
            maxHeight() {
                if (this.height == null) {
                    return document.body.offsetHeight - 400;
                } else {
                    return this.height;
                }
            }
        },
        watch: {
            // staticData() {
            //     // 设置选中项
            //     if (typeof this.selectFunc === 'function') {
            //         let selected = this.staticData.filter(this.selectFunc);
            //         this.setSelected(selected);
            //     }
            // }
        },
        methods: {
            ...mapActions('admin/dataView', { loadDataView: 'load' }),
            // 初始化
            async init(viewCode, callback) {
                // 加载表格视图
                let view = await this.loadDataView(viewCode);

                if (view == null) {
                    console.log(viewCode + '不存在！');
                }

                this.tableView = view.dataView;
                this.tableView.columns = view.viewColumns;
                this.tableView.filterColumns = view.filterColumns;
                this.$emit('on-ready', this.tableView);
                this.filterColumns = view.filterColumns;
                this.columns = view.viewColumns.map((item, index) => {
                    return {
                        ...item,
                        title: item.name,
                        renderHeader: (h, params) => {
                            return h('span', {
                                domProps: {
                                    innerHTML: params.column.name.replace('|', '<br/>')
                                }
                            });
                        },
                        // tree: this.treeEnable && index == 0, // 需要树展开，给第一列添加展开按钮
                        key: item.code,
                        dataType: item.dataType,
                        format: item.displayFormat,
                        width: item.controlWidth,
                        minWidth: 100,
                        align: item.align ? item.align.toLowerCase() : 'Center',
                        sortable: 'custom',
                        resizable: true,
                        slot: 'normal'
                    };
                });
                if (this.tableView.snEnable) {
                    this.columns.unshift({
                        title: '序号',
                        slot: 'sn',
                        align: 'center',
                        width: 60
                    });
                }

                if (this.tableView.commandEnable) {
                    this.columns.unshift({
                        title: ' ',
                        slot: 'command',
                        align: 'center',
                        width: this.tableView.commandWidth == null ? 90 : (this.tableView.commandWidth + 1) * 30,
                        fixed: 'right'
                    });
                }

                if (this.selectEnable) {
                    this.columns.unshift({
                        type: 'selection',
                        align: 'center',
                        width: 60
                    });
                }
                if (this.treeEnable) {
                    this.columns.unshift({
                        tree: true,
                        display: 'inline',
                        align: 'left',
                        width: 100
                    });
                }

                // 默认每页数据量
                if (this.tableView.size) {
                    this.size = this.tableView.size;
                } else if (this.tableView.pageEnable) {
                    this.size = 10;
                } else {
                    this.size = 1000;
                }

                if (this.tableView.sorting) {
                    // 排序
                    let obj = JSON.parse(this.tableView.sorting);
                    let arr = [];
                    for (let key in obj) {
                        if (obj[key] === 'desc') {
                            arr.push('-' + key);
                        } else {
                            arr.push('+' + key);
                        }
                    }

                    this.orderBy = arr.join(',');
                }

                if (this.tableView.filtering) {
                    // 排序
                    let obj = JSON.parse(this.tableView.filtering);
                    for (let key in obj) {
                        this.viewFilter[key] = obj[key];
                    }
                }

                this.inited = true;

                if (typeof callback === 'function') {
                    callback();
                }
            },
            // 加载数据
            async loadData(staticData) {
                if (!this.inited) {
                    await this.init(this.viewCode);
                }

                if (staticData) {
                    this.staticData = this.copy(staticData);
                }

                if (this.static) {
                    this.total = this.staticData.length;

                    let offset = (this.current - 1) * this.size;
                    this.data = offset + this.size >= this.staticData.length ? this.staticData.slice(offset, this.staticData.length) : this.staticData.slice(offset, offset + this.size);
                } else {
                    let data = {
                        ...this.getAllFilter(),
                        page: this.current,
                        per: this.size,
                        orderBy: this.orderBy
                    };

                    if (this.tableView.isCustom) {
                        let res = await customModelApi.query(this.tableView.model, data);

                        this.total = res.totalCount;
                        this.data = res.data;
                    } else if (this.tableView.isDataSource) {
                        let res = await dataSourceApi.query(this.tableView.dataSource, data);

                        this.total = res.totalCount;
                        this.data = res.table;
                    } else {
                        let res = await modelApi.query(this.tableView.model, data, this.tableView.functionName, this.tableView.functionType);

                        this.total = res.totalCount;
                        this.data = res.data;
                    }

                    // 如果超出页码，设为最后一页
                    if (this.current > Math.ceil(this.total / this.size)) {
                        this.current = Math.ceil(this.total / this.size);
                    }

                    // 最小为第一页
                    if (this.current <= 0) {
                        this.current = 1;
                    }

                    // 设置选中项
                    this.data.forEach(item => {
                        item._checked = this.selectedData.some(i => {
                            return item.id === i.id;
                        });
                    });
                    // if (typeof this.selectFunc === 'function') {
                    //     let selected = this.data.filter(this.selectFunc);
                    //     this.setSelected(selected);
                    // }
                }

                // 如果这行数据有子集，需要添加展开加载方法
                if (this.treeEnable) {
                    this.data.forEach(item => {
                        if (this.hasChildren == null || this.hasChildren(item)) {
                            item._loading = false;
                            item.children = [];
                        }
                    });

                    this.data = this.copy(this.data);
                }

                // 加载数据源
                this.initDataSource();

                this.$emit('on-load-data');
            },
            // 点击更多按钮
            async moreClick(name) {
                if (!this.inited) {
                    await this.init(this.viewCode);
                }

                if (this.static) {
                    if (name === 'exportExcel') {
                        dataViewApi.exportExcel(this.tableView, this.staticData);
                    } else if (name === 'exportPdf') {
                        dataViewApi.exportPdf(this.tableView, this.staticData);
                    } else if (name === 'print') {
                        dataViewApi.print(this.tableView, this.staticData);
                    }
                } else {
                    if (name === 'exportExcel') {
                        this.exportExcel();
                    } else if (name === 'exportPdf') {
                        this.exportPdf();
                    } else if (name === 'print') {
                        this.print();
                    }
                }
            },
            // 导出Excel
            exportExcel() {
                let data = {
                    ...this.getAllFilter(),
                    orderBy: this.orderBy
                };

                if (this.tableView.isCustom) {
                    customModelApi.exportExcel(this.tableView, data);
                } else if (this.tableView.isDataSource) {
                    dataSourceApi.exportExcel(this.tableView, data);
                } else {
                    modelApi.exportExcel(this.tableView, data);
                }
            },
            // 导出PDF
            exportPdf() {
                let data = {
                    ...this.getAllFilter(),
                    orderBy: this.orderBy
                };

                if (this.tableView.isCustom) {
                    customModelApi.exportExcel(this.tableView, data);
                } else if (this.tableView.isDataSource) {
                    dataSourceApi.exportPdf(this.tableView, data);
                } else {
                    modelApi.exportPdf(this.tableView, data);
                }
            },
            // 打印
            print() {
                let data = {
                    ...this.getAllFilter(),
                    orderBy: this.orderBy
                };

                if (this.tableView.isCustom) {
                    customModelApi.exportExcel(this.tableView, data);
                } else if (this.tableView.isDataSource) {
                    dataSourceApi.printList(this.tableView, data);
                } else {
                    modelApi.printList(this.tableView, data);
                }
            },
            // 加载数据源
            initDataSource() {
                this.columns.forEach(column => {
                    if (column.source != null && column.source.trim() !== '') {
                        if (column.controlType === 'Select' || column.controlType === 'Radio') {
                            this.data.forEach(row => {
                                let param = this.getParam(row, column);

                                // 选择框、单选框组
                                if (param != null) {
                                    this.fillDataSource(row, column, param);
                                }
                            });
                        }
                    }
                });
            },
            // 填充数据源
            async fillDataSource(data, column, param) {
                if (!data.dataSource) {
                    data.dataSource = {};
                }

                // 参数完整，查询数据
                let res = await modelApi.query(column.source, param);

                data.dataSource[column.code] = res.data.map(item => {
                    return {
                        id: column.sourceDataCode == null || column.sourceDataCode.trim() === '' ? item.id : this.parseData(item, column.sourceDataCode),
                        name: this.parseData(item, column.sourceDisplayCode)
                    };
                });

                // 默认第一项
                if (data) {
                    if (this.parseData(data, column.code) == null && column.isDefaultFirst && res.length > 0) {
                        this.setData(data, column.code, this.parseData(res[0], column.sourceDataCode));
                    }
                }

                // 更新data触发刷新
                this.data = this.data.map(item => {
                    return item;
                });

                // 触发
                this.onDataChange(column);
            },
            // 获取数据源
            getDataSource(data, column) {
                if (column.dataType.indexOf('Enum:') === 0) {
                    // 枚举
                    return this.getEnumList(column.dataType.split(':')[1]);
                } else if (data.dataSource != null && data.dataSource[column.code] != null) {
                    return data.dataSource[column.code];
                }
            },
            // 可筛选下拉框加载数据
            loadOption(data, column, keyword) {
                if (!data.dataSource) {
                    data.dataSource = {};
                }

                let param = this.getParam(data, column);

                if (param != null) {
                    if ((keyword == null || keyword.trim() === '') && this.parseData(data, column.code) != null) {
                        param.id = this.parseData(data, column.code);
                    } else {
                        param.keyword = keyword;
                    }
                    param.per = 20;

                    this.fillDataSource(data, column, param);
                } else {
                    // 参数不完整，清空数据
                    data.dataSource[column.code] = [];
                    this.setData(data, column.code, null);
                    // column.displayValue = null;

                    // 触发
                    column.triggers.forEach(item => {
                        item.needRefresh = true;
                    });
                }
            },
            // 每页数量切换
            pageSizeChange(size) {
                this.size = size;
                this.loadData();
            },
            // 排序切换
            sortChange({ key, order }) {
                let orderColumns = [];
                if (this.orderBy) {
                    orderColumns = this.orderBy.split(',');
                }

                orderColumns = orderColumns.filter(item => {
                    return item.substring(1) !== key;
                });

                // 添加排序字段
                if (order === 'asc') {
                    orderColumns.unshift('+' + key);
                } else if (order === 'desc') {
                    orderColumns.unshift('-' + key);
                }

                this.orderBy = orderColumns.join(',');

                this.loadData();
            },
            columnWidthResize(newWidth, oldWidth, column, event) {
                console.log('columnWidthResize', newWidth, oldWidth, column, event);
            },
            // 创建新项
            create() {
                this.$emit('create');
            },
            // 编辑项
            edit(row, index) {
                this.$emit('edit', { row, index });
            },
            // 删除项
            remove(row) {
                this.confirm('确定要删除该项吗？', async () => {
                    if (this.tableView.isCustom) {
                        await customModelApi.remove(this.tableView.model, row.id);
                    } else {
                        await modelApi.remove(this.tableView.model, row.id);
                    }

                    this.success('操作成功', () => {
                        this.loadData();
                    });
                });
            },
            // 数据变化事件
            onDataChange(data, sender, selected) {
                // if (this.onChange != null) {
                //     this.onChange(data, sender, selected);
                // }
            },
            // 获取默认值
            getDefaultData() {
                let data = {};

                this.columns.forEach(item => {
                    if (item.defaultValue) {
                        this.setData(data, item.code, item.defaultValue);
                    } else {
                        if (item.dataType === 'Boolean') {
                            this.setData(data, item.code, false);
                        } else {
                            this.setData(data, item.code, null);
                        }
                    }
                });

                return data;
            },
            // 添加新行
            addNew() {
                this.staticData.push(this.getDefaultData());
            },
            // 打开表格设置界面
            tableSettingOpen() {
                this.tableSettingActive = true;

                setTimeout(() => {
                    this.$refs.tableSetting.open(this.tableView, this.copy(this.tableView.columns));
                });
            },
            // 打开筛选设置界面
            filterSettingOpen() {
                this.filterSettingActive = true;

                setTimeout(() => {
                    this.$refs.filterSetting.open(this.tableView, this.copy(this.tableView.filterColumns));
                });
            },
            select(selection, row) {
                this.selectedData.push(row);
                this.$emit('on-select-change');
            },
            selectCancel(selection, row) {
                const index = this.selectedData.findIndex(item => item.id === row.id);
                this.selectedData.splice(index, 1);
                this.$emit('on-select-change');
            },
            selectAll(selection) {
                if (this.static) {
                    this.setSelected(this.staticData);
                } else {
                    let selected = this.copy(this.selectedData);

                    this.data.forEach(item => {
                        if (
                            !selected.some(i => {
                                return i.id == item.id;
                            })
                        ) {
                            selected.push(item);
                        }
                    });

                    this.setSelected(selected);
                }
                this.$emit('on-select-change');
            },
            selectAllCancel(selection) {
                if (this.static) {
                    this.setSelected([]);
                } else {
                    let selected = this.copy(this.selectedData);

                    this.data.forEach(item => {
                        const index = selected.findIndex(i => {
                            return i.id == item.id;
                        });

                        if (index != -1) {
                            selected.splice(index, 1);
                        }
                    });

                    this.setSelected(selected);
                }

                this.$emit('on-select-change');
            },
            // 获取选中项
            getSelected() {
                return this.selectedData;
            },
            // 设置选中项
            setSelected(selected) {
                this.selectedData = [];
                selected.forEach(item => {
                    this.selectedData.push(item);
                });

                if (this.static) {
                    this.staticData.forEach(item => {
                        item._checked = this.selectedData.some(i => {
                            return item.id === i.id;
                        });
                    });
                } else {
                    this.data.forEach(item => {
                        item._checked = this.selectedData.some(i => {
                            return item.id === i.id;
                        });
                    });
                }

                this.data = this.copy(this.data);
            },
            // 键盘事件
            onKeyup(e) {
                if (e) {
                    var keycode = window.event ? e.keyCode : e.which;

                    if (!keycode) {
                        return;
                    }

                    if (keycode !== 0 && keycode !== 1 && keycode !== 13) {
                        return;
                    }
                }

                this.loadData();
            },
            // 合并后最终的筛选项
            getAllFilter() {
                return {
                    ...this.viewFilter,
                    ...this.filter
                };
            },
            // 树展开动态查询
            async onLoadData(item, callback) {
                if (this.treeLoad != null) {
                    let data = await this.treeLoad(item);
                    data.forEach(item => {
                        if (this.hasChildren == null || this.hasChildren(item)) {
                            item._loading = false;
                            item.children = [addNew];
                        }
                    });

                    callback(data);
                }
            }
        }
    };
</script>
