'use strict';

Object.defineProperty(exports, "__esModule", {
    value: true
});
exports.EditableRow = exports.EditableFormRow = undefined;

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 _extends2 = require('babel-runtime/helpers/extends');

var _extends3 = _interopRequireDefault(_extends2);

var _react = require('react');

var _react2 = _interopRequireDefault(_react);

var _moment = require('moment');

var _moment2 = _interopRequireDefault(_moment);

var _form = require('../form');

var _form2 = _interopRequireDefault(_form);

var _input = require('../input');

var _input2 = _interopRequireDefault(_input);

var _inputNumber = require('../input-number');

var _inputNumber2 = _interopRequireDefault(_inputNumber);

var _select = require('../select');

var _select2 = _interopRequireDefault(_select);

var _datePicker = require('../date-picker');

var _datePicker2 = _interopRequireDefault(_datePicker);

var _treeSelect = require('../tree-select');

var _treeSelect2 = _interopRequireDefault(_treeSelect);

var _radio = require('../radio');

var _radio2 = _interopRequireDefault(_radio);

var _checkbox = require('../checkbox');

var _checkbox2 = _interopRequireDefault(_checkbox);

var _dragTable = require('./dragTable');

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

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 FormItem = _form2['default'].Item;
var EditableContext = _react2['default'].createContext(null);
var TextArea = _input2['default'].TextArea;

var DATE_FORMAT = 'YYYY-MM-DD';
var DATE_TIME_FORMAT = 'YYYY-MM-DD HH:mm:ss';
var getColumnMapFromChildren = function getColumnMapFromChildren() {
    var children = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];

    var columnMap = {};
    children.forEach(function (child) {
        var _ref = child.props || {},
            _ref$column = _ref.column,
            column = _ref$column === undefined ? {} : _ref$column;

        columnMap[column.dataIndex] = column.editType || 'text';
    });
    return columnMap;
};
var Editablerow = function Editablerow(_a) {
    var form = _a.form,
        index = _a.index,
        moveRow = _a.moveRow,
        props = __rest(_a, ["form", "index", "moveRow"]);

    var columnMap = getColumnMapFromChildren(props.children);
    return _react2['default'].createElement(
        EditableContext.Provider,
        { value: { form: form, columnMap: columnMap } },
        moveRow ? _react2['default'].createElement(_dragTable.DragableBodyRow, (0, _extends3['default'])({ index: index, moveRow: moveRow }, props)) : _react2['default'].createElement('tr', props)
    );
};
var EditableFormRow = exports.EditableFormRow = _form2['default'].create()(Editablerow);

