function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); }
function _extends() { _extends = Object.assign ? Object.assign.bind() : function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; }
function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return _typeof(key) === "symbol" ? key : String(key); }
function _toPrimitive(input, hint) { if (_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, "prototype", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); }
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); }
function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
import React, { Component } from 'react';
// import { Mode } from "rc-select/lib/interface";
import Select from "antd/es/select";
import Table from "antd/es/table";
import PropTypes from 'prop-types';
// @ts-ignore
import cloneDeep from 'lodash/cloneDeep';
// @ts-ignore
import isEqual from 'lodash/isEqual';
// import PagePoint from '../PagePoint/index';
var Option = Select.Option;
var transfer = function transfer(item) {
  return item ? item.toString().toLowerCase() : item;
};
var TableSelect = /*#__PURE__*/function (_Component) {
  _inherits(TableSelect, _Component);
  var _super = _createSuper(TableSelect);
  function TableSelect(props) {
    var _this;
    _classCallCheck(this, TableSelect);
    _this = _super.call(this, props);
    _this.lock = void 0;
    _this.select = void 0;
    _this.origValue = void 0;
    _this.setRef = function (select) {
      _this.select = select;
    };
    _this.onDropdownVisibleChange = function (open) {
      if (_this.lock) {
        // https://github.com/ant-design/ant-design/issues/13448#issuecomment-449225691
        _this.select.focus();
        return;
      }
      _this.setState({
        open: open,
        update: true
      });
    };
    _this.clickRow = function (record) {
      var _this$props = _this.props,
        mode = _this$props.selectProps.mode,
        _this$props$tableProp = _this$props.tableProps,
        rowKey = _this$props$tableProp.rowKey,
        dataSource = _this$props$tableProp.dataSource;
      if (mode === 'multiple') {
        // 多选情况下 选择完不关闭下拉框
        // https://github.com/ant-design/ant-design/issues/13448#issuecomment-444522006
        clearTimeout(_this.lock);
        _this.lock = setTimeout(function () {
          _this.lock = null;
        }, 100);
      } else if (record) {
        _this.setState({
          value: record[rowKey],
          tableData: dataSource,
          update: true
        });
        // this.triggerChange(record[rowKey]);
      }
    };
    // triggerChange = value =>{
    //     const {[regKey]: dataRegId, onChange } = this.props as any;
    //     const valueStr = JSON.stringify(value);
    //     if (dataRegId) {
    //         sendPagePoint({ eventType: clickType, tagname: 'tableSelect', value: valueStr,  [regKey]: dataRegId, origValue: this.origValue });
    //         this.origValue = valueStr;
    //     }
    //     onChange && onChange(value);
    // }
    _this.renderOptions = function (data) {
      var arr = [];
      var _this$props$tableProp2 = _this.props.tableProps,
        rowKey = _this$props$tableProp2.rowKey,
        display = _this$props$tableProp2.display;
      var _iterator = _createForOfIteratorHelper(data),
        _step;
      try {
        for (_iterator.s(); !(_step = _iterator.n()).done;) {
          var item = _step.value;
          arr.push( /*#__PURE__*/React.createElement(Option, {
            key: item[rowKey],
            value: item[rowKey]
          }, item[display]));
        }
      } catch (err) {
        _iterator.e(err);
      } finally {
        _iterator.f();
      }
      return arr;
    };
    _this.deselect = function (val) {
      var value = _this.state.value;
      // this.triggerChange((value as string[]).filter(item => 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 _this$props$tableProp3 = _this.props.tableProps,
        dataSource = _this$props$tableProp3.dataSource,
        columns = _this$props$tableProp3.columns,
        display = _this$props$tableProp3.display;
      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$props2 = _this.props,
      _value = _this$props2.value,
      _mode = _this$props2.selectProps.mode,
      _dataSource = _this$props2.tableProps.dataSource;
    _this.state = {
      value: _value || (_mode === 'multiple' ? [] : ''),
      open: false,
      update: false,
      tableData: cloneDeep(_dataSource)
    };
    _this.lock = null;
    return _this;
  }
  _createClass(TableSelect, [{
    key: "render",
    value: function render() {
      var _this2 = this;
      var _this$state = this.state,
        value = _this$state.value,
        open = _this$state.open,
        tableData = _this$state.tableData;
      var _this$props3 = this.props,
        tableProps = _this$props3.tableProps,
        selectProps = _this$props3.selectProps,
        mode = _this$props3.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 = _objectSpread(_objectSpread(_objectSpread({}, tableProps), tableMultiOpts), {}, {
        dataSource: tableData,
        bordered: false,
        pagination: false
      });
      var selectOpts = _objectSpread(_objectSpread(_objectSpread({}, selectProps), selectMultiOpts), {}, {
        open: open,
        value: value,
        onDropdownVisibleChange: this.onDropdownVisibleChange,
        onSearch: this.searchTable,
        dropdownRender: function dropdownRender() {
          return (
            /*#__PURE__*/
            // @ts-ignore
            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 (
        /*#__PURE__*/
        // @ts-ignore
        React.createElement(Select, _extends({
          ref: this.setRef
        }, selectOpts), options)
      );
    }
  }], [{
    key: "getDerivedStateFromProps",
    value: function getDerivedStateFromProps(nextProps, prevState) {
      if (!isEqual(nextProps.tableProps.dataSource, prevState.tableData)) {
        if (nextProps.update === prevState.update) {
          return {
            tableData: cloneDeep(nextProps.tableProps.dataSource)
          };
        } else {
          return {
            update: false
          };
        }
      }
      if (!isEqual(nextProps.value, prevState.value)) {
        if (nextProps.update === prevState.update) {
          return {
            value: nextProps.value
          };
        } else {
          return {
            update: false
          };
        }
      }
      return null;
    }
  }]);
  return TableSelect;
}(Component);
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
};
export { TableSelect as default };