"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 QueryPanel_1 = require("../QueryPanel");
var TreePanel_1 = require("../TreePanel");
var DefaultPageSize = 10;
/**
 * Data Table 与TableLayout 极为相似
*/
var DataTable = /** @class */ (function (_super) {
    __extends(DataTable, _super);
    function DataTable() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.rowKey = 'id';
        _this.sorter = {};
        _this.pageChanged = true;
        _this.treePanel = null;
        _this.queryFetch = '';
        _this.state = {
            selectedRowKeys: [],
            selectObjects: [],
            current: 1,
            pageSize: _this.props.pageSize || DefaultPageSize,
        };
        _this.param = {
            start_: 0,
            count_: _this.props.pageSize || DefaultPageSize,
            order_: _this.rowKey,
            by_: 'desc',
        };
        _this.reflush = function (param) {
            if (param === void 0) { param = {}; }
            _this.query(_.extend(_this.param, { start_: 0 }, param));
        };
        _this.query = function (param) {
            _.extend(_this.param, param, { start_: 0 });
            _this.setState({
                current: 1,
                selectedRowKeys: [],
                selectedRows: [],
            });
            // @ts-ignore
            _this.props.dispatch({
                type: _this.queryFetch,
                query: _.extend({}, _this.props.default, _this.param)
            });
        };
        _this.getSelect = function () {
            return [_this.state.selectedRowKeys, _this.state.selectObjects];
        };
        _this.getParam = function () { return _this.param; };
        _this.treeFilter = function (val) {
            if (_this.treePanel) {
                _this.treePanel.filter(val);
            }
        };
        return _this;
    }
    DataTable.prototype.componentDidMount = function () {
        //@ts-ignore
        this.rowKey = this.props.rowKey || 'id';
        this.param.order_ = this.rowKey;
        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.queryFetch = this.props.fetch ? this.props.fetch : (this.props.namespace + '/_query');
        if (_.has(this.props, 'default.order_')) {
            this.param.order_ = this.props.default.order_;
        }
        else {
            this.param.order_ = this.rowKey;
        }
        if (_.has(this.props, 'default.order_')) {
            this.param.by_ = this.props.default.by_;
        }
        else {
            this.param.by_ = 'desc';
        }
        var param = {
            type: this.queryFetch,
            query: _.extend({}, this.props.default, this.param)
        };
        if (this.props.autoLoad === false) {
            return;
        }
        // @ts-ignore
        this.props.dispatch(param);
    };
    DataTable.prototype.transateList = function (list) {
        var transateField = [];
        this.props.columns.map(function (column) {
            var _a;
            if (column.transate) {
                transateField.push({ field: column.dataIndex, shift: column.transate.shift, def: column.transate.default, scope: column.transate.scope });
                var scope_1 = utils_1.Cache.sessionData(column.transate.scope) || {};
                var fetchIds_1 = [];
                list.map(function (record) { if (!_.has(scope_1, record[column.dataIndex] + '')) {
                    if (record[column.dataIndex]) {
                        fetchIds_1.push(record[column.dataIndex]);
                    }
                } });
                fetchIds_1 = _.union(fetchIds_1);
                if (fetchIds_1.length > 0) {
                    $.ajax(column.transate.query, {
                        async: false,
                        method: 'POST',
                        contentType: "application/json",
                        data: JSON.stringify((_a = {},
                            _a[column.transate.field || 'ids'] = fetchIds_1.join(','),
                            _a)),
                    }).done(function (resp) {
                        _.keys(resp.data).map(function (key) {
                            if (column.transate.fetch) {
                                scope_1[key + ''] = resp.data[key + ''][column.transate.fetch];
                            }
                            else {
                                scope_1[key + ''] = resp.data[key + ''];
                            }
                            utils_1.Cache.sessionData(column.transate.scope, scope_1);
                        });
                    });
                }
            }
        });
        if (transateField.length > 0) {
            transateField.map(function (_a) {
                var field = _a.field, scope = _a.scope, shift = _a.shift, def = _a.def;
                var cache = utils_1.Cache.sessionData(scope) || {};
                list.map(function (item) {
                    var orgin = _.toString(item[field]);
                    if (shift && !_.has(item, shift)) {
                        item[shift] = orgin;
                    }
                    if (_.has(cache, item[field]) && !_.has(item, '__inject_' + field)) {
                        _.set(item, field, cache[item[field]]);
                        _.set(item, '__inject_' + field, 'true');
                    }
                    else {
                        if (def !== false) {
                            item[field] = def || '';
                        }
                    }
                });
            });
        }
        return list;
    };
    DataTable.prototype.search = function (pagination, filters, sorter) {
        var query = __assign({}, this.param, { start_: (pagination.current - 1) * pagination.pageSize, count_: pagination.pageSize });
        this.param.count_ = pagination.pageSize;
        var state = {};
        if (!_.isEqual(this.sorter, sorter)) {
            query.start_ = 0;
            state.current = 1;
            this.setState({
                current: 1,
            });
            this.sorter = sorter;
        }
        else {
            state.pageSize = pagination.pageSize;
            state.current = pagination.current;
        }
        this.setState(__assign({}, state));
        if (_.has(sorter, 'field')) {
            query.order_ = sorter.field;
            query.by_ = sorter.order == 'ascend' ? 'asc' : 'desc';
        }
        // @ts-ignore
        this.props.dispatch({
            type: this.queryFetch,
            query: _.extend({}, this.props.default, query)
        });
    };
    // _getSelect(){
    //     let selectedRowKeys = [];
    //     let allSelectedKey = this.state.selectedRows.map(d => d[this.rowKey]);
    //     let pageKey = this.props.dataSource.map(d=> d[this.rowKey]);
    //     return _.intersection(allSelectedKey, pageKey);
    // }
    DataTable.prototype.onSelect = function (selectedRowKeys, selectObjects) {
        this.setState({
            selectedRowKeys: selectedRowKeys, selectObjects: selectObjects
        });
    };
    DataTable.prototype.render = function () {
        var _this = this;
        var params = {};
        if (!_.has(this.props, 'size')) {
            params.size = 'default';
        }
        if (!_.has(this.props, 'rowKey')) {
            params.rowKey = this.rowKey;
        }
        var total = 0;
        if (_.has(this.props, 'total')) {
            total = this.props.total;
        }
        else {
            total = this.props[this.props.namespace].total;
        }
        if (!_.has(this.props, 'dataSource')) {
            params.dataSource = this.props[this.props.namespace].list;
        }
        var columns = _.concat([], _.filter(this.props.columns, function (item) { return item.show === undefined || item.show == true; }));
        if (_.has(this.props, 'showIndex')) {
            if (_.isBoolean(this.props.showIndex && this.props.showIndex)) {
                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)) {
                columns.unshift({
                    title: this.props.showIndex,
                    className: '_index',
                    render: function (d, j, i) {
                        return i + (_this.state.current - 1) * _this.state.pageSize + 1;
                    }
                });
            }
        }
        //去掉被设置为false的列
        // params.columns = _.filter(this.props.columns, item => item.show === undefined || item.show == true);
        var selectedRowKeys = [];
        var selectObjects = [];
        if (this.props.select) {
            (this.props.dataSource || params.dataSource).map(function (item) {
                if (_.indexOf(_this.state.selectedRowKeys, item[_this.rowKey]) >= 0) {
                    selectedRowKeys.push(item[_this.rowKey]);
                    selectObjects.push(item);
                }
            });
            params.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.Row, { type: "flex" },
            this.props.treePanel ? React.createElement(antd_1.Col, { className: "tree-panel", style: { width: this.props.treePanelWidth || 250 } },
                React.createElement(TreePanel_1.default, __assign({}, this.props.treePanel, { ref: function (treePanel) { return _this.treePanel = treePanel; } }))) : '',
            React.createElement(antd_1.Col, { className: "table-panel" },
                this.props.queryPanel ? React.createElement(QueryPanel_1.default, __assign({}, this.props.queryPanel)) : [],
                React.createElement(antd_1.Table, __assign({}, this.props, params, { columns: columns, dataSource: this.transateList(this.props.dataSource || params.dataSource), rowClassName: function (item) { return _.has(item, '__EFFECT') ? 'row-high-' + item['__EFFECT'] : ''; }, onChange: function (pagination, filters, sorter) { return _this.search(pagination, filters, sorter); }, pagination: {
                        current: this.state.current,
                        total: total,
                        showQuickJumper: true,
                        showSizeChanger: true,
                        hideOnSinglePage: false,
                        pageSize: this.state.pageSize,
                        pageSizeOptions: utils_1.Const.PAGE_OPTIONS,
                    } }))));
    };
    return DataTable;
}(React.PureComponent));
var state = function (props) { return props; };
var dispatch = undefined;
var merge = undefined;
var options = { withRef: true };
var dataTable = dva_1.connect(state, dispatch, merge, options)(DataTable);
dataTable.prototype.query = function (param) {
    this.getWrappedInstance().query(param);
};
dataTable.prototype.reflush = function (param) {
    if (param === void 0) { param = {}; }
    this.getWrappedInstance().reflush(param);
};
dataTable.prototype.getSelect = function () {
    return this.getWrappedInstance().getSelect();
};
dataTable.prototype.getParam = function () {
    return this.getWrappedInstance().getParam();
};
dataTable.prototype.treeFilter = function (val) {
    this.getWrappedInstance().treeFilter(val);
};
exports.default = dataTable;
