"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 antd_1 = require("antd");
var React = require("react");
var _ = require("lodash");
var utils_1 = require("../../utils");
var Linked_1 = require("./Linked");
var PageSize = 10;
/**
 * @private
*/
var MODE;
(function (MODE) {
    MODE[MODE["ADD"] = 0] = "ADD";
    MODE[MODE["EDIT"] = 1] = "EDIT";
    MODE[MODE["COMMON"] = 2] = "COMMON";
})(MODE = exports.MODE || (exports.MODE = {}));
/**
 * 列表弹框，弹出一个列表。
 * 1. 可以对列表里面的数据进行增删改查
 * 2. 可以弹出一个单选或多选框，选一条或多条数据后，返回给页面
*/
var ListModal = /** @class */ (function (_super) {
    __extends(ListModal, _super);
    function ListModal() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.rowKey = 'id';
        _this.mode = MODE.COMMON;
        _this.linked = null;
        _this.state = {
            list: [],
            current: 1,
            total: 0,
            columns: [],
            selectedRowKeys: [],
            selectedRowObjects: [],
        };
        _this.sorter = {};
        _this.param = {};
        _this.editObject = {};
        _this.queryField = "";
        return _this;
    }
    //删除的传参
    ListModal.prototype.componentWillMount = function () {
        this.rowKey = this.props.rowKey || this.rowKey;
    };
    //数据初始化 - 渲染之前的更新
    ListModal.prototype.componentDidUpdate = function (old) {
        var _this = this;
        if (!old.show && this.props.show) {
            this.linked = new Linked_1.default(this.props.columns);
            this.mode = MODE.COMMON;
            this.editObject = {};
            this.param = _.assign({}, { start_: 0, count_: PageSize }, this.props.param);
            utils_1.Ajax.POST(this.props.query, this.param, function (json) {
                _this.setState({
                    list: _.has(json, "list") ? json.list : json.data,
                    current: 1,
                    total: json.total,
                    columns: _this.buildOption()
                });
            });
        }
        else if (old.show === true && this.props.show === false) {
            this.mode = MODE.COMMON;
            this.editObject = {};
            this.setState({
                list: [],
                current: 1,
                total: 0,
                selectedRowKeys: [],
                selectedRowObjects: [],
            });
        }
    };
    //添加数据 - 执行
    ListModal.prototype.doAdd = function (record, save) {
        var _this = this;
        var list = _.concat([], this.state.list);
        var total = this.state.total;
        if (save) {
            utils_1.Ajax.PUT(this.props.add, _.assign({}, this.editObject, { _add: null, _edit: null }), function (json) {
                if (json.code == '0') {
                    antd_1.message.success('添加成功');
                    _this.editObject = {};
                    _this.mode = MODE.COMMON;
                    if (_.has(json, 'data')) {
                        list[0] = _.assign(list[0], _this.props.param, json.data, { _edit: false });
                        _this.setState({ list: list, total: total + 1 });
                    }
                    else {
                        utils_1.Ajax.POST(_this.props.query, _this.param, function (json) {
                            _this.setState({ list: _.has(json, "list") ? json.list : json.data, total: json.total });
                        });
                    }
                }
                else {
                    antd_1.message.error('添加失败');
                }
            });
        }
        else {
            list.shift();
            this.setState({ list: list });
            this.mode = MODE.COMMON;
        }
    };
    //编辑数据 - 执行
    ListModal.prototype.doEdit = function (record, save) {
        var _this = this;
        var list = _.concat([], this.state.list);
        if (save) {
            utils_1.Ajax.PATCH(this.props.edit, _.assign({}, this.editObject, { _add: null, _edit: null }), function (json) {
                if (json.code == '0') {
                    antd_1.message.success('修改成功');
                    _this.setState({ list: utils_1.Model.update(_this.state.list, _.assign({}, _this.editObject, { _edit: false }), _this.rowKey) });
                    _this.editObject = {};
                    _this.mode = MODE.COMMON;
                }
                else {
                    antd_1.message.error('修改失败');
                }
            });
        }
        else {
            list.map(function (item) { return item._edit = false; });
            this.setState({ list: list });
            this.mode = MODE.COMMON;
        }
    };
    //table - 操作栏 - 点击
    ListModal.prototype.exitEditMode = function (record, save) {
        if (save) {
            for (var i = 0; i < this.props.columns.length; i++) {
                var field = this.props.columns[i];
                var txt = this.editObject[field.dataIndex];
                if (field.require) {
                    if (_.isEmpty(_.toString(txt))) {
                        antd_1.message.error(field.title + " \u4E0D\u80FD\u4E3A\u7A7A");
                        return;
                    }
                }
                if (field.pattern) {
                    if (field.require || !_.isEmpty(txt)) {
                        if (_.isString(field.pattern)) {
                            if (!RegExp(field.pattern).test(txt)) {
                                antd_1.message.error(field.message || field.title + " \u683C\u5F0F\u9519\u8BEF");
                                return;
                            }
                        }
                        else if (!field.pattern.test(txt)) {
                            antd_1.message.error(field.message || field.title + " \u683C\u5F0F\u9519\u8BEF");
                            return;
                        }
                    }
                }
            }
        }
        switch (this.mode) {
            case MODE.ADD:
                this.doAdd(record, save);
                break;
            case MODE.EDIT:
                this.doEdit(record, save);
                break;
            default:
                break;
        }
    };
    //modal标题 - 添加 - 点击
    ListModal.prototype.add = function () {
        if (this.mode === MODE.COMMON) {
            this.mode = MODE.ADD;
            this.linked.init(null);
            var list = _.concat([], this.state.list);
            var obj_1 = _.assign({ _edit: true, _add: true, }, this.props.param);
            this.props.columns.map(function (column) {
                if (_.isArray(column.options) && column.options.length) {
                    obj_1[column.dataIndex] = column.options[0].value;
                }
                else {
                    obj_1[column.dataIndex] = '';
                }
            });
            this.editObject = _.assign({}, obj_1);
            list.unshift(_.assign({}, obj_1));
            this.setState({ list: list });
        }
    };
    //table - 操作栏 - 编辑 - 点击
    ListModal.prototype.edit = function (record) {
        var _this = this;
        if (this.mode === MODE.COMMON) {
            this.mode = MODE.EDIT;
            this.linked.init(record);
            this.editObject = _.assign({}, this.props.param, record);
            var list = _.concat([], this.state.list);
            list.map(function (item) {
                if (item[_this.rowKey] == record[_this.rowKey]) {
                    item._edit = true;
                }
                else {
                    item._edit = false;
                }
            });
            this.setState({ list: list });
        }
    };
    //过滤数据中出现null的情况
    ListModal.prototype.renderColumns = function (text, record, column, render) {
        var _this = this;
        if (column.readonly && this.mode == MODE.EDIT) {
            if (render) {
                return render(text);
            }
            if (column.options) {
                var val = _.find(column.options, { value: text + '' });
                return val ? val.name : text;
            }
            return text;
        }
        if (record && record._edit) {
            if (column.options) {
                if (column.type == 'switch') {
                    var checked = !(text == (column.options[1].value + ''));
                    return React.createElement(antd_1.Switch, { onChange: function (val) { return _this.editObject[column.dataIndex] = (val ? column.options[0].value : column.options[1].value); }, size: this.props.tiny ? 'small' : 'default', checkedChildren: column.options[0].name, unCheckedChildren: column.options[1].name, defaultChecked: checked });
                }
                else {
                    return React.createElement(antd_1.Select, { style: { width: column.width }, onChange: function (val) {
                            _this.editObject[column.dataIndex] = val;
                            if (column.link) {
                                _this.linked.call(column, val, function () {
                                    _this.setState({ __now: _.now() });
                                });
                            }
                        }, size: this.props.tiny ? 'small' : 'default', defaultValue: text }, this.linked.getOptions(column).map(function (item) { return React.createElement(antd_1.Select.Option, { value: item.value }, item.name); }));
                }
            }
            if (column.type == 'number') {
                // return <InputNumber size="default"  defaultValue={text} onChange={val => this.editObject[column.dataIndex] = val} />;
                return React.createElement(antd_1.InputNumber, { size: this.props.tiny ? 'small' : 'default', style: this.props.tiny ? { padding: 0, height: 22 } : {}, defaultValue: text, onChange: function (val) { return _this.editObject[column.dataIndex] = val; } });
            }
            return React.createElement(antd_1.Input, { size: this.props.tiny ? 'small' : 'default', style: this.props.tiny ? { padding: 0, height: 22 } : {}, defaultValue: text, onChange: function (e) { return _this.editObject[column.dataIndex] = e.target.value; } });
        }
        if (render) {
            return render(text);
        }
        if (column.options) {
            var val = _.find(column.options, { value: text + '' });
            return val ? val.name : text;
        }
        return text;
    };
    //删除数据 - 执行
    ListModal.prototype.doDel = function (record) {
        var _this = this;
        var param = {};
        var total = this.state.total;
        if (_.has(this.props, 'delKey')) {
            param[this.props.delKey] = record[this.rowKey];
        }
        else {
            param.ids = record[this.rowKey];
        }
        _.assign(param, this.props.param);
        utils_1.Ajax.DELETE(this.props.del, param, function (json) {
            if (json.code == '0') {
                antd_1.message.success('删除成功');
                var list = utils_1.Model.del(_this.state.list, [record[_this.rowKey]], _this.rowKey);
                var total_1 = _this.state.total - 1;
                if (list.length == 0 || ((_this.state.current * PageSize - total_1) > PageSize)) {
                    _this.search({ current: 1, pageSize: PageSize }, null, _this.sorter);
                }
                else {
                    _this.setState({ list: list, total: total_1 });
                }
            }
            else {
                antd_1.message.error('删除成功');
            }
        });
    };
    //编辑时 - 将column转化为input
    ListModal.prototype.buildEditColumn = function () {
        var _this = this;
        var columns = _.concat([], this.props.columns);
        columns.map(function (column) {
            var render = column.render;
            column.render = function (text, record) { return _this.renderColumns(text === undefined ?
                ((_.isArray(column.options) && column.options.length) ? column.options[0].value + '' : '')
                : text === null ? '' : text + '', record, column, render); };
        });
        return columns;
    };
    //列的构筑
    ListModal.prototype.buildOption = function () {
        var _this = this;
        var columns = this.buildEditColumn();
        if (this.props.edit || this.props.del || this.props.select) {
            var operCol = {
                title: '操作',
                dataIndex: this.rowKey,
                className: 'table-oper',
                width: 100,
                render: function (text, editObject) {
                    var acts = [];
                    if (editObject._edit) {
                        acts.push(React.createElement(antd_1.Icon, { type: "check", title: "\u4FDD\u5B58", onClick: function () { return _this.exitEditMode(editObject, true); } }));
                        acts.push(React.createElement(antd_1.Icon, { type: "close", title: "\u53D6\u6D88", onClick: function () { return _this.exitEditMode(editObject, false); } }));
                    }
                    else if (_this.props.select) {
                        acts.push(React.createElement(antd_1.Button, { size: _this.props.tiny ? 'small' : 'default', onClick: function () { return _this.props.select([editObject]); } }, "\u9009\u62E9"));
                    }
                    else {
                        if (_this.props.edit) {
                            acts.push(React.createElement(antd_1.Icon, { type: "edit", title: "\u7F16\u8F91", onClick: function () { return _this.edit(editObject); } }));
                        }
                        if (_this.props.del) {
                            acts.push(React.createElement(antd_1.Popconfirm, { title: "\u786E\u8BA4\u8981\u5220\u9664\u8FD9\u6761\u8BB0\u5F55\u5427 ?", onConfirm: function () { _this.doDel(editObject); } },
                                React.createElement(antd_1.Icon, { type: "close", title: "\u5220\u9664" })));
                        }
                    }
                    if (_this.props.otherAction && _this.props.otherAction.length > 0) {
                        _this.props.otherAction.map(function (d) {
                            var _title = d.tip(editObject);
                            acts.push(React.createElement(antd_1.Icon, { type: d.icon, title: _title, onClick: function () {
                                    d.render(editObject).then(function (resp) {
                                        if (d.remove) {
                                            var param = {};
                                            if (_.has(_this.props, 'delKey')) {
                                                param[_this.props.delKey] = editObject[_this.rowKey];
                                            }
                                            else {
                                                param.ids = editObject[_this.rowKey];
                                            }
                                            _.assign(param, _this.props.param);
                                            var list = utils_1.Model.del(_this.state.list, [editObject[_this.rowKey]], _this.rowKey);
                                            var total = _this.state.total - 1;
                                            if (list.length == 0 || ((_this.state.current * PageSize - total) > PageSize)) {
                                                _this.search({ current: 1, pageSize: PageSize }, null, _this.sorter);
                                            }
                                            else {
                                                _this.setState({ list: list, total: total });
                                            }
                                            _this.setState({
                                                list: list
                                            });
                                        }
                                        d.callback(resp);
                                    });
                                } }));
                        });
                    }
                    return acts;
                }
            };
            columns.push(operCol);
        }
        return columns;
    };
    //查询
    ListModal.prototype.search = function (pagination, filters, sorter) {
        var _this = this;
        var _param = {
            start_: (pagination.current - 1) * pagination.pageSize,
            count_: pagination.pageSize,
        };
        _.assign(this.param, _param);
        if (!_.isEqual(this.sorter, sorter)) {
            this.param.start = 0;
            this.sorter = sorter;
        }
        if (_.has(sorter, 'field')) {
            this.param.order_ = sorter.field;
            this.param.by_ = sorter.order == 'ascend' ? 'asc' : 'desc';
        }
        else {
            this.param.order_ = null;
            this.param.by_ = null;
        }
        utils_1.Ajax.POST(this.props.query, this.param, function (json) {
            _this.mode = MODE.COMMON;
            _this.setState({ list: _.has(json, "list") ? json.list : json.data, total: json.total, current: pagination.current });
        });
    };
    //查询
    ListModal.prototype.filter = function (value) {
        var _this = this;
        var param = {
            sort_: this.param.sort_,
            by_: this.param.by_,
            start_: 0,
            count_: PageSize,
        };
        param[this.queryField] = value;
        this.param = _.assign({}, this.props.param, param);
        utils_1.Ajax.POST(this.props.query, this.param, function (json) {
            _this.mode = MODE.COMMON;
            _this.setState({ list: _.has(json, "list") ? json.list : json.data, total: json.total, current: 1 });
        });
    };
    ListModal.prototype.render = function () {
        var _this = this;
        var modalParam = {};
        modalParam.title = [];
        if (this.props.search) {
            this.queryField = this.props.search[0].field;
            modalParam.title.push(React.createElement(antd_1.Input.Search, { style: {
                    maxWidth: 250,
                    marginRight: 6,
                }, size: this.props.tiny ? 'small' : 'default', addonBefore: React.createElement(antd_1.Select, { defaultValue: this.props.search[0].field, style: { minWidth: 60 }, onChange: function (e) { return _this.queryField = e; } }, this.props.search.map(function (item) { return React.createElement(antd_1.Select.Option, { value: item.field }, item.title); })), onSearch: function (value) { return _this.filter(value); }, enterButton: true }));
        }
        if (this.props.title) {
            modalParam.title.push(this.props.title);
        }
        if (this.props.mutiSelect && this.props.select) {
            modalParam.footer = React.createElement(antd_1.Button, { disabled: this.state.selectedRowKeys.length == 0, onClick: function (e) { return _this.props.select(_this.state.selectedRowObjects); }, type: "primary" },
                "\u9009\u62E9",
                this.state.selectedRowKeys.length > 0 ? "(" + this.state.selectedRowKeys.length + ")" : '');
        }
        else if (_.has(this.props, 'onOk')) {
            modalParam.footer = React.createElement(antd_1.Button, { size: this.props.tiny ? 'small' : 'default', onClick: function (e) { return _this.props.onOk(null); }, type: "primary" }, "\u786E\u5B9A");
        }
        else {
            modalParam.footer = null;
        }
        if (_.has(this.props, 'add')) {
            modalParam.title.unshift(React.createElement(antd_1.Button, { size: this.props.tiny ? 'small' : 'default', style: { marginRight: 12 }, onClick: function (e) { return _this.add(); }, icon: "plus-circle" }, "\u6DFB\u52A0"));
        }
        var tableParam = {
        // scroll: {
        //     x: true,
        //     y: 600
        // }
        };
        if (this.props.mutiSelect && this.props.select) {
            tableParam.rowSelection = {
                selectedRowKeys: this.state.selectedRowKeys,
                onChange: function (selectedRowKeys, selectedRowObjects) { return _this.setState({ selectedRowKeys: selectedRowKeys, selectedRowObjects: selectedRowObjects }); },
            };
        }
        if (this.props.showPage !== false) {
            tableParam.pagination = {
                current: this.state.current,
                total: this.state.total,
                hideOnSinglePage: true,
                showQuickJumper: true,
                showSizeChanger: false,
                pageSize: PageSize
            };
        }
        return React.createElement(antd_1.Modal, __assign({}, modalParam, { visible: this.props.show, width: this.props.width || 800, onCancel: this.props.onCancel, bodyStyle: { padding: 0 }, className: "_list_modal" }),
            React.createElement(antd_1.Table, __assign({ className: "vap-table" }, tableParam, { rowKey: this.rowKey, columns: this.state.columns, onChange: function (pagination, filters, sorter) { return _this.search(pagination, filters, sorter); }, dataSource: this.state.list, size: this.props.tiny ? 'small' : 'default' })));
    };
    return ListModal;
}(React.PureComponent));
exports.default = ListModal;
