"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);
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (_) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
Object.defineProperty(exports, "__esModule", { value: true });
var Table_1 = require("./Table");
var React = require("react");
var _ = require("lodash");
var $ = require("jquery");
var antd_1 = require("antd");
var utils_1 = require("../../utils");
var DEF_PAGE_SIZE = 10;
var default_1 = /** @class */ (function (_super) {
    __extends(default_1, _super);
    function default_1() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.rowKey = 'id';
        _this.delKey = 'ids';
        _this.objName = '';
        _this.sorter = {};
        _this.param = {
            start_: 0,
            count_: _this.props.pageSize || DEF_PAGE_SIZE,
        };
        _this.state = {
            list: [],
            pageSize: _this.props.pageSize || DEF_PAGE_SIZE,
            total: 0,
            current: 1,
            loading: false,
        };
        _this.cleanAndQuery = function (param) {
            _this.setState({ list: [], total: 0, current: 1 });
            _this.query(param);
        };
        _this.query = function (param) {
            _this.param = _.assign({}, _this.props.param, { start_: 0, count_: _this.state.pageSize }, param);
            _this._query();
        };
        _this.clear = function () {
            _this.setState({
                list: [],
                total: 0,
                current: 1,
                loading: false,
            });
        };
        _this.add = function (param, callBack) {
            if (callBack === void 0) { callBack = null; }
            return __awaiter(_this, void 0, void 0, function () {
                var resp;
                return __generator(this, function (_a) {
                    switch (_a.label) {
                        case 0: return [4 /*yield*/, utils_1.Ajax.PUT(this.props.add, param)];
                        case 1:
                            resp = _a.sent();
                            if (resp.code == '0') {
                                antd_1.message.success(this.objName + "\u6DFB\u52A0\u6210\u529F");
                                if (_.has(resp, 'data')) {
                                    this.setState({ list: utils_1.Model.add(this.state.list, resp.data) });
                                }
                                else {
                                    this.setState({ list: utils_1.Model.add(this.state.list, param) });
                                }
                                if (callBack) {
                                    callBack(resp);
                                }
                            }
                            else {
                                antd_1.message.error(this.objName + "\u6DFB\u52A0\u5931\u8D25");
                            }
                            return [2 /*return*/];
                    }
                });
            });
        };
        _this.delete = function (ids, callBack) {
            if (callBack === void 0) { callBack = null; }
            return __awaiter(_this, void 0, void 0, function () {
                var param, resp;
                return __generator(this, function (_a) {
                    switch (_a.label) {
                        case 0:
                            param = {};
                            param[this.delKey] = ids + '';
                            return [4 /*yield*/, utils_1.Ajax.DELETE(this.props.delete, param)];
                        case 1:
                            resp = _a.sent();
                            if (resp.code == '0') {
                                antd_1.message.success(this.objName + "\u5220\u9664\u6210\u529F");
                                this.setState({ list: utils_1.Model.del(this.state.list, (ids + '').split(','), this.rowKey) });
                                if (callBack) {
                                    callBack(resp);
                                }
                            }
                            else {
                                antd_1.message.error(this.objName + "\u5220\u9664\u5931\u8D25");
                            }
                            return [2 /*return*/];
                    }
                });
            });
        };
        _this.update = function (param, callBack) {
            if (callBack === void 0) { callBack = null; }
            return __awaiter(_this, void 0, void 0, function () {
                var resp;
                return __generator(this, function (_a) {
                    switch (_a.label) {
                        case 0: return [4 /*yield*/, utils_1.Ajax.PATCH(this.props.update, param)];
                        case 1:
                            resp = _a.sent();
                            if (resp.code == '0') {
                                antd_1.message.success(this.objName + "\u4FEE\u6539\u6210\u529F");
                                this.setState({ list: utils_1.Model.update(this.state.list, param, this.rowKey) });
                                if (callBack) {
                                    callBack(resp);
                                }
                            }
                            else {
                                antd_1.message.error(this.objName + "\u4FEE\u6539\u5931\u8D25");
                            }
                            return [2 /*return*/];
                    }
                });
            });
        };
        return _this;
    }
    default_1.prototype.componentDidMount = function () {
        _.assign(this.param, this.props.param);
        if (this.props.autoLoad === false) {
            return;
        }
        // @ts-ignore
        this.rowKey = this.props.rowKey || 'id';
        this.delKey = this.props.delKey || 'ids';
        this.objName = this.props.objName || '';
        this._query();
    };
    default_1.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) {
                            scope_1[key + ''] = resp.data[key + ''][column.transate.fetch];
                            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) {
                    if (shift && !_.has(item, shift)) {
                        item[shift] = item[field];
                    }
                    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;
    };
    default_1.prototype._query = function () {
        var _this = this;
        this.setState({ loading: true });
        utils_1.Ajax.POST(this.props.query, this.param, function (json) {
            var current = _this.param.start_ === 0 ? 1 : _this.state.current;
            var list = json.list;
            var total = json.total;
            var loading = false;
            list = _this.transateList(list);
            if (_.has(_this.props, "queryAfterFun")) {
                _this.props.queryAfterFun(json.list);
            }
            _this.setState({ current: current, list: list, total: total, loading: loading });
        });
    };
    //获取当前页面页数，更新Table
    default_1.prototype._updateTable = function (param) {
        var _this = this;
        if (param && this.state.current == 1) {
            this.setState({ list: utils_1.Model.add(this.state.list, param) });
        }
        else {
            this.param = {
                start_: this.state.pageSize * this.state.current,
                count_: this.state.pageSize,
            };
            this.setState({ loading: true });
            utils_1.Ajax.CLEAR(this.props.query);
            utils_1.Ajax.POST(this.props.query, this.param, function (json) { return _this.setState({ list: json.list, loading: false }); });
        }
    };
    default_1.prototype.componentDidUpdate = function (old) {
        if (this.props._notUpdate) {
            return;
        }
        if (old.query != this.props.query || !_.isEqual(old.param, this.props.param)) {
            this.param = _.assign({ start_: 0, count_: this.state.pageSize, }, this.props.param);
            this._query();
        }
    };
    default_1.prototype.search = function (pagination, filters, sorter) {
        var _this = this;
        this.setState({ loading: true });
        var param = __assign({}, this.param, { start_: (pagination.current - 1) * pagination.pageSize, count_: pagination.pageSize });
        this.param.count_ = pagination.pageSize;
        var state = {};
        if (!_.isEqual(this.sorter, sorter) || this.state.pageSize != pagination.pageSize) {
            param.start_ = 0;
            param.count_ = pagination.pageSize;
            state.current = 1;
            state.pageSize = pagination.pageSize;
            this.sorter = sorter;
        }
        else {
            state.pageSize = pagination.pageSize;
            state.current = pagination.current;
        }
        if (_.has(sorter, 'field')) {
            param.order_ = sorter.field;
            param.by_ = sorter.order == 'ascend' ? 'asc' : 'desc';
        }
        else {
            param.order_ = null;
            param.by_ = null;
        }
        utils_1.Ajax.POST(this.props.query, param, function (json) {
            state.list = _this.transateList(json.list);
            state.total = json.total;
            state.loading = false;
            _this.setState(state);
        });
    };
    default_1.prototype.render = function () {
        var _this = this;
        var param = {
            dataSource: this.state.list,
            onChange: function (pagination, filters, sorter) { return _this.search(pagination, filters, sorter); }
        };
        var showSizeChanger = true;
        if (this.props.showSizeChanger === false) {
            showSizeChanger = false;
        }
        param.pagination = {
            current: this.state.current,
            total: this.state.total,
            showQuickJumper: true,
            showSizeChanger: showSizeChanger,
            pageSize: this.state.pageSize,
            pageSizeOptions: ['10', '15', '20', '30'],
        };
        var columns = _.concat([], this.props.columns);
        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;
                    }
                });
            }
        }
        if (_.has(this.props, "onClick")) {
            param.onRow = function (record, index) {
                return {
                    onClick: function () { return _this.props.onClick(record, index); }
                };
            };
        }
        ;
        return React.createElement(Table_1.default, __assign({}, this.props, param, { columns: columns, rowClassName: function (item) { return _.has(item, '__EFFECT') ? 'row-high-' + item['__EFFECT'] : ''; }, loading: this.state.loading }));
    };
    return default_1;
}(React.PureComponent));
exports.default = default_1;
