"use strict";

function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports["default"] = void 0;

var _react = _interopRequireWildcard(require("react"));

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

var _classnames = _interopRequireDefault(require("classnames"));

var _lodash = require("lodash");

var _mkuiFd = require("mkui-fd");

var _util = require("./util");

var _noop = _interopRequireDefault(require("../_util/noop"));

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

function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }

function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; }

function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }

function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }

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 _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); }

function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }

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, descriptor.key, descriptor); } }

function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }

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 } }); if (superClass) _setPrototypeOf(subClass, superClass); }

function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || 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; } 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 : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

var Search = _mkuiFd.Input.Search;

var Panel = /*#__PURE__*/function (_React$Component) {
  _inherits(Panel, _React$Component);

  var _super = _createSuper(Panel);

  /** *******************life cycle************************** */
  function Panel(props) {
    var _this;

    _classCallCheck(this, Panel);

    _this = _super.call(this, props);

    _defineProperty(_assertThisInitialized(_this), "selectCategoryHandle", function (category) {
      var api = _this.props.api;
      var _this$state = _this.state,
          data = _this$state.data,
          selectedCodes = _this$state.selectedCodes;
      var params = {
        referenceDataCode: data.code,
        categoryCode: category.code
      };

      if (!category.inited) {
        _this.setState({
          spinning: true
        });

        api(params).then(function (response) {
          category.items = response.items;

          if (response.categories) {
            category.categories = response.categories;
          }

          category.inited = true;

          _this.setState({
            selectedCodes: [].concat(_toConsumableArray(selectedCodes), [category.code]),
            data: (0, _lodash.cloneDeep)(data),
            spinning: false
          });
        });
      } else {
        _this.setState({
          selectedCodes: [].concat(_toConsumableArray(selectedCodes), [category.code]),
          data: (0, _lodash.cloneDeep)(data)
        });
      }
    });

    _defineProperty(_assertThisInitialized(_this), "selectOptionHandle", function (option) {
      var onSelect = _this.props.onSelect;

      if (onSelect) {
        onSelect([(0, _lodash.pick)(option, ['name', 'code'])], option);
      }
    });

    _defineProperty(_assertThisInitialized(_this), "clickBreadcrumbHandle", function (item) {
      var selectedCodes = _this.state.selectedCodes;
      var codes = (0, _util.buildSelectedCodes)(selectedCodes, item.code);

      _this.setState({
        selectedCodes: codes
      });
    });

    _defineProperty(_assertThisInitialized(_this), "searchHandle", function (e) {
      var keywords = e.target.value.trim();

      if (keywords) {
        _this.search(keywords);
      } else {
        _this.setState({
          searchResult: null
        });
      }
    });

    _this.state = {
      data: {},
      selectedCodes: [],
      spinning: false
    };
    _this.search = (0, _lodash.debounce)(_this.search, 500);
    return _this;
  }
  /** *******************handle************************** */


  _createClass(Panel, [{
    key: "search",
    value:
    /** *******************inner method************************** */
    function search(keywords) {
      var _this2 = this;

      var api = this.props.api;
      this.setState({
        spinning: true
      });
      api({
        keywords: keywords
      }).then(function (response) {
        var result = (0, _util.getSearchResult)(response);

        _this2.setState({
          searchResult: result,
          spinning: false
        });
      });
    }
    /** *******************render************************** */

  }, {
    key: "renderSearchResult",
    value: function renderSearchResult() {
      var _this3 = this;

      var prefixCls = this.props.prefixCls;
      var searchResult = this.state.searchResult;
      return searchResult && searchResult.length > 0 ? /*#__PURE__*/_react["default"].createElement("ul", {
        className: "".concat(prefixCls, "-search-result")
      }, searchResult.map(function (item) {
        return /*#__PURE__*/_react["default"].createElement("li", {
          key: item.code,
          onClick: function onClick() {
            _this3.selectOptionHandle(item);
          }
        }, item.fullName.join(' / '));
      })) : /*#__PURE__*/_react["default"].createElement("div", {
        className: "".concat(prefixCls, "-search-empty")
      }, "\u672A\u641C\u7D22\u5230\u76F8\u5173\u8BB0\u5F55\u3002");
    }
  }, {
    key: "renderContent",
    value: function renderContent() {
      var _this4 = this;

      var prefixCls = this.props.prefixCls;
      var _this$state2 = this.state,
          data = _this$state2.data,
          selectedCodes = _this$state2.selectedCodes;
      var selectedData = (0, _util.buildSelectedData)(data, selectedCodes);
      var breadcrumbData = (0, _util.buildBreadcrumbData)(data, selectedCodes);
      var categories = selectedData.categories || [];
      var items = selectedData.items || [];
      var isEmpty = !categories.length && !items.length;
      return /*#__PURE__*/_react["default"].createElement(_react.Fragment, null, breadcrumbData && /*#__PURE__*/_react["default"].createElement("div", {
        className: "".concat(prefixCls, "-breadcrumbs")
      }, /*#__PURE__*/_react["default"].createElement(_mkuiFd.Breadcrumb, null, breadcrumbData.map(function (item, index, arr) {
        return index === arr.length - 1 ? /*#__PURE__*/_react["default"].createElement(_mkuiFd.Breadcrumb.Item, {
          key: item.code
        }, item.name) : /*#__PURE__*/_react["default"].createElement(_mkuiFd.Breadcrumb.Item, {
          key: item.code
        }, /*#__PURE__*/_react["default"].createElement("a", {
          onClick: function onClick() {
            return _this4.clickBreadcrumbHandle(item);
          }
        }, item.name));
      }))), /*#__PURE__*/_react["default"].createElement("div", {
        className: "".concat(prefixCls, "-list")
      }, isEmpty ? /*#__PURE__*/_react["default"].createElement("div", {
        className: "".concat(prefixCls, "-list-empty")
      }, "\u65E0\u9009\u9879\u5185\u5BB9") : /*#__PURE__*/_react["default"].createElement("ul", null, categories.map(function (item) {
        return /*#__PURE__*/_react["default"].createElement("li", {
          key: item.code,
          onClick: function onClick() {
            _this4.selectCategoryHandle(item);
          }
        }, /*#__PURE__*/_react["default"].createElement("span", null, /*#__PURE__*/_react["default"].createElement(_mkuiFd.Icon, {
          className: "".concat(prefixCls, "-list-icon"),
          type: "folder",
          theme: "filled"
        }), item.name), /*#__PURE__*/_react["default"].createElement(_mkuiFd.Icon, {
          className: "".concat(prefixCls, "-arrow-icon"),
          type: "right"
        }));
      }), items.map(function (item) {
        return /*#__PURE__*/_react["default"].createElement("li", {
          key: item.code,
          onClick: function onClick() {
            _this4.selectOptionHandle(item);
          }
        }, /*#__PURE__*/_react["default"].createElement("span", null, /*#__PURE__*/_react["default"].createElement(_mkuiFd.Icon, {
          className: "".concat(prefixCls, "-list-icon"),
          type: "file"
        }), item.name));
      }))));
    }
  }, {
    key: "render",
    value: function render() {
      var _this$props = this.props,
          prefixCls = _this$props.prefixCls,
          showSearch = _this$props.showSearch,
          searchPlaceholder = _this$props.searchPlaceholder;
      var _this$state3 = this.state,
          searchResult = _this$state3.searchResult,
          spinning = _this$state3.spinning;
      return /*#__PURE__*/_react["default"].createElement("div", {
        className: (0, _classnames["default"])("".concat(prefixCls))
      }, showSearch && /*#__PURE__*/_react["default"].createElement("div", {
        className: "".concat(prefixCls, "-search")
      }, /*#__PURE__*/_react["default"].createElement(Search, {
        className: "".concat(prefixCls, "-search-input"),
        placeholder: searchPlaceholder,
        onChange: this.searchHandle
      })), /*#__PURE__*/_react["default"].createElement(_mkuiFd.Spin, {
        spinning: spinning
      }, showSearch && searchResult ? this.renderSearchResult() : this.renderContent()));
    }
  }], [{
    key: "getDerivedStateFromProps",
    value:
    /** *******************static************************** */
    function getDerivedStateFromProps(props, state) {
      if (props.data && props.data.code !== state.data.code) {
        return {
          data: props.data
        };
      }

      return null;
    }
  }]);

  return Panel;
}(_react["default"].Component);

_defineProperty(Panel, "propTypes", {
  prefixCls: _propTypes["default"].string,
  api: _propTypes["default"].func,
  onSelect: _propTypes["default"].func,
  showSearch: _propTypes["default"].bool,
  searchPlaceholder: _propTypes["default"].string
});

_defineProperty(Panel, "defaultProps", {
  prefixCls: 'mk-enhanced-tree-select-panel',
  api: _noop["default"],
  onSelect: _noop["default"],
  showSearch: false,
  searchPlaceholder: '输入名称搜索'
});

var _default = Panel;
exports["default"] = _default;
//# sourceMappingURL=Panel.js.map
