import { ReactWrapper } from 'enzyme';
import SpreadSheet from '../../SpreadSheetProvider';
import { sliceBy } from 'valor-app-utils';
import { ID, IRow } from '../../index.data';
import { IRowWithCell } from '../../SpreadSheetProvider/index.data';

export function getCellsInfo(wrapper: ReactWrapper, parseValueAsInt = true) {
  const tds = wrapper.find(SpreadSheet).find('td[id^="cell"]');
  const resultIds = tds
    .map(it => sliceBy(it.prop('id') as any, { from: ':' }).slice(1))
    .map(it => parseInt(it));
  const resultValues = tds.map(it => it.text()).map(it => (parseValueAsInt ? parseInt(it) : it));
  return { resultIds, resultValues };
}

// 选中cellId
export function selectCell(wrapper: ReactWrapper, cellId: ID) {
  (wrapper
    .find(SpreadSheet)
    .at(0)
    .instance() as any).runtime.fsmService.send('MOUSE.DOWN', { selectedCell: cellId });
}

export const helpers = {
  normalizeRow: (rows: IRow[], row: IRowWithCell) => {
    const rowIdx = rows.findIndex(it => it.id === row.id);
    const nextRow = rows[rowIdx + 1];
    const hasChildren = nextRow && nextRow.level === row.level! + 1;
    const cell = row.cells[0];
    const result = hasChildren
      ? Object.assign({}, row, {
          cells: [{ ...cell, formulaDisabled: false, formula: 'sumChildren()' }],
        })
      : Object.assign({}, row, { cells: [{ ...cell, formulaDisabled: true, formula: '' }] });
    return result;
  },
};

export const flatten_helpers = {
  normalizeRow: (rows: IRow[], row: IRowWithCell) => {
    return row;
  },
};
