import { preferences } from '@kit.ArkData';

export interface ExpenseItem {
  id: string;
  type: '消费' | '收入';
  category: string;
  amount: number;
  remark: string;
  message: string;
  createTime: string;
}

export const EXPENSE_CATEGORIES: string[] = [
  '餐饮', '医药', '数码', '还款', '购物', '交通',
  '娱乐', '住房', '日用', '服饰', '教育', '人情', '其他'
];

export const INCOME_CATEGORIES: string[] = [
  '工资', '奖金', '理财', '兼职', '报销', '退款', '红包', '其他收入'
];

export const CATEGORY_COLORS: Record<string, string> = {
  '餐饮': '#F4A125',
  '医药': '#4CAF50',
  '数码': '#4F6EF7',
  '还款': '#795548',
  '购物': '#9C27B0',
  '交通': '#009688',
  '娱乐': '#FF5722',
  '住房': '#607D8B',
  '日用': '#00BCD4',
  '服饰': '#E91E63',
  '教育': '#3F51B5',
  '人情': '#FF6F00',
  '其他': '#8899A6',
  '工资': '#2E7D32',
  '奖金': '#FF8F00',
  '理财': '#1565C0',
  '兼职': '#6A1B9A',
  '报销': '#00838F',
  '退款': '#C62828',
  '红包': '#D84315',
  '其他收入': '#546E7A',
};

const STORE_NAME = 'expense_store';
const KEY_EXPENSES = 'expenses';

let storeInstance: preferences.Preferences | null = null;

async function getOrCreateStore(): Promise<preferences.Preferences> {
  if (storeInstance === null) {
    storeInstance = await preferences.getPreferences(getContext(), STORE_NAME);
  }
  return storeInstance;
}

function getNumber(val: Object | undefined): number {
  if (typeof val === 'number') return val as number;
  return 0;
}

function getString(val: Object | undefined): string {
  if (typeof val === 'string' && (val as string).length > 0) return val as string;
  return '';
}

function migrateItem(raw: Record<string, Object>): ExpenseItem {
  let amount = getNumber(raw.amount);
  if (amount === 0) amount = getNumber(raw.mash);

  let category = getString(raw.category);
  if (category === '') category = getString(raw.name);
  if (category === 'good' || category === 'income') category = '其他收入';

  let remark = getString(raw.remark);
  if (remark === '') remark = getString(raw.text);
  if (remark === '') remark = getString(raw.note);

  let type: '消费' | '收入' = '消费';
  if (raw.type === '收入' || raw.type === 'income') {
    type = '收入';
  }

  return {
    id: getString(raw.id),
    type: type,
    category: category,
    amount: amount,
    remark: remark,
    message: getString(raw.message),
    createTime: getString(raw.createTime) || getString(raw.date) || new Date().toISOString()
  };
}

export async function loadExpenses(): Promise<ExpenseItem[]> {
  try {
    const store = await getOrCreateStore();
    const json = await store.get(KEY_EXPENSES, '[]');
    const raw = JSON.parse(json as string) as Record<string, Object>[];
    const result: ExpenseItem[] = [];
    for (let i = 0; i < raw.length; i++) {
      result.push(migrateItem(raw[i]));
    }
    return result;
  } catch (e) {
    console.error('loadExpenses failed: ' + e);
    return [];
  }
}

export async function saveExpenses(expenses: ExpenseItem[]): Promise<void> {
  try {
    const store = await getOrCreateStore();
    await store.put(KEY_EXPENSES, JSON.stringify(expenses));
    await store.flush();
  } catch (e) {
    console.error('saveExpenses failed: ' + e);
  }
}

export async function addExpense(item: ExpenseItem): Promise<ExpenseItem[]> {
  const expenses = await loadExpenses();
  expenses.unshift(item);
  await saveExpenses(expenses);
  return expenses;
}

let idCounter = 0;

export function generateId(): string {
  idCounter++;
  return Date.now().toString(36) + idCounter.toString(36) + Math.random().toString(36).substring(2, 10);
}
