import { isNumber } from 'lodash-es';

export function useTableColumn({ columnActions }: any) {
  const { autoCalcWidth, autoMergeAction, textNumber, actionNumber } = columnActions;
  function getColumnActionWidth(actions: []) {
    const ACTION_NUM = 2; //显示几列操作
    if (autoCalcWidth === true) {
      let labelWidth = 0;
      let actionsLength: number = actionNumber || actions.length; // 更多时候 边距为修改为3
      //设置了字数则按字数计算
      if (isNumber(textNumber) && textNumber > 0) {
        actionsLength = textNumber;
      } else {
        if (actionsLength <= ACTION_NUM || autoMergeAction === false) {
          for (let i = 0; i < actionsLength; i++) {
            labelWidth += actions[i].label.length;
          }
        } else {
          for (let i = 0; i < ACTION_NUM - 1; i++) {
            labelWidth += actions[i].label.length;
          }
          labelWidth += ACTION_NUM; // 更多
          actionsLength = ACTION_NUM; //合并为更多
        }
        labelWidth <= ACTION_NUM && (labelWidth = ACTION_NUM);
      }
      return 14 * (labelWidth + actionsLength) + 10 + 12;
    }
    return 100;
  }

  function transformColumnAction(actions: []) {
    if (autoMergeAction) {
      const _actions = [];
      const actionsLength = actions.length;
      if (actionsLength > 6) {
        const moreAction = {
          label: '更多',
          openPermission: true,
          name: 'more',
          children: [...actions.splice(1)],
        };
        _actions.push(actions[0], moreAction);
        return _actions;
      }
    }
    return actions;
  }

  return { getColumnActionWidth, transformColumnAction };
}
