"use strict";

Object.defineProperty(exports, "__esModule", {
    value: true
});

var _defineProperty2 = require("babel-runtime/helpers/defineProperty");

var _defineProperty3 = _interopRequireDefault(_defineProperty2);

var _extends2 = require("babel-runtime/helpers/extends");

var _extends3 = _interopRequireDefault(_extends2);

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 _react = require("react");

var _react2 = _interopRequireDefault(_react);

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

var _select2 = _interopRequireDefault(_select);

var _table = require("../table");

var _table2 = _interopRequireDefault(_table);

var _propTypes = require("prop-types");

var _propTypes2 = _interopRequireDefault(_propTypes);

var _cloneDeep = require("lodash/cloneDeep");

var _cloneDeep2 = _interopRequireDefault(_cloneDeep);

var _isEqual = require("lodash/isEqual");

var _isEqual2 = _interopRequireDefault(_isEqual);

var _index = require("../page-point/index");

var _index2 = _interopRequireDefault(_index);

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

// import { Mode } from "rc-select/lib/interface";
var Option = _select2["default"].Option;
var sendPagePoint = _index2["default"].sendPagePoint,
    regKey = _index2["default"].pagePointConfig.regKey,
    clickType = _index2["default"].EventType.clickType;

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

var TableSelect = function (_Component) {
    (0, _inherits3["default"])(TableSelect, _Component);

    function TableSelect(props) {
        (0, _classCallCheck3["default"])(this, TableSelect);

        var _this = (0, _possibleConstructorReturn3["default"])(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((0, _extends3["default"])({ 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
                }, (0, _defineProperty3["default"])(_sendPagePoint, regKey, dataRegId), (0, _defineProperty3["default"])(_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(_react2["default"].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: (0, _cloneDeep2["default"])(dataSource)
        };
        return _this;
    }

    (0, _createClass3["default"])(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 = (0, _extends3["default"])((0, _extends3["default"])((0, _extends3["default"])({}, tableProps), tableMultiOpts), { dataSource: tableData, bordered: false });
            var selectOpts = (0, _extends3["default"])((0, _extends3["default"])((0, _extends3["default"])({}, selectProps), selectMultiOpts), { open: open,
                value: value, onDropdownVisibleChange: this.onDropdownVisibleChange, onSearch: this.searchTable, dropdownRender: function dropdownRender() {
                    return _react2["default"].createElement(_table2["default"], (0, _extends3["default"])({}, tableOpts, { onRow: function onRow(record) {
                            return {
                                onMouseDown: function onMouseDown() {
                                    _this2.clickRow(record);
                                }
                            };
                        }, onHeaderRow: function onHeaderRow() {
                            return {
                                onMouseDown: function onMouseDown() {
                                    _this2.clickRow(null);
                                }
                            };
                        } }));
                } });
            return _react2["default"].createElement(
                _select2["default"],
                (0, _extends3["default"])({ ref: this.setRef }, selectOpts),
                options
            );
        }
    }], [{
        key: "getDerivedStateFromProps",
        value: function getDerivedStateFromProps(nextProps, prevState) {
            var changeObj = {};
            if (!(0, _isEqual2["default"])(nextProps.tableProps.dataSource, prevState.tableData)) {
                if (nextProps.update === prevState.update) {
                    changeObj.tableData = (0, _cloneDeep2["default"])(nextProps.tableProps.dataSource);
                } else {
                    changeObj.update = false;
                }
            }
            if (!(0, _isEqual2["default"])(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;
}(_react.Component);

exports["default"] = TableSelect;

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