import _extends from "@babel/runtime/helpers/extends";
import _Select from "antd/es/select";
import _inheritsLoose from "@babel/runtime/helpers/inheritsLoose";
import _asyncToGenerator from "@babel/runtime/helpers/asyncToGenerator";
import _regeneratorRuntime from "@babel/runtime/regenerator";
import * as React from 'react';
// import './index.css';

function createTimeoutFun(func, threshold) {
  if (threshold === void 0) {
    threshold = 300;
  }
  function Timer() {
    this.threshold = threshold;
    this.func = func;
    this.val = [];
  }
  var _run = function _run(val) {
    window.setTimeout(function () {
      try {
        this.func.apply(this, this.val || []);
      } catch (e) {
        console.error(e);
      }
      this.run = _run;
    }.bind(this), this.threshold);
    this.run = function () {};
  };
  Timer.prototype.run = _run;
  var timer = new Timer();
  var init = function () {
    this.val = arguments;
    this.run.apply(this, this.val || []);
  }.bind(timer);
  return init;
}
function get(url) {
  return new Promise(function (resolve) {
    fetch(url).then( /*#__PURE__*/function () {
      var _ref = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee(res) {
        return _regeneratorRuntime.wrap(function _callee$(_context) {
          while (1) switch (_context.prev = _context.next) {
            case 0:
              if (!(res.json && typeof res.json === 'function')) {
                _context.next = 8;
                break;
              }
              _context.t0 = resolve;
              _context.next = 4;
              return res.json();
            case 4:
              _context.t1 = _context.sent;
              (0, _context.t0)(_context.t1);
              _context.next = 9;
              break;
            case 8:
              resolve(res);
            case 9:
            case "end":
              return _context.stop();
          }
        }, _callee);
      }));
      return function (_x) {
        return _ref.apply(this, arguments);
      };
    }());
  });
}
;
var SelectUser = /*#__PURE__*/function (_React$Component) {
  _inheritsLoose(SelectUser, _React$Component);
  function SelectUser(props) {
    var _this;
    _this = _React$Component.call(this, props) || this;
    _this.getInitOption = function (v) {
      var _this$props;
      // let url = `/api/privileges/searchUser?size=${this.props.searchSize || 100}`;
      var url = "/api/v1/user/list?size=" + (((_this$props = _this.props) === null || _this$props === void 0 ? void 0 : _this$props.searchSize) || 100);
      if (_this.props.url) {
        var _this$props2;
        url = _this.props.url + "?size=" + (((_this$props2 = _this.props) === null || _this$props2 === void 0 ? void 0 : _this$props2.searchSize) || 100);
      }
      if (v) {
        url += "&username=" + v;
      }
      get(url).then(function (data) {
        if (data.success) {
          var list = [].concat(((_this.props || {}).opts || []).filter(function (opt) {
            if (opt === void 0) {
              opt = {};
            }
            return (opt.chinese_name || '').includes(v || '') || (opt.user_name || '').includes(v || '');
          }), data.data.filter(function (dat) {
            return !_this.optsvalues.includes(dat.user_name);
          }));
          // 传进了默认值
          if (!v && _this.defaultValue) {
            var searchV;
            // let defaultVType;
            // 默认值是数组
            if (Object.prototype.toString.call(_this.defaultValue) === '[object Array]') {
              var searchList = _this.defaultValue.filter(function (item) {
                return !data.data.find(function (data) {
                  return data.user_name === item;
                });
              });
              searchV = searchList.join(',');
            } else if (typeof _this.defaultValue === 'string' && !data.data.find(function (item) {
              return item.user_name === _this.defaultValue;
            })) {
              searchV = _this.defaultValue;
            }
            // 默认值初始请求的列表里没有，单独请求，并加入列表，并设置值
            if (searchV) {
              var _this$props3;
              var _url = "/api/v1/user/list?size=" + (((_this$props3 = _this.props) === null || _this$props3 === void 0 ? void 0 : _this$props3.searchSize) || 100) + "&username=" + searchV;
              if (_this.props.url) {
                var _this$props4;
                _url = _this.props.url + "?size=" + (((_this$props4 = _this.props) === null || _this$props4 === void 0 ? void 0 : _this$props4.searchSize) || 100) + "&username=" + searchV;
              }
              get(_url).then(function (res) {
                if (res.success) {
                  list = [].concat(list).concat(res.data.filter(function (dat) {
                    return !_this.optsvalues.includes(dat.user_name);
                  }));
                  _this.setState({
                    userList: list,
                    value: _this.defaultValue
                  });
                }
              });
            } else {
              // 默认值初始值列表里有，设置值
              _this.setState({
                userList: list,
                value: _this.defaultValue
              });
            }
          } else {
            _this.setState({
              userList: list
            });
          }
        }
      });
    };
    _this.onChange = function (value) {
      _this.props.onChange && _this.props.onChange(value); // 整个用户信息给出，而不是只是id
      _this.setState({
        value: value
      });
    };
    _this.onSearch = createTimeoutFun(function (v) {
      _this.props.onSearch ? _this.props.onSearch(v) : null;
      _this.getInitOption(v);
    }, _this.props.timeout || 300);
    _this.onSelect = function (value) {
      var v = _this.state.userList.find(function (item) {
        return item.user_name === value;
      });
      _this.props.onSelect ? _this.props.onSelect(v) : null; // 整个用户信息给出，而不是只是id
    };
    _this.defaultValue = _this.props.defaultValue || _this.props.value; // form中的initialValues默认值是从props.value传递进来的
    _this.getInitOption();
    _this.optsvalues = ((_this.props || {}).opts || []).map(function (user) {
      return user.user_name;
    });
    _this.state = {
      userList: (_this.props || {}).opts || [],
      value: undefined,
      mode: _this.props.mode
    };
    console.log(props, _this.props);
    return _this;
  }
  var _proto = SelectUser.prototype;
  _proto.shouldComponentUpdate = function shouldComponentUpdate(nextProps, nextState, nextContext) {
    return true;
  };
  _proto.render = function render() {
    return /*#__PURE__*/React.createElement(_Select, _extends({
      style: {
        minWidth: 200
      },
      showSearch: true,
      filterOption: false,
      value: this.state.value
    }, this.props, {
      onSelect: this.onSelect,
      onChange: this.onChange,
      onSearch: this.onSearch
    }), this.state.userList.map(function (item) {
      return /*#__PURE__*/React.createElement(_Select.Option, {
        key: item.user_name,
        value: item.user_name
      }, item.chinese_name + "(" + item.user_name + ")");
    }));
  };
  return SelectUser;
}(React.Component);
/**
 * @param {*} param { key, exactMatch }
 *     key 搜索的名字 多个以逗号链接
 *     exactMatch 是否完全匹配  默认 false
 *     size 最多返回多少条 默认30
 * @param {string} url
 * @return {Promise} ==> [{ name, chineseName, ... }]
 */
export { SelectUser as default };
SelectUser.getUser = function (param, url) {
  var key = param.key,
    _param$exactMatch = param.exactMatch,
    exactMatch = _param$exactMatch === void 0 ? false : _param$exactMatch,
    valueName = param.valueName,
    _param$size = param.size,
    size = _param$size === void 0 ? 30 : _param$size;
  if (!key) {
    key = param;
  }
  return fetch.get(url ? url : "/api/v1/user/list", {
    username: key,
    exactMatch: exactMatch ? 1 : '',
    valueName: valueName,
    size: size
  }).then(function (res) {
    return res.data || [];
  });
};