var EditableRow = exports.EditableRow = function (_Component) {
    (0, _inherits3['default'])(EditableRow, _Component);

    function EditableRow() {
        (0, _classCallCheck3['default'])(this, EditableRow);

        var _a;

        var _this = (0, _possibleConstructorReturn3['default'])(this, (EditableRow.__proto__ || Object.getPrototypeOf(EditableRow)).apply(this, arguments));

        _this.state = {
            relastionSelectParentValue: (_a = _this.props.record) === null || _a === void 0 ? void 0 : _a[_this.props.dataIndex]
        };
        _this.dateTimePickerChange = function (date, dateString, dataIndex) {
            if (_this.form) {
                _this.form.setFieldsValue((0, _defineProperty3['default'])({}, dataIndex, dateString));
            }
        };
        _this.getInputComponent = function (type) {
            var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
            var width = arguments[2];
            var dataIndex = arguments[3];
            var value = arguments[4];

            if (typeof type === 'function') {
                // 自定义编辑类型
                return type();
            } else {
                switch (type) {
                    case 'number':
                        return _react2['default'].createElement(_inputNumber2['default'], null);
                    case 'date':
                        return _react2['default'].createElement(_datePicker2['default'], null);
                    case 'datetime':
                        return _react2['default'].createElement(
                            'div',
                            null,
                            _react2['default'].createElement(_datePicker2['default'], { defaultValue: (0, _moment2['default'])(value, DATE_TIME_FORMAT), showTime: true, onChange: function onChange(date, dateString) {
                                    return _this.dateTimePickerChange(date, dateString, dataIndex);
                                } })
                        );
                    case 'select':
                        return _react2['default'].createElement(_select2['default'], { options: options });
                    case 'textarea':
                        return _react2['default'].createElement(TextArea, null);
                    case 'text':
                        return _react2['default'].createElement(_input2['default'], null);
                    case 'radio':
                        return _react2['default'].createElement(_radio2['default'].Group, { options: options });
                    case 'checkbox':
                        return _react2['default'].createElement(_checkbox2['default'].Group, { options: options });
                    case 'treeSelect':
                        return _react2['default'].createElement(_treeSelect2['default'], { showSearch: true, allowClear: true, labelInValue: true, style: { width: width }, dropdownStyle: { maxHeight: 400, overflow: 'auto' }, treeData: options, placeholder: 'Please select', treeDefaultExpandAll: true });
                    case 'multiTreeSelect':
                        return _react2['default'].createElement(_treeSelect2['default'], { multiple: true, showSearch: true, labelInValue: true, allowClear: true, style: { width: width }, dropdownStyle: { maxHeight: 400, overflow: 'auto' }, treeData: options, placeholder: 'Please select', treeDefaultExpandAll: true });
                    default:
                        break;
                }
            }
        };
        _this.getInitValue = function (type, value, initValue) {
            if (typeof type === 'function' && typeof initValue === 'function') {
                return initValue(value);
            } else {
                switch (type) {
                    case 'number':
                        return Number(value);
                    case 'date':
                        if (value) {
                            return (0, _moment2['default'])(value, DATE_FORMAT);
                        }
                        return '';
                    case 'datetime':
                        return (0, _moment2['default'])(value, DATE_TIME_FORMAT);
                    case 'select':
                    case 'text':
                    case 'textarea':
                        return value;
                    case 'treeSelect':
                        if (value) {
                            // return { label: '', value }
                            if (value.value) {
                                return value;
                            }
                            return { label: '', value: value };
                        }
                        return null;
                    case 'multiTreeSelect':
                        if (value && Array.isArray(value)) {
                            // return value.map(v => v.value)
                            return value;
                        }
                        return null;
                    default:
                        return value;
                }
            }
        };
        _this.handleRender = function (editType, restProps) {
            if (editType === 'checkbox') {
                return String(restProps.children.filter(function (v) {
                    return v;
                }));
            }
            return restProps.children;
        };
        return _this;
    }

    (0, _createClass3['default'])(EditableRow, [{
        key: 'componentDidUpdate',
        value: function componentDidUpdate() {
            if (this.props.relationKey && this.form) {
                var values = this.form.getFieldsValue();
                if (this.state.relastionSelectParentValue !== values[this.props.dataIndex]) {
                    this.form.setFieldsValue((0, _defineProperty3['default'])({}, this.props.relationKey, this.state.relastionSelectParentValue ? '' : values[this.props.relationKey]));
                    this.setState({
                        relastionSelectParentValue: values[this.props.dataIndex]
                    });
                }
            }
        }
    }, {
        key: 'save',
        value: function save(form, columnMap) {
            var _props = this.props,
                record = _props.record,
                handleSave = _props.handleSave,
                toggleEditRow = _props.toggleEditRow;

            form.validateFields(function (error, values) {
                if (error) {
                    return;
                }
                // eslint-disable-next-line no-unused-vars
                for (var v in values) {
                    if (values[v] instanceof _moment2['default']) {
                        var type = columnMap && columnMap[v] || 'date';
                        values[v] = values[v].format(type === 'datetime' ? DATE_TIME_FORMAT : DATE_FORMAT);
                    }
                }
                toggleEditRow();
                handleSave((0, _extends3['default'])((0, _extends3['default'])({}, record), values), 'save');
            });
        }
    }, {
        key: 'cancel',
        value: function cancel() {
            var _props2 = this.props,
                record = _props2.record,
                handleSave = _props2.handleSave,
                toggleEditRow = _props2.toggleEditRow;

            toggleEditRow();
            handleSave(record, "cancel");
        }
    }, {
        key: 'render',
        value: function render() {
            var _this2 = this;

            var _a = this.props,
                width = _a.width,
                editing = _a.editing,
                dataIndex = _a.dataIndex,
                title = _a.title,
                editType = _a.editType,
                editRules = _a.editRules,
                editOptions = _a.editOptions,
                editInitValue = _a.editInitValue,
                record = _a.record,
                keyValue = _a.keyValue,
                toggleEditRow = _a.toggleEditRow,
                editContent = _a.editContent,
                saveContent = _a.saveContent,
                cancelContent = _a.cancelContent,
                restProps = __rest(_a, ["width", "editing", "dataIndex", "title", "editType", "editRules", "editOptions", "editInitValue", "record", "keyValue", "toggleEditRow", "editContent", "saveContent", "cancelContent"]);
            if (dataIndex === 'edit') {
                return _react2['default'].createElement(
                    'td',
                    null,
                    editing ? _react2['default'].createElement(
                        'span',
                        null,
                        _react2['default'].createElement(
                            EditableContext.Consumer,
                            null,
                            function (_ref2) {
                                var form = _ref2.form,
                                    columnMap = _ref2.columnMap;
                                return _react2['default'].createElement(
                                    _react2['default'].Fragment,
                                    null,
                                    _react2['default'].createElement(
                                        'a',
                                        { onClick: function onClick() {
                                                return _this2.save(form, columnMap);
                                            }, style: { marginRight: 8 } },
                                        saveContent
                                    ),
                                    _react2['default'].createElement(
                                        'a',
                                        { onClick: function onClick() {
                                                return _this2.cancel();
                                            } },
                                        cancelContent
                                    )
                                );
                            }
                        )
                    ) :
                    // eslint-disable-next-line jsx-a11y/anchor-is-valid
                    _react2['default'].createElement(
                        'a',
                        { onClick: function onClick() {
                                return toggleEditRow(keyValue, record, 'edit');
                            } },
                        editContent
                    ),
                    '\xA0\xA0',
                    restProps.children
                );
            } else {
                return _react2['default'].createElement(
                    EditableContext.Consumer,
                    null,
                    function (_ref3) {
                        var form = _ref3.form;
                        var getFieldDecorator = form.getFieldDecorator;

                        _this2.form = form;
                        return _react2['default'].createElement(
                            'td',
                            null,
                            editing ? _react2['default'].createElement(
                                FormItem,
                                { style: { margin: 0 } },
                                getFieldDecorator(dataIndex, (0, _extends3['default'])((0, _extends3['default'])({}, editRules && editRules.length ? { rules: editRules } : {}), { initialValue: _this2.getInitValue(editType, record[dataIndex], editInitValue) }))(_this2.getInputComponent(editType, editOptions, width, dataIndex, record[dataIndex]))
                            ) : _this2.handleRender(editType, restProps)
                        );
                    }
                );
            }
        }
    }]);
    return EditableRow;
}(_react.Component);