import _extends from "@babel/runtime/helpers/extends";
import _defineProperty from "@babel/runtime/helpers/defineProperty";
import _slicedToArray from "@babel/runtime/helpers/slicedToArray";
import _objectWithoutProperties from "@babel/runtime/helpers/objectWithoutProperties";

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) { _defineProperty(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; }

import { createBEM } from '@zarm-design/bem';
import React, { createRef, forwardRef, memo, useCallback, useContext, useEffect, useMemo, useState } from 'react';
import { ConfigContext } from '../config-provider';
import { resolvedFieldNames } from '../picker-view/utils';
import Radio from '../radio';
import Tabs from '../tabs';
import { parseItems, parseState } from './utils';
var CascaderView = /*#__PURE__*/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 = _objectWithoutProperties(props, ["className", "dataSource", "defaultValue", "value", "fieldNames", "cols", "itemRender", "onChange"]);

  var cascaderViewRef = ref || /*#__PURE__*/createRef();

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

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

  var _useState = useState(_objectSpread(_objectSpread({}, parseState(props)), {}, {
    tabIndex: 0
  })),
      _useState2 = _slicedToArray(_useState, 2),
      state = _useState2[0],
      setState = _useState2[1];

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

  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 = 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 = 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.createElement("div", _extends({
    className: cls,
    ref: cascaderViewRef
  }, restProps), /*#__PURE__*/React.createElement(Tabs, {
    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.createElement("span", {
      className: bem('tab-text', [{
        unselected: !groupActiveItemDisplay
      }])
    }, groupActiveItemDisplay !== null && groupActiveItemDisplay !== void 0 ? groupActiveItemDisplay : locale.unselectedTabText);
    return /*#__PURE__*/React.createElement(Tabs.Panel, {
      key: +index,
      title: panelTitle
    }, /*#__PURE__*/React.createElement("div", {
      className: bem('content')
    }, /*#__PURE__*/React.createElement(Radio.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.createElement(Radio, {
        key: "".concat(label).concat(+i),
        className: bem('content-item', [{
          active: isActive
        }]),
        value: item[fieldNames.value]
      }, label);
    }))));
  })));
});
CascaderView.displayName = 'CascaderView';
CascaderView.defaultProps = {
  cols: Infinity
};
export default /*#__PURE__*/memo(CascaderView);