import { computed, watch } from 'vue';
import { useNormalModel } from '../_util/use/useModel';
import { TABLE_NAME } from './const';

// string[] | number[] 不能直接调用数组的大部分方法，因此转换为 (string | number)[] 后使用

var useTableExpand = _ref => {
  let {
    props,
    ctx,
    columns,
    getRowKey
  } = _ref;
  // 展开列唯一
  const expandColumn = computed(() => {
    const arr = columns.value.filter(column => column.props.type === 'expand');
    if (arr.length > 1) {
      console.warn(`[${TABLE_NAME}]: type=expand 不能存在多个`);
    }
    return arr[0];
  });
  watch(expandColumn, () => {
    if (expandColumn.value && !props.rowKey) {
      console.warn(`[${TABLE_NAME}]: 当存在 expand 列时，请设置rowKey!`);
    }
  });
  const [currentExpandedKeys] = useNormalModel(props, ctx.emit, {
    prop: 'expandedKeys'
  });
  const isExpandOpened = _ref2 => {
    let {
      row
    } = _ref2;
    const rowKey = getRowKey({
      row
    });
    return currentExpandedKeys.value.includes(rowKey);
  };
  const toggleRowExpend = _ref3 => {
    let {
      row
    } = _ref3;
    const rowKey = getRowKey({
      row
    });
    const expandOpenedList = currentExpandedKeys.value;
    const index = expandOpenedList.indexOf(rowKey);
    if (index !== -1) {
      expandOpenedList.splice(index, 1);
    } else {
      expandOpenedList.push(rowKey);
    }
    return index === -1;
  };
  const handleExpand = _ref4 => {
    let {
      row
    } = _ref4;
    const expanded = toggleRowExpend({
      row
    });
    ctx.emit('expandChange', {
      row,
      expanded
    });
  };
  return {
    expandColumn,
    isExpandOpened,
    toggleRowExpend,
    handleExpand
  };
};

export { useTableExpand as default };
