import { IStoreState, ICell, ID, IBodyCellNamePolicy } from '../../index.data';
import { getCellByBracedId, getCellIdByStr, getLabelByIj } from '../../store/formula_support';
import { getRow, getCell, getCellij } from '../../store/selectors';
export function cellidToHtml(
state: IStoreState,
cellId: ID,
bodyCellNamePolicy: IBodyCellNamePolicy,
) {
const cellName = getCellName(state, cellId, bodyCellNamePolicy);
if (!cellName) throw new Error('根据命名策略bodyCellNamePolicy, 无法获取cell的名称');
const idStr = '{{id' + cellId + '}}';
return `${cellName.rowName}.${cellName.colName}`;
}
// 33+{{id1111}}*{{id2222}} => 33+测试.小计*
export function formulaToHtml(
state: IStoreState,
formula: string,
bodyCellNamePolicy: IBodyCellNamePolicy,
) {
return formula.replace(/\{\{id[^\}]+\}\}/g, idStr => {
const cell = getCellByBracedId(state, idStr);
return cellidToHtml(state, cell!.id, bodyCellNamePolicy);
});
}
/**
* A1 => {rowName:测试, colName:小计}
*/
export function getCellName(
state: IStoreState,
cellId: ID,
bodyCellNamePolicy: IBodyCellNamePolicy,
): { rowName: string; colName: string } | null {
const cell = getCell(state, cellId);
const { rowNameJ, colNames } = bodyCellNamePolicy!;
const colName = colNames[getCellij(state, cell!.id).j];
if (!colName) return null;
const row = getRow(state, cell!.rowId!);
const rowNameCellId = (row.cellIds || ([] as ID[]))[rowNameJ];
if (!rowNameCellId) return null;
const rowName = getCell(state, rowNameCellId)!.value || '无名行';
return { rowName, colName };
}
// 33+测试.小计* => 33+{{id1111}}*{{id2222}}
export function htmlToFormula(s: string) {
return s.replace(//g, m => {
const result = m.match(/data-id="([^"]+)"/);
if (!result) throw new Error(`公式未出现data-id: ${s}`);
return result[1];
});
}
export function getCellIdsFromContent(content: string): ID[] {
const result = content.match(/\{\{id[^\}]+\}\}/g);
return result ? result.map(it => it.slice(4, -2)) : [];
}