"use strict";
var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var __assign = (this && this.__assign) || function () {
    __assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return __assign.apply(this, arguments);
};
Object.defineProperty(exports, "__esModule", { value: true });
var React = require("react");
var _ = require("lodash");
var antd_1 = require("antd");
var utils_1 = require("../../utils");
var dva_1 = require("dva");
var SearchBar_1 = require("./SearchBar");
var SelectBar_1 = require("./SelectBar");
var MIN_HEIGHT = 694;
var DEF_PAGE_SIZE = 15;
/**
 * VTable ： 最新的数据Table组件 建议用它来替代 DataTable 和 TableLayout
 *
*/
var VTable = /** @class */ (function (_super) {
    __extends(VTable, _super);
    function VTable(props) {
        var _this = _super.call(this, props) || this;
        _this.mode = 'common';
        _this.id = 'id_' + _.random(999999);
        _this.rowKey = 'id';
        _this.fetch = '';
        _this.param = {};
        _this.columns = [];
        _this.state = {
            selectedRowKeys: [],
            selectObjects: [],
            current: 1,
            pageSize: DEF_PAGE_SIZE,
            maxHeight: MIN_HEIGHT,
        };
        /**
         * 获取选中项
         */
        _this.getSelected = function () { return [_this.state.selectedRowKeys, _this.state.selectObjects]; };
        /**
         * 刷新当前页面
         *  */
        _this.reflush = function (param) {
            if (param === void 0) { param = {}; }
            _this.query(_.extend(_this.param, { start_: 0 }, param));
        };
        if (!_.has(_this.props, 'namespace')) {
            if (!_.has(_this.props, 'fetch') || !_.has(_this.props, 'total') || !_.has(_this.props, 'dataSource')) {
                console.error('参数 namespace 或 fetch/total/dataSource 缺失');
            }
        }
        _this.rowKey = _this.props.rowKey || 'id';
        _this.fetch = _this.props.fetch ? _this.props.fetch : (_this.props.namespace + '/_query');
        _this.columns = _.concat([], _.filter(_this.props.columns, function (item) { return item.show === undefined || item.show == true; }));
        if (_.has(_this.props, 'mode')) {
            _this.mode = _this.props.mode;
        }
        if (_this.props.showIndex !== false) {
            if (_this.props.showIndex === undefined || _this.props.showIndex === true) {
                _this.columns.unshift({
                    title: '序号',
                    className: '_index',
                    render: function (d, j, i) { return i + (_this.state.current - 1) * _this.state.pageSize + 1; }
                });
            }
            else if (_.isString(_this.props.showIndex)) {
                _this.columns.unshift({
                    title: _this.props.showIndex,
                    className: '_index',
                    render: function (d, j, i) { return i + (_this.state.current - 1) * _this.state.pageSize + 1; }
                });
            }
        }
        _.extend(_this.param, _this.props.default);
        return _this;
    }
    VTable.prototype.fetchData = function (param, callback) {
        if (callback === void 0) { callback = undefined; }
        var query = param;
        if (this.props.beforeSearch) {
            query = this.props.beforeSearch(query);
        }
        // @ts-ignore
        this.props.dispatch(_.extend({ type: this.fetch }, { query: query }, { callback: callback }));
    };
    VTable.prototype.componentDidMount = function () {
        if (this.props.autoLoad === false) {
            return;
        }
        this.fetchData(_.extend(this.param, { start_: 0, count_: this.state.pageSize }));
        this.reMax();
    };
    //重新设置表格的列，及序号设置，序号不传则为原序号
    VTable.prototype.setColumns = function (columns, showIndex) {
        var _this = this;
        if (showIndex === void 0) { showIndex = null; }
        this.columns = _.concat([], _.filter(columns, function (item) { return item.show === undefined || item.show == true; }));
        var index = this.props.showIndex;
        if (showIndex !== null) {
            index = showIndex;
        }
        if (index !== false) {
            if (index === undefined || index === true) {
                this.columns.unshift({
                    title: '序号',
                    className: '_index',
                    render: function (d, j, i) { return i + (_this.state.current - 1) * _this.state.pageSize + 1; }
                });
            }
            else if (_.isString(index)) {
                this.columns.unshift({
                    title: index,
                    className: '_index',
                    render: function (d, j, i) { return i + (_this.state.current - 1) * _this.state.pageSize + 1; }
                });
            }
        }
        this.param = _.extend({}, this.props.default);
        this.setState({ _t: _.now() });
    };
    /**
     * 获取当前查询参数
     */
    // getParam = () => this.param;
    /**
     * 查询
     *  */
    VTable.prototype.query = function (param, manaul) {
        if (manaul === void 0) { manaul = false; }
        _.extend(this.param, param, { start_: 0 });
        this.setState({ current: 1, selectedRowKeys: [], selectedRows: [], });
        if (manaul) {
            this.fetchData(_.extend({}, this.props.default, this.param));
            utils_1.Ajax.POST('/api-serversys/syslog/addSysLog', { type: 1, requestUrl: window.location.pathname + window.location.hash });
        }
        else {
            this.fetchData(_.extend({}, this.props.default, this.param));
        }
    };
    VTable.prototype.onSelect = function (selectedRowKeys, selectObjects) {
        this.setState({ selectedRowKeys: selectedRowKeys, selectObjects: selectObjects });
    };
    VTable.prototype.renderSelectBar = function () {
        var _this = this;
        if (!_.has(this.props, 'selectBar')) {
            return React.createElement(React.Fragment, null);
        }
        var style = {};
        if (this.mode == 'common') {
            style.maxHeight = this.state.maxHeight;
        }
        else {
            style.maxHeight = '100%';
        }
        return React.createElement(SelectBar_1.default, __assign({}, this.props.selectBar, { style: style, onSelect: function (sel, parent) {
                var result = _this.props.selectBar.onSelect(sel, parent);
                if (_.isPlainObject(result)) {
                    _this.query(result);
                    // console.log(result);
                }
            } }));
    };
    VTable.prototype.reMax = function () {
        if (this.props.selectBar || this.mode != 'common') {
            var layout = document.getElementById(this.id);
            var height = 0;
            var searchBar = layout.getElementsByClassName('vap-table-search-bar');
            var table = layout.getElementsByClassName('ant-table-wrapper');
            var page = layout.getElementsByClassName('vap-table-pagination');
            if (searchBar.length == 1) {
                // @ts-ignore
                height += searchBar[0].offsetHeight;
            }
            if (searchBar.length == 1) {
                // @ts-ignore
                height += table[0].offsetHeight;
            }
            if (page.length == 1) {
                // @ts-ignore
                height += page[0].offsetHeight;
            }
            if (height <= MIN_HEIGHT) {
                height = MIN_HEIGHT;
            }
            this.setState({ maxHeight: height });
        }
    };
    VTable.prototype.renderSearchBar = function () {
        var _this = this;
        if (!_.has(this.props, 'searchBar')) {
            return React.createElement(React.Fragment, null);
        }
        return React.createElement(SearchBar_1.default, __assign({ onSearch: function (param) { return _this.query(param, true); }, default: this.props.default }, this.props.searchBar, { selectedRowKeys: this.state.selectedRowKeys, selectObjects: this.state.selectObjects, onExpands: function () { return _this.reMax(); }, param: this.param }));
    };
    VTable.prototype.sorterField = function (sorter) {
        var query = __assign({}, this.param, { start_: 0, count_: this.state.pageSize });
        this.setState({ selectedRowKeys: [], selectObjects: [], current: 1, });
        if (_.has(sorter, 'field')) {
            query.order_ = sorter.field;
            query.by_ = sorter.order == 'ascend' ? 'asc' : 'desc';
        }
        this.fetchData(_.extend({}, this.props.default, query));
    };
    VTable.prototype.toPage = function (current, pageSize) {
        var _this = this;
        var resize = pageSize !== this.state.pageSize;
        var callback = function () { };
        if (resize) {
            callback = function () { return _this.reMax(); };
            window.setTimeout(function () { return _this.reMax(); }, 200);
        }
        var query = __assign({}, this.param, { start_: (current - 1) * pageSize, count_: pageSize });
        this.param.count_ = pageSize;
        var state = { selectedRowKeys: [], selectObjects: [] };
        state.pageSize = pageSize;
        state.current = current;
        this.setState(__assign({}, state));
        this.fetchData(_.extend({}, this.props.default, query), callback);
    };
    VTable.prototype.renderTable = function (style) {
        var _this = this;
        // @ts-ignore
        var effects = this.props._loading;
        var dataSource = [];
        if (_.has(this.props, 'dataSource')) {
            dataSource = this.props.dataSource;
        }
        else {
            dataSource = this.props[this.props.namespace].list;
        }
        var selectedRowKeys = [];
        var selectObjects = [];
        var rowSelection = undefined;
        if (this.props.select) {
            dataSource.map(function (item) {
                if (_.indexOf(_this.state.selectedRowKeys, item[_this.rowKey]) >= 0) {
                    selectedRowKeys.push(item[_this.rowKey]);
                    selectObjects.push(item);
                }
            });
            rowSelection = {
                selectedRowKeys: selectedRowKeys,
                onChange: function (selectedRowKeys, selectObjects) { return _this.onSelect(selectedRowKeys, selectObjects); },
                getCheckboxProps: function (record) { return ({ disabled: !_.has(record, _this.rowKey) }); },
            };
        }
        return React.createElement(antd_1.Table, __assign({ size: "small" }, this.props, { style: style, loading: effects[this.fetch], rowKey: this.rowKey, columns: this.columns, dataSource: dataSource, rowClassName: function (item) { return _.has(item, '__EFFECT') ? 'row-high-' + item['__EFFECT'] : ''; }, onChange: function (pagination, filters, sorter) { return _this.sorterField(sorter); }, rowSelection: rowSelection, pagination: false }));
    };
    VTable.prototype.renderPagination = function () {
        var _this = this;
        var total = 0;
        if (_.has(this.props, 'total')) {
            total = this.props.total;
        }
        else {
            total = this.props[this.props.namespace].total;
        }
        var current = this.state.current;
        if (_.has(this.props, 'namespace')) {
            current = this.props[this.props.namespace]._current || this.state.current;
            if (this.state.current != current) {
                this.setState({ current: current });
            }
        }
        return React.createElement(antd_1.Pagination, { onChange: function (page, pageSize) { return _this.toPage(page, pageSize); }, onShowSizeChange: function (page, pageSize) { return _this.toPage(page, pageSize); }, className: "vap-table-pagination", current: current, total: total, size: "small", showTotal: function (total, range) { return React.createElement("span", { className: "vap-table-pagination-info" },
                "\u5171 ",
                React.createElement("b", null, total),
                " \u6761 ",
                React.createElement("span", { className: "vap-table-pagination-range" },
                    "( ",
                    range[0],
                    " - ",
                    range[1],
                    " )")); }, showQuickJumper: true, showSizeChanger: true, hideOnSinglePage: false, pageSize: this.state.pageSize, pageSizeOptions: utils_1.Const.PAGE_OPTIONS });
    };
    VTable.prototype.render = function () {
        var layoutStyle = {};
        if (this.mode == 'fixed') {
            var fixHeight = this.props.fixedHeight || 0;
            // @ts-ignore
            if (_.has(this.props._theme, 'contentHeight')) {
                // @ts-ignore
                layoutStyle.height = this.props._theme.contentHeight - fixHeight;
            }
        }
        var className = ['vap-table', 'vap-table-' + this.mode];
        if (this.props.fixedCol) {
            className.push('vap-table-fixcol');
        }
        return React.createElement(antd_1.Layout, { className: className.join(' '), style: layoutStyle },
            this.renderSelectBar(),
            React.createElement(antd_1.Layout, { id: this.id },
                this.renderSearchBar(),
                React.createElement(antd_1.Layout.Content, { className: "vap-table-content" }, this.renderTable({})),
                this.props.pagination === false ? [] : React.createElement(antd_1.Layout.Footer, { className: "vap-table-footer" }, this.renderPagination())));
    };
    return VTable;
}(React.PureComponent));
var state = function (props) { return props; };
var dispatch = undefined;
var merge = undefined;
var options = { withRef: true };
var vTable = dva_1.connect(state, dispatch, merge, options)(VTable);
vTable.prototype.query = function (param) {
    this.getWrappedInstance().query(param);
};
vTable.prototype.setColumns = function (cols, showIndex) {
    if (showIndex === void 0) { showIndex = null; }
    this.getWrappedInstance().setColumns(cols, showIndex);
};
vTable.prototype.reflush = function (param) {
    if (param === void 0) { param = {}; }
    this.getWrappedInstance().reflush(param);
};
vTable.prototype.getSelected = function () {
    return this.getWrappedInstance().getSelected();
};
// vTable.prototype.getParam = function () {
//     return this.getWrappedInstance().getParam();
// }
exports.default = vTable;
