import { rpx2vw4style as __rpx2vw__ } from "babel-runtime-jsx-style-transform";

function _extends() { _extends = Object.assign || 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 _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; }

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 _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 _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }

function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure 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 _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 _iterableToArrayLimit(arr, i) { var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }

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

import { __awaiter, __rest } from "tslib";
import classNames from 'classnames';
import React, { createElement, forwardRef, Fragment, useEffect, useRef, useState } from "react";
import { ScrollView, Text } from "@alifd/meet-react-component-one";
import BreadCrumb from '../bread-crumb';
import Icon from '../icon';
import List from '../list';
import { useLocale } from '../locale';
import Picker from '../picker';
import View from '../view';
import SelectDrawer from '../select-drawer';
import { isFunction, isUndef, isValidArray, isStrictWechatMiniProgram } from '../utils';
import { find, getDataByValues, getFirstValue, getSiblings, getFullPathByValue } from '../utils/tree';

var getInitValue = function getInitValue(props) {
  var _props$dataSource = props.dataSource,
      dataSource = _props$dataSource === void 0 ? [] : _props$dataSource,
      defaultValue = props.defaultValue,
      value = props.value;
  var ret = [];

  if ('value' in props) {
    if (isValidArray(value)) {
      ret = value;
    } else if (!Array.isArray(value) && value) {
      ret = getFullPathByValue(props.dataSource, props.value);
    }
  } else if (!isUndef(defaultValue)) {
    if (isValidArray(defaultValue)) {
      ret = defaultValue;
    } else if (!Array.isArray(defaultValue) && defaultValue) {
      ret = getFullPathByValue(dataSource, defaultValue);
    }
  }

  return ret;
};

var getInitInternalValue = function getInitInternalValue(props) {
  var r = getInitValue(props);
  var isNormalMode = props.mode !== 'mini';

  if (r.length === 0) {
    if (!isNormalMode) {
      return getFirstValue(props.dataSource);
    } else {
      return [];
    }
  } else {
    return r;
  }
};

var defaultRenderContent = function defaultRenderContent() {
  var values = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
  var separator = arguments.length > 1 ? arguments[1] : undefined;
  return Array.isArray(values) ? values.map(function (val) {
    return val.label;
  }).join(separator) : '';
};

