"use strict";

var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard");

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");

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

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

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

var _slicedToArray2 = _interopRequireDefault(require("@babel/runtime/helpers/slicedToArray"));

var _objectWithoutProperties2 = _interopRequireDefault(require("@babel/runtime/helpers/objectWithoutProperties"));

var _bem = require("@zarm-design/bem");

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

var _configProvider = require("../config-provider");

var _utils = require("../picker-view/utils");

var _radio = _interopRequireDefault(require("../radio"));

var _tabs = _interopRequireDefault(require("../tabs"));

var _utils2 = require("./utils");

function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (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 = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { (0, _defineProperty2.default)(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }

var CascaderView = /*#__PURE__*/(0, _react.forwardRef)(function (props, ref) {
  var className = props.className,
      dataSource = props.dataSource,
      defaultValue = props.defaultValue,
      value = props.value,
      propsFieldNames = props.fieldNames,
      cols = props.cols,
      itemRender = props.itemRender,
      onChange = props.onChange,
      restProps = (0, _objectWithoutProperties2.default)(props, ["className", "dataSource", "defaultValue", "value", "fieldNames", "cols", "itemRender", "onChange"]);
  var cascaderViewRef = ref || /*#__PURE__*/(0, _react.createRef)();

  var _useContext = (0, _react.useContext)(_configProvider.ConfigContext),
      prefixCls = _useContext.prefixCls,
      globalLocal = _useContext.locale;

  var locale = globalLocal === null || globalLocal === void 0 ? void 0 : globalLocal.CascaderView;
  var bem = (0, _bem.createBEM)('cascader-view', {
    prefixCls: prefixCls
  });
  var tabsBem = (0, _bem.createBEM)('cascader-view-tabs', {
    prefixCls: prefixCls
  });
  var cls = bem([className]);

  var _useState = (0, _react.useState)(_objectSpread(_objectSpread({}, (0, _utils2.parseState)(props)), {}, {
    tabIndex: 0
  })),
      _useState2 = (0, _slicedToArray2.default)(_useState, 2),
      state = _useState2[0],
      setState = _useState2[1];

  var currentValue = state.currentValue,
      tabIndex = state.tabIndex;
  var fieldNames = (0, _utils.resolvedFieldNames)(propsFieldNames);
  var handleObtainItem = (0, _react.useCallback)(function (list, _value) {
    return list.find(function (item) {
      return item[fieldNames.value] === _value;
    });
  }, [fieldNames.value]);
  /**
   * 初始化列表值
   */

  (0, _react.useEffect)(function () {
    var initValue = [];
    var v = value || defaultValue || [];
    v.reduce(function (accumulator, _currentValue) {
      var valueItem = handleObtainItem(accumulator, _currentValue);

      if (valueItem) {
        initValue.push(valueItem[fieldNames.value]);
        return valueItem.children || [];
      }

      return [];
    }, dataSource);
    setState(_objectSpread(_objectSpread({}, state), {}, {
      currentValue: initValue,
      tabIndex: initValue.length
    }));
  }, [dataSource, handleObtainItem, value, defaultValue]);
  /**
   * 获取列表数据
   */

  var columnDataList = (0, _react.useMemo)(function () {
    var group = [];
    var _dataSource = dataSource;
    var i = 0;

    while (_dataSource.length) {
      var colVal = currentValue[i];
      var selected = colVal ? handleObtainItem(_dataSource, colVal) : undefined;
      group.push({
        selected: selected,
        options: _dataSource
      });
      var childrenData = ((selected !== null && selected !== void 0 ? selected : _dataSource[0]) || {}).children;

      if (i < currentValue.length && childrenData && childrenData.length && i + 1 < cols) {
        _dataSource = childrenData;
      } else {
        _dataSource = [];
      }

      i += 1;
    }

    return group;
  }, [cols, currentValue, dataSource, handleObtainItem, fieldNames]);
  /**
   * 修改列表值
   * @param itemValue
   * @param index
   */

  var handleChange = function handleChange(itemValue, index) {
    var _value = currentValue.slice(0, index);

    if (itemValue !== undefined) {
      _value[index] = itemValue;
    }

    var items = (0, _utils2.parseItems)(dataSource, _value, fieldNames);
    setState(_objectSpread(_objectSpread({}, state), {}, {
      currentValue: _value,
      tabIndex: typeof index === 'number' ? index + 1 : tabIndex
    }));
    onChange === null || onChange === void 0 ? void 0 : onChange(_value, items);
  };
  /**
   * 判断是否有传入 itemRender， 否则使用默认的渲染方式
   * @param item
   */


  var handleItemRender = function handleItemRender(item) {
    return typeof itemRender !== 'function' ? item[fieldNames.label] : itemRender(item);
  };

  return /*#__PURE__*/_react.default.createElement("div", (0, _extends2.default)({
    className: cls,
    ref: cascaderViewRef
  }, restProps), /*#__PURE__*/_react.default.createElement(_tabs.default, {
    swipeable: true,
    scrollable: true,
    defaultValue: tabIndex,
    onChange: function onChange(i) {
      return setState(_objectSpread(_objectSpread({}, state), {}, {
        tabIndex: i
      }));
    },
    className: tabsBem(''),
    lineWidth: 60
  }, columnDataList.map(function (group, index) {
    var _group$selected;

    var groupActiveItemDisplay = (_group$selected = group.selected) === null || _group$selected === void 0 ? void 0 : _group$selected[fieldNames.label];

    var panelTitle = /*#__PURE__*/_react.default.createElement("span", {
      className: bem('tab-text', [{
        unselected: !groupActiveItemDisplay
      }])
    }, groupActiveItemDisplay !== null && groupActiveItemDisplay !== void 0 ? groupActiveItemDisplay : locale.unselectedTabText);

    return /*#__PURE__*/_react.default.createElement(_tabs.default.Panel, {
      key: +index,
      title: panelTitle
    }, /*#__PURE__*/_react.default.createElement("div", {
      className: bem('content')
    }, /*#__PURE__*/_react.default.createElement(_radio.default.Group, {
      type: "list",
      listIconAlign: "after",
      value: currentValue[index],
      onChange: function onChange(v) {
        return handleChange(v, index);
      }
    }, group.options.map(function (item, i) {
      var isActive = currentValue[index] === item[fieldNames.value];
      var label = handleItemRender(item);
      return /*#__PURE__*/_react.default.createElement(_radio.default, {
        key: "".concat(label).concat(+i),
        className: bem('content-item', [{
          active: isActive
        }]),
        value: item[fieldNames.value]
      }, label);
    }))));
  })));
});
CascaderView.displayName = 'CascaderView';
CascaderView.defaultProps = {
  cols: Infinity
};

var _default = /*#__PURE__*/(0, _react.memo)(CascaderView);

exports.default = _default;