/**
 * 客户编号生成工具
 */

const CUSTOMER_NUMBER_KEY = 'customer_number_counter';

/**
 * 获取当前客户编号计数器
 */
const getCounter = (): number => {
  const counter = localStorage.getItem(CUSTOMER_NUMBER_KEY);
  return counter ? parseInt(counter, 10) : 1;
};

/**
 * 保存客户编号计数器
 */
const saveCounter = (counter: number): void => {
  localStorage.setItem(CUSTOMER_NUMBER_KEY, counter.toString());
};

/**
 * 生成新的客户编号
 * 格式：6位数字，从 000001 开始自增
 * @returns 格式化的客户编号，如：000001, 000002, 000003...
 */
export const generateCustomerNumber = (): string => {
  const currentCounter = getCounter();
  const newCounter = currentCounter + 1;
  saveCounter(newCounter);

  // 格式化为6位数字，不足补0
  return newCounter.toString().padStart(6, '0');
};

/**
 * 获取下一个客户编号（不自增，仅预览）
 * @returns 下一个客户编号
 */
export const getNextCustomerNumber = (): string => {
  const currentCounter = getCounter();
  const nextCounter = currentCounter + 1;
  return nextCounter.toString().padStart(6, '0');
};

/**
 * 重置客户编号计数器
 * @param startNumber 起始编号，默认 1
 */
export const resetCustomerNumberCounter = (startNumber: number = 1): void => {
  saveCounter(startNumber - 1);
};

/**
 * 设置客户编号计数器
 * @param counter 当前计数器值
 */
export const setCustomerNumberCounter = (counter: number): void => {
  saveCounter(counter);
};
