import _defineProperty from 'babel-runtime/helpers/defineProperty';
import _classCallCheck from 'babel-runtime/helpers/classCallCheck';
import _createClass from 'babel-runtime/helpers/createClass';
import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn';
import _inherits from 'babel-runtime/helpers/inherits';
import _extends from 'babel-runtime/helpers/extends';
var __rest = this && this.__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;
};
import React, { Component } from 'react';
import moment from 'moment';
import merge from 'lodash/merge';
import Form from '../form';
import Input from '../input';
import InputNumber from '../input-number';
import Select from '../select';
import DatePicker from '../date-picker';
import { DragableBodyRow } from './dragTable';
var FormItem = Form.Item;
var EditableContext = React.createContext(null);
var TextArea = Input.TextArea;
var Option = Select.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 React.createElement(
        EditableContext.Provider,
        { value: form },
        moveRow ? React.createElement(DragableBodyRow, _extends({ index: index, moveRow: moveRow }, props)) : React.createElement('tr', props)
    );
};
export var EditableFormCell = Form.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];
};
export var EditableCell = function (_Component) {
    _inherits(EditableCell, _Component);

    function EditableCell() {
        _classCallCheck(this, EditableCell);

        var _this = _possibleConstructorReturn(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(_defineProperty({}, 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 moment) {
                        values[v] = editType === 'datetime' ? values[v].format(DATE_TIME_FORMAT) : values[v].format(DATE_FORMAT);
                    }
                }
                _this.toggleEdit();
                handleSave(merge(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(React.createElement(
                        Option,
                        { key: item[optionsValue], value: item[optionsValue] },
                        item[optionsLabel]
                    ));
                });
                switch (type) {
                    case 'number':
                        return React.createElement(InputNumber, opts);
                    case 'date':
                        return React.createElement(DatePicker, _extends({}, opts, { onOpenChange: _this.handleOpenChange }));
                    case 'datetime':
                        return React.createElement(
                            'div',
                            { ref: opts.ref, onBlur: opts.onBlur },
                            React.createElement(DatePicker, { defaultValue: opts.defaultValue, showTime: true, onOpenChange: _this.handleOpenChange, onChange: function onChange(date, dateString) {
                                    return _this.dateTimePickerChange(date, dateString, dataIndex);
                                } })
                        );
                    case 'select':
                        return React.createElement(
                            Select,
                            opts,
                            children
                        );
                    case 'textarea':
                        return React.createElement(TextArea, _extends({}, opts, { onPressEnter: _this.save }));
                    case 'text':
                        return React.createElement(Input, _extends({}, opts, { onPressEnter: _this.save }));
                    default:
                        return React.createElement(Input, _extends({}, 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 moment(value, DATE_FORMAT);
                    case 'datetime':
                        return moment(value, DATE_TIME_FORMAT);
                    case 'select':
                    case 'text':
                    case 'textarea':
                        return value;
                    default:
                        return value;
                }
            }
        };
        return _this;
    }

    _createClass(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 React.createElement(
                'td',
                { ref: function ref(node) {
                        _this2.cell = node;
                    } },
                editable && dataIndex ? React.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 ? React.createElement(
                            FormItem,
                            { style: { margin: 0 } },
                            form.getFieldDecorator(dataIndex, _extends({}, config))(_this2.getInputComponent(editType, editOptions, optionsLabel, optionsValue, dataIndex, editType === 'datetime' ? config.initialValue : null))
                        ) : React.createElement(
                            'div',
                            { className: 'editable-cell-value-wrap', style: { paddingRight: 24 }, onClick: _this2.toggleEdit },
                            restProps.children
                        );
                    }
                ) : restProps.children
            );
        }
    }]);

    return EditableCell;
}(Component);