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 Form from '../form';
import Input from '../input';
import InputNumber from '../input-number';
import Select from '../select';
import DatePicker from '../date-picker';
import TreeSelect from '../tree-select';
import Radio from '../radio';
import Checkbox from '../checkbox';
import { DragableBodyRow } from './dragTable';
var FormItem = Form.Item;
var EditableContext = React.createContext(null);
var TextArea = Input.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 React.createElement(
        EditableContext.Provider,
        { value: { form: form, columnMap: columnMap } },
        moveRow ? React.createElement(DragableBodyRow, _extends({ index: index, moveRow: moveRow }, props)) : React.createElement('tr', props)
    );
};
export var EditableFormRow = Form.create()(Editablerow);
export var EditableRow = function (_Component) {
    _inherits(EditableRow, _Component);

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

        var _this = _possibleConstructorReturn(this, (EditableRow.__proto__ || Object.getPrototypeOf(EditableRow)).apply(this, arguments));

        _this.dateTimePickerChange = function (date, dateString, dataIndex) {
            if (_this.form) {
                _this.form.setFieldsValue(_defineProperty({}, 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 React.createElement(InputNumber, null);
                    case 'date':
                        return React.createElement(DatePicker, null);
                    case 'datetime':
                        return React.createElement(
                            'div',
                            null,
                            React.createElement(DatePicker, { defaultValue: moment(value, DATE_TIME_FORMAT), showTime: true, onChange: function onChange(date, dateString) {
                                    return _this.dateTimePickerChange(date, dateString, dataIndex);
                                } })
                        );
                    case 'select':
                        return React.createElement(Select, { options: options });
                    case 'textarea':
                        return React.createElement(TextArea, null);
                    case 'text':
                        return React.createElement(Input, null);
                    case 'radio':
                        return React.createElement(Radio.Group, { options: options });
                    case 'checkbox':
                        return React.createElement(Checkbox.Group, { options: options });
                    case 'treeSelect':
                        return React.createElement(TreeSelect, { showSearch: true, allowClear: true, labelInValue: true, style: { width: width }, dropdownStyle: { maxHeight: 400, overflow: 'auto' }, treeData: options, placeholder: 'Please select', treeDefaultExpandAll: true });
                    case 'multiTreeSelect':
                        return React.createElement(TreeSelect, { 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':
                        return moment(value, DATE_FORMAT);
                    case 'datetime':
                        return moment(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;
    }

    _createClass(EditableRow, [{
        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 moment) {
                        var type = columnMap && columnMap[v] || 'date';
                        values[v] = values[v].format(type === 'datetime' ? DATE_TIME_FORMAT : DATE_FORMAT);
                    }
                }
                toggleEditRow();
                handleSave(_extends(_extends({}, record), values), 'save');
            });
        }
    }, {
        key: 'cancel',
        value: function cancel(form) {
            var _props2 = this.props,
                record = _props2.record,
                handleSave = _props2.handleSave,
                toggleEditRow = _props2.toggleEditRow;

            form.validateFields(function (error) {
                if (error) {
                    return;
                }
                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 React.createElement(
                    'td',
                    null,
                    editing ? React.createElement(
                        'span',
                        null,
                        React.createElement(
                            EditableContext.Consumer,
                            null,
                            function (_ref2) {
                                var form = _ref2.form,
                                    columnMap = _ref2.columnMap;
                                return React.createElement(
                                    React.Fragment,
                                    null,
                                    React.createElement(
                                        'a',
                                        { onClick: function onClick() {
                                                return _this2.save(form, columnMap);
                                            }, style: { marginRight: 8 } },
                                        saveContent
                                    ),
                                    React.createElement(
                                        'a',
                                        { onClick: function onClick() {
                                                return _this2.cancel(form);
                                            } },
                                        cancelContent
                                    )
                                );
                            }
                        )
                    ) :
                    // eslint-disable-next-line jsx-a11y/anchor-is-valid
                    React.createElement(
                        'a',
                        { onClick: function onClick() {
                                return toggleEditRow(keyValue, record, 'edit');
                            } },
                        editContent
                    ),
                    '\xA0\xA0',
                    restProps.children
                );
            } else {
                return React.createElement(
                    EditableContext.Consumer,
                    null,
                    function (_ref3) {
                        var form = _ref3.form;
                        var getFieldDecorator = form.getFieldDecorator;

                        _this2.form = form;
                        return React.createElement(
                            'td',
                            null,
                            editing ? React.createElement(
                                FormItem,
                                { style: { margin: 0 } },
                                getFieldDecorator(dataIndex, _extends(_extends({}, 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;
}(Component);