"use strict";

Object.defineProperty(exports, "__esModule", {
    value: true
});

var _extends2 = require("babel-runtime/helpers/extends");

var _extends3 = _interopRequireDefault(_extends2);

var _regenerator = require("babel-runtime/regenerator");

var _regenerator2 = _interopRequireDefault(_regenerator);

var _toConsumableArray2 = require("babel-runtime/helpers/toConsumableArray");

var _toConsumableArray3 = _interopRequireDefault(_toConsumableArray2);

var _defineProperty2 = require("babel-runtime/helpers/defineProperty");

var _defineProperty3 = _interopRequireDefault(_defineProperty2);

var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck");

var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);

var _createClass2 = require("babel-runtime/helpers/createClass");

var _createClass3 = _interopRequireDefault(_createClass2);

var _possibleConstructorReturn2 = require("babel-runtime/helpers/possibleConstructorReturn");

var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);

var _inherits2 = require("babel-runtime/helpers/inherits");

var _inherits3 = _interopRequireDefault(_inherits2);

var _react = require("react");

var _react2 = _interopRequireDefault(_react);

var _table = require("../table");

var _table2 = _interopRequireDefault(_table);

var _icon = require("../icon");

var _icon2 = _interopRequireDefault(_icon);

var _message = require("../message");

var _message2 = _interopRequireDefault(_message);

var _rest = require("@fishx/rest");

var _propTypes = require("prop-types");

var _propTypes2 = _interopRequireDefault(_propTypes);

var _isEqual = require("lodash/isEqual");

var _isEqual2 = _interopRequireDefault(_isEqual);

var _shortid = require("shortid");

var _shortid2 = _interopRequireDefault(_shortid);

var _Column = require("antd/lib/table/Column");

var _Column2 = _interopRequireDefault(_Column);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }

var __awaiter = undefined && undefined.__awaiter || function (thisArg, _arguments, P, generator) {
    function adopt(value) {
        return value instanceof P ? value : new P(function (resolve) {
            resolve(value);
        });
    }
    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) : adopt(result.value).then(fulfilled, rejected);
        }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __rest = undefined && undefined.__rest || function (s, e) {
    var t = {};
    for (var p in s) {
        if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p];
    }if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
        if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]];
    }
    return t;
};

