'use strict';

Object.defineProperty(exports, "__esModule", {
    value: true
});
exports.EditableCell = exports.EditableFormCell = 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 _merge = require('lodash/merge');

var _merge2 = _interopRequireDefault(_merge);

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 _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 Option = _select2['default'].Option;

var DATE_FORMAT = 'YYYY-MM-DD';
var DATE_TIME_FORMAT = 'YYYY-MM-DD HH:mm:ss';
var EditableRow = function EditableRow(_a) {
    var form = _a.form,
        index = _a.index,
        moveRow = _a.moveRow,
        props = __rest(_a, ["form", "index", "moveRow"]);

    return _react2['default'].createElement(
        EditableContext.Provider,
        { value: form },
        moveRow ? _react2['default'].createElement(_dragTable.DragableBodyRow, (0, _extends3['default'])({ index: index, moveRow: moveRow }, props)) : _react2['default'].createElement('tr', props)
    );
};
var EditableFormCell = exports.EditableFormCell = _form2['default'].create()(EditableRow);
// 根据链式key找出value
var findValueByMultiKey = function findValueByMultiKey(obj) {
    var prop = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';

    if (prop.includes('.')) {
        var props = prop.split('.');
        var value = void 0;
        props.forEach(function (key, index) {
            if (index === 0) {
                value = obj[key];
            } else if (value) {
                value = value[key];
            }
        });
        return value;
    }
    return obj[prop];
};

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

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

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

        _this.state = {
            editing: false
        };
        _this.dateTimePickerChange = function (date, dateString, dataIndex) {
            if (_this.form) {
                _this.form.setFieldsValue((0, _defineProperty3['default'])({}, dataIndex, dateString));
            }
        };
        /* eslint-disable */
        _this.toggleEdit = function () {
            var editing = !_this.state.editing;
            _this.setState({ editing: editing }, function () {
                if (editing) {
                    _this.input.focus();
                }
            });
        };
        _this.save = function () {
            var _this$props = _this.props,
                editType = _this$props.editType,
                record = _this$props.record,
                handleSave = _this$props.handleSave;

            _this.form.validateFields(function (error, values) {
                if (error) {
                    return;
                }
                for (var v in values) {
                    if (values[v] instanceof _moment2['default']) {
                        values[v] = editType === 'datetime' ? values[v].format(DATE_TIME_FORMAT) : values[v].format(DATE_FORMAT);
                    }
                }
                _this.toggleEdit();
                handleSave((0, _merge2['default'])(record, values), 'saveCell');
            });
        };
        _this.handleOpenChange = function (open) {
            if (open) {
                _this.input.focus();
            }
        };
        _this.getInputComponent = function (type) {
            var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
            var optionsLabel = arguments[2];
            var optionsValue = arguments[3];
            var dataIndex = arguments[4];
            var initialValue = arguments[5];

            var opts = {
                ref: function ref(node) {
                    _this.input = node;
                },
                onBlur: _this.save
            };
            if (initialValue) {
                opts.defaultValue = initialValue;
            }
            if (typeof type === 'function') {
                //自定义编辑类型
                return type();
            } else {
                var children = [];
                options.forEach(function (item) {
                    children.push(_react2['default'].createElement(
                        Option,
                        { key: item[optionsValue], value: item[optionsValue] },
                        item[optionsLabel]
                    ));
                });
                switch (type) {
                    case 'number':
                        return _react2['default'].createElement(_inputNumber2['default'], opts);
                    case 'date':
                        return _react2['default'].createElement(_datePicker2['default'], (0, _extends3['default'])({}, opts, { onOpenChange: _this.handleOpenChange }));
                    case 'datetime':
                        return _react2['default'].createElement(
                            'div',
                            { ref: opts.ref, onBlur: opts.onBlur },
                            _react2['default'].createElement(_datePicker2['default'], { defaultValue: opts.defaultValue, showTime: true, onOpenChange: _this.handleOpenChange, onChange: function onChange(date, dateString) {
                                    return _this.dateTimePickerChange(date, dateString, dataIndex);
                                } })
                        );
                    case 'select':
                        return _react2['default'].createElement(
                            _select2['default'],
                            opts,
                            children
                        );
                    case 'textarea':
                        return _react2['default'].createElement(TextArea, (0, _extends3['default'])({}, opts, { onPressEnter: _this.save }));
                    case 'text':
                        return _react2['default'].createElement(_input2['default'], (0, _extends3['default'])({}, opts, { onPressEnter: _this.save }));
                    default:
                        return _react2['default'].createElement(_input2['default'], (0, _extends3['default'])({}, opts, { onPressEnter: _this.save }));
                }
            }
        };
        _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':
                        return (0, _moment2['default'])(value, DATE_FORMAT);
                    case 'datetime':
                        return (0, _moment2['default'])(value, DATE_TIME_FORMAT);
                    case 'select':
                    case 'text':
                    case 'textarea':
                        return value;
                    default:
                        return value;
                }
            }
        };
        return _this;
    }

    (0, _createClass3['default'])(EditableCell, [{
        key: 'render',
        value: function render() {
            var _this2 = this;

            var editing = this.state.editing;
            var _a = this.props,
                editable = _a.editable,
                dataIndex = _a.dataIndex,
                editType = _a.editType,
                editRules = _a.editRules,
                editOptions = _a.editOptions,
                optionsLabel = _a.optionsLabel,
                optionsValue = _a.optionsValue,
                editInitValue = _a.editInitValue,
                title = _a.title,
                record = _a.record,
                restProps = __rest(_a, ["editable", "dataIndex", "editType", "editRules", "editOptions", "optionsLabel", "optionsValue", "editInitValue", "title", "record"]);
            return _react2['default'].createElement(
                'td',
                { ref: function ref(node) {
                        _this2.cell = node;
                    } },
                editable && dataIndex ? _react2['default'].createElement(
                    EditableContext.Consumer,
                    null,
                    function (form) {
                        _this2.form = form;
                        var config = {
                            initialValue: _this2.getInitValue(editType, findValueByMultiKey(record, dataIndex), editInitValue)
                        };
                        if (editRules) {
                            config.rules = editRules;
                        }
                        return editing ? _react2['default'].createElement(
                            FormItem,
                            { style: { margin: 0 } },
                            form.getFieldDecorator(dataIndex, (0, _extends3['default'])({}, config))(_this2.getInputComponent(editType, editOptions, optionsLabel, optionsValue, dataIndex, editType === 'datetime' ? config.initialValue : null))
                        ) : _react2['default'].createElement(
                            'div',
                            { className: 'editable-cell-value-wrap', style: { paddingRight: 24 }, onClick: _this2.toggleEdit },
                            restProps.children
                        );
                    }
                ) : restProps.children
            );
        }
    }]);
    return EditableCell;
}(_react.Component);