import _objectSpread from "@babel/runtime/helpers/esm/objectSpread2";
import { createVNode as _createVNode } from "vue";
import _extends from "@babel/runtime/helpers/esm/extends";
var __rest = this && this.__rest || function (s, e) {
  var t = {};
  for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p];
  if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
    if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]];
  }
  return t;
};
import { onBeforeMount, ref, defineComponent, onBeforeUnmount, provide, toRef, computed } from 'vue';
import useResponsiveObserve, { responsiveArray } from '../_util/responsiveObserve';
import Row from './Row';
import PropTypes from '../_util/vue-types';
import { flattenChildren, getClass, getStyle } from '../_util/props-util';
import useConfigInject from '../config-provider/hooks/useConfigInject';
import useStyle from './style';
import warning from '../_util/warning';
export const DescriptionsItemProps = {
  prefixCls: String,
  label: PropTypes.any,
  span: Number
};
const descriptionsItemProp = () => ({
  prefixCls: String,
  label: PropTypes.any,
  labelStyle: {
    type: Object,
    default: undefined
  },
  contentStyle: {
    type: Object,
    default: undefined
  },
  span: {
    type: [Number, String, Object],
    default: 1
  }
});
export const DescriptionsItem = defineComponent({
  compatConfig: {
    MODE: 3
  },
  name: 'ADescriptionsItem',
  props: descriptionsItemProp(),
  setup(_, {
    slots
  }) {
    return () => {
      var _a;
      return (_a = slots.default) === null || _a === void 0 ? void 0 : _a.call(slots);
    };
  }
});
const DEFAULT_COLUMN_MAP = {
  xxxl: 3,
  xxl: 3,
  xl: 3,
  lg: 3,
  md: 3,
  sm: 2,
  xs: 1
};
function getColumn(column, screens) {
  if (typeof column === 'number') {
    return column;
  }
  if (typeof column === 'object') {
    for (let i = 0; i < responsiveArray.length; i++) {
      const breakpoint = responsiveArray[i];
      if (screens[breakpoint] && column[breakpoint] !== undefined) {
        return column[breakpoint] || DEFAULT_COLUMN_MAP[breakpoint];
      }
    }
  }
  return 3;
}
export const matchScreen = (screens, screenSizes) => {
  if (!screenSizes) {
    return;
  }
  for (const breakpoint of responsiveArray) {
    if (screens[breakpoint] && (screenSizes === null || screenSizes === void 0 ? void 0 : screenSizes[breakpoint]) !== undefined) {
      return screenSizes[breakpoint];
    }
  }
};
const transChildren2Items = childNodes => childNodes.map(node => {
  var _a, _b, _c, _d, _e;
  return _extends(_extends({}, node === null || node === void 0 ? void 0 : node.props), {
    children: (_a = node.children) === null || _a === void 0 ? void 0 : _a.default(),
    label: (_c = (_b = node === null || node === void 0 ? void 0 : node.props) === null || _b === void 0 ? void 0 : _b.label) !== null && _c !== void 0 ? _c : (_e = (_d = node.children) === null || _d === void 0 ? void 0 : _d.label) === null || _e === void 0 ? void 0 : _e.call(_d),
    key: node.key,
    style: getStyle(node),
    class: getClass(node)
  });
});
function getItems(screens, items, children) {
  const childNodes = flattenChildren(children);
  const mergedItems = items || transChildren2Items(childNodes);
  return mergedItems.map(_a => {
    var {
        span
      } = _a,
      restItem = __rest(_a, ["span"]);
    if (span === 'filled') {
      return _extends(_extends({}, restItem), {
        filled: true
      });
    }
    return _extends(_extends({}, restItem), {
      span: typeof span === 'number' ? span : matchScreen(screens, span)
    });
  });
}
function getRows(rowItems, column) {
  let rows = [];
  let tempRow = [];
  let exceed = false;
  let count = 0;
  rowItems.filter(n => n).forEach(rowItem => {
    const {
        filled
      } = rowItem,
      restItem = __rest(rowItem, ["filled"]);
    if (filled) {
      tempRow.push(restItem);
      rows.push(tempRow);
      tempRow = [];
      count = 0;
      return;
    }
    const restSpan = column - count;
    count += rowItem.span || 1;
    if (count >= column) {
      if (count > column) {
        exceed = true;
        tempRow.push(_extends(_extends({}, restItem), {
          span: restSpan
        }));
      } else {
        tempRow.push(restItem);
      }
      rows.push(tempRow);
      tempRow = [];
      count = 0;
    } else {
      tempRow.push(restItem);
    }
  });
  if (tempRow.length) {
    rows.push(tempRow);
  }
  rows = rows.map(rows => {
    const count = rows.reduce((acc, item) => acc + (item.span || 1), 0);
    if (count < column) {
      // If the span of the last element in the current row is less than the column, then add its span to the remaining columns
      const last = rows[rows.length - 1];
      last.span = column - (count - (last.span || 1));
      return rows;
    }
    return rows;
  });
  return [rows, exceed];
}
export const descriptionsProps = () => ({
  prefixCls: String,
  bordered: {
    type: Boolean,
    default: undefined
  },
  size: {
    type: String,
    default: 'default'
  },
  title: PropTypes.any,
  extra: PropTypes.any,
  column: {
    type: [Number, Object],
    default: () => DEFAULT_COLUMN_MAP
  },
  layout: String,
  colon: {
    type: Boolean,
    default: undefined
  },
  labelStyle: {
    type: Object,
    default: undefined
  },
  contentStyle: {
    type: Object,
    default: undefined
  },
  items: {
    type: Array,
    default: undefined
  }
});
export const descriptionsContext = Symbol('descriptionsContext');
const Descriptions = defineComponent({
  compatConfig: {
    MODE: 3
  },
  name: 'ADescriptions',
  inheritAttrs: false,
  props: descriptionsProps(),
  slots: Object,
  Item: DescriptionsItem,
  setup(props, {
    slots,
    attrs
  }) {
    const {
      prefixCls,
      direction
    } = useConfigInject('descriptions', props);
    let token;
    const screens = ref({});
    const [wrapSSR, hashId] = useStyle(prefixCls);
    const responsiveObserve = useResponsiveObserve();
    onBeforeMount(() => {
      token = responsiveObserve.value.subscribe(screen => {
        if (typeof props.column !== 'object') {
          return;
        }
        screens.value = screen;
      });
    });
    onBeforeUnmount(() => {
      responsiveObserve.value.unsubscribe(token);
    });
    provide(descriptionsContext, {
      labelStyle: toRef(props, 'labelStyle'),
      contentStyle: toRef(props, 'contentStyle')
    });
    const mergeColumn = computed(() => getColumn(props.column, screens.value));
    return () => {
      var _a, _b, _c;
      const {
        size,
        bordered = false,
        layout = 'horizontal',
        colon = true,
        title = (_a = slots.title) === null || _a === void 0 ? void 0 : _a.call(slots),
        extra = (_b = slots.extra) === null || _b === void 0 ? void 0 : _b.call(slots)
      } = props;
      const children = (_c = slots.default) === null || _c === void 0 ? void 0 : _c.call(slots);
      const items = getItems(screens.value, props.items, children);
      const [rows, exceed] = getRows(items, mergeColumn.value);
      warning(!exceed, 'Descriptions', 'Sum of column `span` in a line not match `column` of Descriptions.');
      return wrapSSR(_createVNode("div", _objectSpread(_objectSpread({}, attrs), {}, {
        "class": [prefixCls.value, {
          [`${prefixCls.value}-${size}`]: size !== 'default',
          [`${prefixCls.value}-bordered`]: !!bordered,
          [`${prefixCls.value}-rtl`]: direction.value === 'rtl'
        }, attrs.class, hashId.value]
      }), [(title || extra) && _createVNode("div", {
        "class": `${prefixCls.value}-header`
      }, [title && _createVNode("div", {
        "class": `${prefixCls.value}-title`
      }, [title]), extra && _createVNode("div", {
        "class": `${prefixCls.value}-extra`
      }, [extra])]), _createVNode("div", {
        "class": `${prefixCls.value}-view`
      }, [_createVNode("table", null, [_createVNode("tbody", null, [rows.map((row, index) => _createVNode(Row, {
        "key": index,
        "index": index,
        "colon": colon,
        "prefixCls": prefixCls.value,
        "vertical": layout === 'vertical',
        "bordered": bordered,
        "row": row
      }, null))])])])]));
    };
  }
});
Descriptions.install = function (app) {
  app.component(Descriptions.name, Descriptions);
  app.component(Descriptions.Item.name, Descriptions.Item);
  return app;
};
export default Descriptions;