import _defineProperty from "babel-runtime/helpers/defineProperty";
import _extends from "babel-runtime/helpers/extends";
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 React, { Component } from "react";
// import { Mode } from "rc-select/lib/interface";
import Select from "../select";
import Table from "../table";
import PropTypes from "prop-types";
import cloneDeep from "lodash/cloneDeep";
import isEqual from "lodash/isEqual";
import PagePoint from "../page-point/index";
var Option = Select.Option;
var sendPagePoint = PagePoint.sendPagePoint,
    regKey = PagePoint.pagePointConfig.regKey,
    clickType = PagePoint.EventType.clickType;

var transfer = function transfer(item) {
    return item ? item.toString().toLowerCase() : item;
};

var TableSelect = function (_Component) {
    _inherits(TableSelect, _Component);

    function TableSelect(props) {
        _classCallCheck(this, TableSelect);

        var _this = _possibleConstructorReturn(this, (TableSelect.__proto__ || Object.getPrototypeOf(TableSelect)).call(this, props));

        _this.setRef = function (select) {
            _this.select = select;
        };
        _this.onDropdownVisibleChange = function (open) {
            var dataSource = _this.props.tableProps.dataSource;

            _this.setState(_extends({ open: open, update: true }, open ? { tableData: dataSource } : {}));
        };
        _this.clickRow = function (record) {
            var _this$props = _this.props,
                mode = _this$props.selectProps.mode,
                rowKey = _this$props.tableProps.rowKey;
            var value = _this.state.value;

            if (record && mode !== "multiple") {
                _this.setState({ value: record[rowKey], open: false, update: true });
                if (value !== record[rowKey]) {
                    _this.triggerChange(record[rowKey]);
                }
            }
        };
        _this.triggerChange = function (value) {
            var _this$props2 = _this.props,
                dataRegId = _this$props2[regKey],
                onChange = _this$props2.onChange;

            var valueStr = JSON.stringify(value);
            if (dataRegId) {
                var _sendPagePoint;

                sendPagePoint((_sendPagePoint = {
                    eventType: clickType,
                    tagname: "tableSelect",
                    value: valueStr
                }, _defineProperty(_sendPagePoint, regKey, dataRegId), _defineProperty(_sendPagePoint, "origValue", _this.origValue), _sendPagePoint));
                _this.origValue = valueStr;
            }
            onChange && onChange(value);
        };
        _this.renderOptions = function (data) {
            var arr = [];
            var _this$props$tableProp = _this.props.tableProps,
                rowKey = _this$props$tableProp.rowKey,
                display = _this$props$tableProp.display;
            var _iteratorNormalCompletion = true;
            var _didIteratorError = false;
            var _iteratorError = undefined;

            try {
                for (var _iterator = data[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
                    var item = _step.value;

                    arr.push(React.createElement(
                        Option,
                        { key: item[rowKey], value: item[rowKey] },
                        item[display]
                    ));
                }
            } catch (err) {
                _didIteratorError = true;
                _iteratorError = err;
            } finally {
                try {
                    if (!_iteratorNormalCompletion && _iterator["return"]) {
                        _iterator["return"]();
                    }
                } finally {
                    if (_didIteratorError) {
                        throw _iteratorError;
                    }
                }
            }

            return arr;
        };
        _this.deselect = function (val) {
            var value = _this.state.value;

            _this.triggerChange(value.filter(function (item) {
                return item !== val;
            }));
            _this.setState(function (prevState) {
                return {
                    value: prevState.value.filter(function (item) {
                        return item !== val;
                    }),
                    update: true
                };
            });
        };
        _this.selectChange = function (selectedRowKeys) {
            var dataSource = _this.props.tableProps.dataSource;

            _this.triggerChange(selectedRowKeys);
            _this.setState({
                value: selectedRowKeys,
                tableData: dataSource,
                update: true
            });
        };
        _this.searchTable = function (value) {
            // columns key依次模糊匹配
            var open = _this.state.open;
            var _this$props$tableProp2 = _this.props.tableProps,
                dataSource = _this$props$tableProp2.dataSource,
                columns = _this$props$tableProp2.columns,
                display = _this$props$tableProp2.display;

            if (open) {
                var keys = columns.map(function (v) {
                    if (v.dataIndex !== display) {
                        return v.dataIndex;
                    }
                    return null;
                }).filter(function (v) {
                    return v;
                });
                var res = value ? dataSource.filter(function (item) {
                    if (transfer(item[display]).includes(transfer(value))) {
                        return true;
                    }
                    for (var i = 0; i < keys.length; i += 1) {
                        if (item[keys[i]] && transfer(item[keys[i]]).includes(transfer(value))) {
                            return true;
                        }
                    }
                    return false;
                }) : dataSource;
                _this.setState({ tableData: res, update: true });
            }
        };
        var _this$props3 = _this.props,
            value = _this$props3.value,
            mode = _this$props3.selectProps.mode,
            dataSource = _this$props3.tableProps.dataSource;

        _this.state = {
            value: value || (mode === "multiple" ? [] : ""),
            open: false,
            update: false,
            tableData: cloneDeep(dataSource)
        };
        return _this;
    }

    _createClass(TableSelect, [{
        key: "render",
        value: function render() {
            var _this2 = this;

            var _state = this.state,
                value = _state.value,
                open = _state.open,
                tableData = _state.tableData;
            var _props = this.props,
                tableProps = _props.tableProps,
                selectProps = _props.selectProps,
                mode = _props.selectProps.mode;

            var options = this.renderOptions(tableData);
            var rowSelection = {
                selectedRowKeys: value || [],
                onChange: this.selectChange
            };
            var tableMultiOpts = mode === "multiple" ? { rowSelection: rowSelection } : {};
            var selectMultiOpts = mode === "multiple" ? { onDeselect: this.deselect } : {};
            var tableOpts = _extends(_extends(_extends({}, tableProps), tableMultiOpts), { dataSource: tableData, bordered: false });
            var selectOpts = _extends(_extends(_extends({}, selectProps), selectMultiOpts), { open: open,
                value: value, onDropdownVisibleChange: this.onDropdownVisibleChange, onSearch: this.searchTable, dropdownRender: function dropdownRender() {
                    return React.createElement(Table, _extends({}, tableOpts, { onRow: function onRow(record) {
                            return {
                                onMouseDown: function onMouseDown() {
                                    _this2.clickRow(record);
                                }
                            };
                        }, onHeaderRow: function onHeaderRow() {
                            return {
                                onMouseDown: function onMouseDown() {
                                    _this2.clickRow(null);
                                }
                            };
                        } }));
                } });
            return React.createElement(
                Select,
                _extends({ ref: this.setRef }, selectOpts),
                options
            );
        }
    }], [{
        key: "getDerivedStateFromProps",
        value: function getDerivedStateFromProps(nextProps, prevState) {
            var changeObj = {};
            if (!isEqual(nextProps.tableProps.dataSource, prevState.tableData)) {
                if (nextProps.update === prevState.update) {
                    changeObj.tableData = cloneDeep(nextProps.tableProps.dataSource);
                } else {
                    changeObj.update = false;
                }
            }
            if (!isEqual(nextProps.value, prevState.value)) {
                if (nextProps.update === prevState.update) {
                    changeObj.value = nextProps.value;
                } else {
                    changeObj.update = false;
                }
            }
            return Object.keys(changeObj).length ? changeObj : null;
        }
    }]);

    return TableSelect;
}(Component);

export default TableSelect;

TableSelect.propTypes = {
    /* eslint-disable */
    tableProps: PropTypes.shape({
        display: PropTypes.string.isRequired
    }),
    onChange: PropTypes.func,
    value: PropTypes.oneOfType([PropTypes.string, PropTypes.number, PropTypes.array])
};
TableSelect.defaultProps = {
    update: false
};