import { requestClient } from '#/api/request';

const prefix = 'spreadsheet-formula/';

export interface SpreadsheetFormulaRefSlot {
  slot: string;
  label: string;
}

export interface SpreadsheetFormulaItem {
  id: number;
  code: string;
  name: string;
  description: string;
  expression_template: string;
  ref_slots: SpreadsheetFormulaRefSlot[];
  sort: number;
  status: number;
  created_at: number;
  updated_at: number;
}

export async function listSpreadsheetFormula() {
  return requestClient.get<SpreadsheetFormulaItem[]>(`${prefix}list`);
}

export async function createSpreadsheetFormula(data: {
  code: string;
  name: string;
  description?: string;
  expression_template: string;
  ref_slots: SpreadsheetFormulaRefSlot[];
  sort?: number;
  status?: boolean;
}) {
  return requestClient.post<SpreadsheetFormulaItem>(`${prefix}create`, data);
}

export async function updateSpreadsheetFormula(data: {
  id: number;
  code?: string;
  name?: string;
  description?: string;
  expression_template?: string;
  ref_slots?: SpreadsheetFormulaRefSlot[];
  sort?: number;
  status?: boolean;
}) {
  return requestClient.post<SpreadsheetFormulaItem>(`${prefix}update`, data);
}

export async function deleteSpreadsheetFormula(id: number) {
  return requestClient.post<boolean>(`${prefix}delete`, { id });
}

/** Replace REF0/REF1 with Excel-style column letters + row 1 */
export function buildFormulaFromTemplate(
  template: string,
  refColumns: number[],
): string {
  let result = template;
  refColumns.forEach((colIndex, i) => {
    const letters = colIndexToLetters(colIndex);
    const re = new RegExp(`REF${i}`, 'g');
    result = result.replace(re, `${letters}1`);
  });
  return result;
}

function colIndexToLetters(index: number): string {
  let n = index + 1;
  let result = '';
  while (n > 0) {
    n -= 1;
    result = String.fromCharCode(65 + (n % 26)) + result;
    n = Math.floor(n / 26);
  }
  return result;
}

export { colIndexToLetters };