var TableEdit = function (_Component) {
    (0, _inherits3["default"])(TableEdit, _Component);

    function TableEdit(props) {
        (0, _classCallCheck3["default"])(this, TableEdit);

        var _this = (0, _possibleConstructorReturn3["default"])(this, (TableEdit.__proto__ || Object.getPrototypeOf(TableEdit)).call(this, props));

        _this.addRow = function () {
            var _this$state = _this.state,
                dataSource = _this$state.dataSource,
                newColumns = _this$state.newColumns;
            var _this$props$rowKey = _this.props.rowKey,
                rowKey = _this$props$rowKey === undefined ? "key" : _this$props$rowKey;

            var key = _shortid2["default"].generate();
            var newRow = (0, _defineProperty3["default"])({}, rowKey, key);
            newColumns.forEach(function (v) {
                if (v.dataIndex !== "edit") {
                    if (v.editType === "date") {
                        newRow[v.dataIndex] = new Date().toLocaleDateString();
                    } else {
                        newRow[v.dataIndex] = "";
                    }
                }
            });
            var newData = dataSource.concat(newRow);
            _this.setState({ dataSource: newData, editingKey: key, update: true });
        };
        _this.onSaveRowEdit = function (reocrd, newData) {
            var onSaveRowEdit = _this.props.onSaveRowEdit;

            _this.setState({ dataSource: newData, update: true });
            onSaveRowEdit && onSaveRowEdit(reocrd, newData);
        };
        _this.delRow = function (key) {
            var dataSource = _this.state.dataSource;
            var _this$props = _this.props,
                beforeRowDelete = _this$props.beforeRowDelete,
                afterRowDelete = _this$props.afterRowDelete;

            var record = dataSource.find(function (item) {
                return item.key === key;
            });
            if (beforeRowDelete && !beforeRowDelete(record)) {
                return;
            }
            var newData = dataSource.filter(function (item) {
                return item.key !== key;
            });
            _this.setState({ dataSource: newData, update: true });
            afterRowDelete && afterRowDelete(newData);
        };
        _this.upMoveRow = function (key) {
            var _this$state2 = _this.state,
                dataSource = _this$state2.dataSource,
                editingKey = _this$state2.editingKey;
            var afterUpMoveRow = _this.props.afterUpMoveRow;

            var newData = [].concat((0, _toConsumableArray3["default"])(dataSource));
            var idx = newData.findIndex(function (item) {
                return item.key === key;
            });
            if (idx !== 0) {
                newData[idx] = newData.splice(idx - 1, 1, newData[idx])[0];
                _this.setState({ dataSource: newData, update: true });
                afterUpMoveRow && afterUpMoveRow(newData, newData[idx - 1], editingKey);
            } else {
                _message2["default"].warn("当前行是第一行，无法上移");
            }
        };
        _this.downMoveRow = function (key) {
            var _this$state3 = _this.state,
                dataSource = _this$state3.dataSource,
                editingKey = _this$state3.editingKey;
            var afterDownMoveRow = _this.props.afterDownMoveRow;

            var newData = [].concat((0, _toConsumableArray3["default"])(dataSource));
            var idx = newData.findIndex(function (item) {
                return item.key === key;
            });
            if (idx !== newData.length - 1) {
                newData[idx] = newData.splice(idx + 1, 1, newData[idx])[0];
                _this.setState({ dataSource: newData, update: true });
                afterDownMoveRow && afterDownMoveRow(newData, newData[idx + 1], editingKey);
            } else {
                _message2["default"].warn("当前行是最后一行，无法下移");
            }
        };
        _this.caluNewColumns = function () {
            return __awaiter(_this, void 0, void 0, /*#__PURE__*/_regenerator2["default"].mark(function _callee() {
                var _this2 = this;

                var _props, children, operColumnTitle, _state, removeable, upmoveable, downmoveable, columns, operateFirst, editColumn, _columns, _loop, i, _loop2, _ret2;

                return _regenerator2["default"].wrap(function _callee$(_context3) {
                    while (1) {
                        switch (_context3.prev = _context3.next) {
                            case 0:
                                _props = this.props, children = _props.children, operColumnTitle = _props.operColumnTitle;
                                _state = this.state, removeable = _state.removeable, upmoveable = _state.upmoveable, downmoveable = _state.downmoveable, columns = _state.columns, operateFirst = _state.operateFirst;
                                editColumn = {
                                    title: operColumnTitle,
                                    dataIndex: "edit",
                                    width: 100,
                                    editable: true,
                                    render: function render(_, record) {
                                        return _react2["default"].createElement(
                                            _react2["default"].Fragment,
                                            null,
                                            removeable && _react2["default"].createElement(
                                                "a",
                                                { onClick: function onClick() {
                                                        _this2.delRow(record.key);
                                                    } },
                                                _react2["default"].createElement(_icon2["default"], { type: "delete" }),
                                                "\xA0\xA0"
                                            ),
                                            upmoveable && _react2["default"].createElement(
                                                "a",
                                                { onClick: function onClick() {
                                                        _this2.upMoveRow(record.key);
                                                    } },
                                                _react2["default"].createElement(_icon2["default"], { type: "arrow-up" }),
                                                "\xA0\xA0"
                                            ),
                                            downmoveable && _react2["default"].createElement(
                                                "a",
                                                { onClick: function onClick() {
                                                        _this2.downMoveRow(record.key);
                                                    } },
                                                _react2["default"].createElement(_icon2["default"], { type: "arrow-down" })
                                            )
                                        );
                                    },
                                    editContent: function editContent() {
                                        return _react2["default"].createElement(_icon2["default"], { type: "edit" });
                                    },
                                    saveContent: function saveContent() {
                                        return _react2["default"].createElement(_icon2["default"], { type: "save" });
                                    },
                                    cancelContent: function cancelContent() {
                                        return _react2["default"].createElement(_icon2["default"], { type: "stop" });
                                    }
                                };
                                _columns = [];

                                if (!columns) {
                                    _context3.next = 15;
                                    break;
                                }

                                _loop = /*#__PURE__*/_regenerator2["default"].mark(function _loop(i) {
                                    var col, editOptions, editType, _ref, data;

                                    return _regenerator2["default"].wrap(function _loop$(_context) {
                                        while (1) {
                                            switch (_context.prev = _context.next) {
                                                case 0:
                                                    col = columns[i];
                                                    editOptions = col.editOptions, editType = col.editType;

                                                    if (!(editOptions && editOptions.indexOf("http") !== -1)) {
                                                        _context.next = 8;
                                                        break;
                                                    }

                                                    _context.next = 5;
                                                    return (0, _rest.fetch)(editOptions, { method: "GET" });

                                                case 5:
                                                    _ref = _context.sent;
                                                    data = _ref.data;

                                                    col.editOptions = data;

                                                case 8:
                                                    if (col.editOptions && col.editOptions.length) {
                                                        col.render = function (text) {
                                                            if (editType === 'select') {
                                                                var res = col.editOptions.find(function (v) {
                                                                    return v.value === text;
                                                                });
                                                                return res ? res.label : null;
                                                            } else if (editType === 'treeSelect') {
                                                                return text && text.label ? text.label : text;
                                                            } else if (editType === 'multiTreeSelect' && Array.isArray(text)) {
                                                                var labels = text.map(function (v) {
                                                                    return v.label;
                                                                }) || [];
                                                                return labels;
                                                            } else if (editType === 'checkbox' && Array.isArray(text)) {
                                                                var filters = col.editOptions.filter(function (v) {
                                                                    return text.includes(v.value);
                                                                }).map(function (v) {
                                                                    return v.label;
                                                                }) || [];
                                                                return filters.length > 0 ? filters : text;
                                                            } else {
                                                                return text;
                                                            }
                                                        };
                                                    }

                                                case 9:
                                                case "end":
                                                    return _context.stop();
                                            }
                                        }
                                    }, _loop, _this2);
                                });
                                i = 0;

                            case 7:
                                if (!(i < columns.length)) {
                                    _context3.next = 12;
                                    break;
                                }

                                return _context3.delegateYield(_loop(i), "t0", 9);

                            case 9:
                                i++;
                                _context3.next = 7;
                                break;

                            case 12:
                                if (operateFirst) {
                                    _columns = [editColumn].concat((0, _toConsumableArray3["default"])(columns));
                                } else {
                                    _columns = [].concat((0, _toConsumableArray3["default"])(columns), [editColumn]);
                                }
                                _context3.next = 26;
                                break;

                            case 15:
                                _loop2 = /*#__PURE__*/_regenerator2["default"].mark(function _loop2(i) {
                                    var child, _a, title, dataIndex, width, editType, _a$editOptions, editOptions, _a$editRules, editRules, restOpts, _ref2, data, render;

                                    return _regenerator2["default"].wrap(function _loop2$(_context2) {
                                        while (1) {
                                            switch (_context2.prev = _context2.next) {
                                                case 0:
                                                    child = children[i];

                                                    if (child.props) {
                                                        _context2.next = 3;
                                                        break;
                                                    }

                                                    return _context2.abrupt("return", "continue");

                                                case 3:
                                                    _a = child.props, title = _a.title, dataIndex = _a.dataIndex, width = _a.width, editType = _a.editType, _a$editOptions = _a.editOptions, editOptions = _a$editOptions === undefined ? [] : _a$editOptions, _a$editRules = _a.editRules, editRules = _a$editRules === undefined ? [] : _a$editRules, restOpts = __rest(_a, ["title", "dataIndex", "width", "editType", "editOptions", "editRules"]);

                                                    if (!(editOptions.indexOf("http") !== -1)) {
                                                        _context2.next = 10;
                                                        break;
                                                    }

                                                    _context2.next = 7;
                                                    return (0, _rest.fetch)(editOptions, { method: "GET" });

                                                case 7:
                                                    _ref2 = _context2.sent;
                                                    data = _ref2.data;

                                                    editOptions = data;

                                                case 10:
                                                    render = void 0;

                                                    if (editOptions.length) {
                                                        render = function render(text) {
                                                            if (editType === 'select') {
                                                                var res = editOptions.find(function (v) {
                                                                    return v.value === text;
                                                                });
                                                                return res ? res.label : null;
                                                            } else if (editType === 'treeSelect') {
                                                                return text && text.label ? text.label : text;
                                                            } else if (editType === 'multiTreeSelect' && Array.isArray(text)) {
                                                                var labels = text.map(function (v) {
                                                                    return v.label;
                                                                }) || [];
                                                                return labels;
                                                            } else if (editType === 'checkbox' && Array.isArray(text)) {
                                                                var filters = editOptions.filter(function (v) {
                                                                    return text.includes(v.value);
                                                                }).map(function (v) {
                                                                    return v.label;
                                                                }) || [];
                                                                return filters.length > 0 ? filters : text;
                                                            } else {
                                                                return text;
                                                            }
                                                        };
                                                    }
                                                    _columns.push((0, _extends3["default"])((0, _extends3["default"])((0, _extends3["default"])({}, restOpts), { title: title,
                                                        dataIndex: dataIndex,
                                                        width: width,
                                                        editType: editType,
                                                        editOptions: editOptions,
                                                        editRules: editRules }), render ? { render: render } : {}));

                                                case 13:
                                                case "end":
                                                    return _context2.stop();
                                            }
                                        }
                                    }, _loop2, _this2);
                                });
                                i = 0;

                            case 17:
                                if (!(i < children.length)) {
                                    _context3.next = 25;
                                    break;
                                }

                                return _context3.delegateYield(_loop2(i), "t1", 19);

                            case 19:
                                _ret2 = _context3.t1;

                                if (!(_ret2 === "continue")) {
                                    _context3.next = 22;
                                    break;
                                }

                                return _context3.abrupt("continue", 22);

                            case 22:
                                i++;
                                _context3.next = 17;
                                break;

                            case 25:
                                if (operateFirst) {
                                    _columns.unshift(editColumn);
                                } else {
                                    _columns.push(editColumn);
                                }

                            case 26:
                                _columns.forEach(function (v) {
                                    if (v.editType) {
                                        v.editable = true;
                                    }
                                });
                                return _context3.abrupt("return", _columns);

                            case 28:
                            case "end":
                                return _context3.stop();
                        }
                    }
                }, _callee, this);
            }));
        };
        var _this$props2 = _this.props,
            dataSource = _this$props2.dataSource,
            columns = _this$props2.columns,
            removeable = _this$props2.removeable,
            upmoveable = _this$props2.upmoveable,
            downmoveable = _this$props2.downmoveable,
            operateFirst = _this$props2.operateFirst;

        _this.state = {
            editingKey: "",
            newColumns: [],
            columns: columns,
            dataSource: dataSource,
            removeable: removeable,
            upmoveable: upmoveable,
            update: false,
            downmoveable: downmoveable,
            operateFirst: operateFirst
        };
        return _this;
    }

    (0, _createClass3["default"])(TableEdit, [{
        key: "componentDidMount",
        value: function componentDidMount() {
            return __awaiter(this, void 0, void 0, /*#__PURE__*/_regenerator2["default"].mark(function _callee2() {
                var _columns;

                return _regenerator2["default"].wrap(function _callee2$(_context4) {
                    while (1) {
                        switch (_context4.prev = _context4.next) {
                            case 0:
                                _context4.next = 2;
                                return this.caluNewColumns();

                            case 2:
                                _columns = _context4.sent;

                                this.setState({ newColumns: _columns });

                            case 4:
                            case "end":
                                return _context4.stop();
                        }
                    }
                }, _callee2, this);
            }));
        }
    }, {
        key: "componentDidUpdate",
        value: function componentDidUpdate(_, preState) {
            return __awaiter(this, void 0, void 0, /*#__PURE__*/_regenerator2["default"].mark(function _callee3() {
                var _columns;

                return _regenerator2["default"].wrap(function _callee3$(_context5) {
                    while (1) {
                        switch (_context5.prev = _context5.next) {
                            case 0:
                                _context5.next = 2;
                                return this.caluNewColumns();

                            case 2:
                                _columns = _context5.sent;

                                if (!(0, _isEqual2["default"])(this.state.columns, preState.columns) || !(0, _isEqual2["default"])(this.state.removeable, preState.removeable) || !(0, _isEqual2["default"])(this.state.upmoveable, preState.upmoveable) || !(0, _isEqual2["default"])(this.state.downmoveable, preState.downmoveable)) {
                                    this.setState({ newColumns: _columns });
                                }

                            case 4:
                            case "end":
                                return _context5.stop();
                        }
                    }
                }, _callee3, this);
            }));
        }
    }, {
        key: "render",
        value: function render() {
            var _this3 = this;

            var opts = {};
            var _state2 = this.state,
                editingKey = _state2.editingKey,
                newColumns = _state2.newColumns,
                dataSource = _state2.dataSource;
            var _a = this.props,
                footer = _a.footer,
                insertable = _a.insertable,
                children = _a.children,
                restProps = __rest(_a, ["footer", "insertable", "children"]);
            if (insertable) {
                opts.footer = function (currentPageData) {
                    return _react2["default"].createElement(
                        _react2["default"].Fragment,
                        null,
                        footer && footer(currentPageData),
                        _react2["default"].createElement(
                            "a",
                            { onClick: _this3.addRow },
                            _react2["default"].createElement(_icon2["default"], { type: "plus" })
                        )
                    );
                };
            }
            return _react2["default"].createElement(_table2["default"], (0, _extends3["default"])({}, opts, restProps, { dataSource: dataSource, onSaveRowEdit: this.onSaveRowEdit, editRow: true, columns: newColumns, editingKey: editingKey }));
        }
    }], [{
        key: "getDerivedStateFromProps",
        value: function getDerivedStateFromProps(nextProps, prevState) {
            var changeObj = {};
            if (!(0, _isEqual2["default"])(nextProps.dataSource, prevState.dataSource)) {
                if (nextProps.update === prevState.update) {
                    changeObj.dataSource = nextProps.dataSource;
                } else {
                    changeObj.update = false;
                }
            }
            if (!(0, _isEqual2["default"])(nextProps.columns, prevState.columns)) {
                if (nextProps.update === prevState.update) {
                    changeObj.columns = nextProps.columns;
                } else {
                    changeObj.update = false;
                }
            }
            if (!(0, _isEqual2["default"])(nextProps.removeable, prevState.removeable)) {
                if (nextProps.update === prevState.update) {
                    changeObj.removeable = nextProps.removeable;
                } else {
                    changeObj.update = false;
                }
            }
            if (!(0, _isEqual2["default"])(nextProps.upmoveable, prevState.upmoveable)) {
                if (nextProps.update === prevState.update) {
                    changeObj.upmoveable = nextProps.upmoveable;
                } else {
                    changeObj.update = false;
                }
            }
            if (!(0, _isEqual2["default"])(nextProps.downmoveable, prevState.downmoveable)) {
                if (nextProps.update === prevState.update) {
                    changeObj.downmoveable = nextProps.downmoveable;
                } else {
                    changeObj.update = false;
                }
            }
            return Object.keys(changeObj).length ? changeObj : null;
        }
    }]);
    return TableEdit;
}(_react.Component);

exports["default"] = TableEdit;

TableEdit.componentName = 'TableEdit';
TableEdit.Column = _Column2["default"];
TableEdit.propTypes = {
    insertable: _propTypes2["default"].bool,
    removeable: _propTypes2["default"].bool,
    upmoveable: _propTypes2["default"].bool,
    downmoveable: _propTypes2["default"].bool,
    operateFirst: _propTypes2["default"].bool,
    onSaveRowEdit: _propTypes2["default"].func,
    beforeRowDelete: _propTypes2["default"].func,
    afterRowDelete: _propTypes2["default"].func,
    afterUpMoveRow: _propTypes2["default"].func,
    afterDownMoveRow: _propTypes2["default"].func
};
TableEdit.defaultProps = {
    insertable: false,
    removeable: false,
    upmoveable: false,
    update: false,
    downmoveable: false,
    operateFirst: false,
    operColumnTitle: 'Operation'
};
module.exports = exports['default'];