var CascaderSelect = function CascaderSelect(props, ref) {
  var _props$prefix = props.prefix,
      prefix = _props$prefix === void 0 ? 'mt-' : _props$prefix,
      _props$dataSource2 = props.dataSource,
      dataSource = _props$dataSource2 === void 0 ? [] : _props$dataSource2,
      _props$separator = props.separator,
      separator = _props$separator === void 0 ? '/' : _props$separator,
      _props$mode = props.mode,
      mode = _props$mode === void 0 ? 'normal' : _props$mode,
      value = props.value,
      defaultValue = props.defaultValue,
      className = props.className,
      hasClear = props.hasClear,
      _props$useSimpleValue = props.useSimpleValue,
      useSimpleValue = _props$useSimpleValue === void 0 ? false : _props$useSimpleValue,
      onChange = props.onChange,
      _props$rootTipText = props.rootTipText,
      rootTipText = _props$rootTipText === void 0 ? '' : _props$rootTipText,
      localeProp = props.locale,
      loadData = props.loadData,
      isPreview = props.isPreview,
      renderPreview = props.renderPreview,
      _props$size = props.size,
      size = _props$size === void 0 ? 'medium' : _props$size,
      previewClassNameProp = props.previewClassName,
      previewStyle = props.previewStyle,
      _props$onSelect = props.onSelect,
      onSelect = _props$onSelect === void 0 ? function () {} : _props$onSelect,
      _props$onClear = props.onClear,
      onClear = _props$onClear === void 0 ? function () {} : _props$onClear,
      onCancel = props.onCancel,
      _props$renderContent = props.renderContent,
      renderContent = _props$renderContent === void 0 ? defaultRenderContent : _props$renderContent,
      others = __rest(props, ["prefix", "dataSource", "separator", "mode", "value", "defaultValue", "className", "hasClear", "useSimpleValue", "onChange", "rootTipText", "locale", "loadData", "isPreview", "renderPreview", "size", "previewClassName", "previewStyle", "onSelect", "onClear", "onCancel", "renderContent"]);

  var scrollRef = useRef(null);
  var clsPrefix = "".concat(prefix, "cascader-select");
  var isControlled = ('value' in props);
  var isNormalMode = mode !== 'mini';
  var previewClassName = classNames(previewClassNameProp, "".concat(prefix, "form-item-input--preview-").concat(size));
  var loadingIcon = /*#__PURE__*/React.createElement(Icon, {
    className: "".concat(clsPrefix, "-icon--loading"),
    name: "loading",
    size: "s"
  });
  var selectedIcon = /*#__PURE__*/React.createElement(Icon, {
    className: "".concat(clsPrefix, "-icon--selected"),
    name: "select",
    size: "s"
  });

  var _useState = useState(getInitValue(props)),
      _useState2 = _slicedToArray(_useState, 2),
      curVal = _useState2[0],
      setVal = _useState2[1];

  var _useState3 = useState(getInitInternalValue(props)),
      _useState4 = _slicedToArray(_useState3, 2),
      internalValue = _useState4[0],
      setInternalVal = _useState4[1];

  var _useState5 = useState(null),
      _useState6 = _slicedToArray(_useState5, 2),
      loadingNode = _useState6[0],
      setLoadingNode = _useState6[1];

  var _useState7 = useState(false),
      _useState8 = _slicedToArray(_useState7, 2),
      drawerVisible = _useState8[0],
      setDrawerVisible = _useState8[1];

  var locale = localeProp || useLocale('Cascader', props, {
    rootTipText: '首页'
  });
  var innerSelectedPath = getDataByValues(dataSource, internalValue);

  var handlePickerChange = function handlePickerChange(v) {
    setInternalVal(v);
  };

  var handleOk = function handleOk() {
    if (isNormalMode) {
      if (isValidArray(internalValue)) {
        var lastVal = internalValue[internalValue.length - 1];
        var n = find(dataSource, function (node) {
          return node.value === lastVal;
        });

        if (n && n.children) {
          handleCancel('invalid-selection');
          return;
        }
      } else {
        handleCancel('invalid-selection');
        return;
      }
    }

    if (!isControlled) {
      setVal(internalValue);
    }

    if (onChange) {
      var selectedPath = getDataByValues(dataSource, internalValue);
      var lastData = selectedPath[selectedPath.length - 1];
      onChange(useSimpleValue ? lastData.value || '' : internalValue, lastData, {
        selectedPath: selectedPath
      });
    }
  };

  var handleCancel = function handleCancel(reason) {
    setInternalVal(curVal);

    if (isFunction(onCancel)) {
      onCancel(reason);
    }
  };

  var handleListClick = function handleListClick(item, dpt) {
    return __awaiter(void 0, void 0, void 0, /*#__PURE__*/regeneratorRuntime.mark(function _callee() {
      var val, newInternalVal;
      return regeneratorRuntime.wrap(function _callee$(_context) {
        while (1) {
          switch (_context.prev = _context.next) {
            case 0:
              val = item.value;
              newInternalVal = [].concat(_toConsumableArray(internalValue.slice(0, dpt)), [val]);

              if (loadData && internalValue.indexOf(val) > -1) {
                newInternalVal = internalValue.slice(0, internalValue.indexOf(val) + 1);
              }

              setInternalVal(newInternalVal);

              if (!(loadData && !item.isLeaf)) {
                _context.next = 9;
                break;
              }

              setLoadingNode(val);
              _context.next = 8;
              return loadData(item);

            case 8:
              setLoadingNode(null);

            case 9:
              if (onSelect) {
                onSelect(val, item);
              }

            case 10:
            case "end":
              return _context.stop();
          }
        }
      }, _callee);
    }));
  };

  var handleBreadCrumbClick = function handleBreadCrumbClick() {
    var index = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0;
    setInternalVal(internalValue.slice(0, index));
  };

  var handleClear = function handleClear() {
    if (!isControlled) {
      setVal([]);
      setInternalVal([]);
    }

    if (onClear) {
      onClear();
    }

    if (onChange) {
      onChange(useSimpleValue ? '' : [], {}, {
        selectedPath: []
      });
    }
  };

  var handleVisibleChange = function handleVisibleChange(visible) {
    setDrawerVisible(visible);
  };

  useEffect(function () {
    setVal(getInitValue(props));
    setInternalVal(getInitInternalValue(props));
  }, [value]);
  useEffect(function () {
    if (!drawerVisible) {
      setVal(getInitValue(props));
      setInternalVal(getInitInternalValue(props));
    }
  }, [props.dataSource]);
  var nextList = [];

  if (isNormalMode) {
    if (isValidArray(internalValue)) {
      var lastVal = internalValue[internalValue.length - 1];
      var t = find(dataSource, function (node) {
        return node.value === lastVal;
      });

      if (t && loadingNode === t.value) {
        nextList = [];
      } else if (t && isValidArray(t.children)) {
        nextList = t.children;
      }
    } else {
      nextList = dataSource;
    }
  }

  var renderPicker = function renderPicker() {
    return isValidArray(dataSource) ? /*#__PURE__*/React.createElement(Picker, {
      cascade: true,
      data: dataSource,
      value: internalValue,
      onChange: handlePickerChange
    }) : null;
  };

  if (isPreview) {
    if (isFunction(renderPreview)) {
      return /*#__PURE__*/React.createElement(View, {
        className: previewClassName,
        style: __rpx2vw__(previewStyle)
      }, renderPreview(innerSelectedPath));
    }

    return /*#__PURE__*/React.createElement(Text, {
      className: previewClassName,
      style: __rpx2vw__(previewStyle)
    }, innerSelectedPath.map(function (node) {
      return node.label;
    }).join(separator));
  }

  return /*#__PURE__*/React.createElement(SelectDrawer, _extends({}, others, {
    ref: ref,
    hasClear: hasClear,
    className: classNames(clsPrefix, className),
    content: renderContent(getDataByValues(dataSource, curVal), separator),
    drawerClassName: "".concat(clsPrefix, "-container"),
    onVisibleChange: handleVisibleChange,
    onOk: handleOk,
    onCancel: handleCancel,
    onClear: handleClear
  }), isNormalMode ? /*#__PURE__*/React.createElement(Fragment, null, /*#__PURE__*/React.createElement(BreadCrumb, {
    className: classNames("".concat(clsPrefix, "-nav"), _defineProperty({}, "".concat(clsPrefix, "-nav--wechat"), isStrictWechatMiniProgram)),
    onClick: handleBreadCrumbClick
  }, /*#__PURE__*/React.createElement(BreadCrumb.Item, null, rootTipText || locale.rootTipText), isValidArray(innerSelectedPath) ? innerSelectedPath.map(function (val) {
    return /*#__PURE__*/React.createElement(BreadCrumb.Item, {
      key: val.value
    }, val.label);
  }) : null), /*#__PURE__*/React.createElement(View, {
    className: "".concat(clsPrefix, "-gutter")
  })) : null, !isNormalMode ? renderPicker() : /*#__PURE__*/React.createElement(ScrollView, {
    showsVerticalScrollIndicator: true,
    showsHorizontalScrollIndicator: false,
    ref: scrollRef,
    className: "".concat(clsPrefix, "-scrollview")
  }, /*#__PURE__*/React.createElement(View, {
    className: "".concat(clsPrefix, "-item-container")
  }, isValidArray(internalValue) ? internalValue.map(function (val, index) {
    var list = getSiblings(dataSource, val);
    return isValidArray(list) ? /*#__PURE__*/React.createElement(List, {
      className: "".concat(clsPrefix, "-list"),
      key: val
    }, list.map(function (item) {
      var icon = null;
      var hasArrow = loadData && !item.isLeaf || !loadData && item.children;

      if (loadData && loadingNode === item.value) {
        icon = loadingIcon;
      } else if (loadData && item.value === val || !loadData && item.value === val) {
        icon = selectedIcon;
      }

      return /*#__PURE__*/React.createElement(List.Item, {
        key: item.value,
        title: item.label,
        extra: icon,
        arrow: hasArrow && !icon ? 'right' : null,
        onClick: function onClick() {
          handleListClick(item, index);
        }
      });
    })) : null;
  }) : null, isValidArray(nextList) ? /*#__PURE__*/React.createElement(List, {
    className: "".concat(clsPrefix, "-list")
  }, nextList.map(function (item) {
    var icon = null;
    var hasArrow = item.children || loadData && !item.isLeaf;

    if (loadData && item.isLeaf && item.value === loadingNode) {
      icon = loadingIcon;
    }

    return /*#__PURE__*/React.createElement(List.Item, {
      key: item.value,
      title: item.label,
      extra: icon,
      arrow: hasArrow && !icon ? 'right' : null,
      onClick: function onClick() {
        handleListClick(item, internalValue ? internalValue.length : 0);
      }
    });
  })) : null)));
};

CascaderSelect.displayName = 'CascaderSelect';
export default /*#__PURE__*/forwardRef(CascaderSelect);