import {
  getIndividualRankings,
  saveIndividualRankings as saveIndividualRankingsToConfig,
  getTeamRankings,
  saveTeamRankings as saveTeamRankingsToConfig,
  getSystemUsers,
  saveSystemUsers as saveSystemUsersToConfig,
  addSystemUser as addSystemUserToConfig,
  deleteSystemUser as deleteSystemUserToConfig,
  updateSystemUser as updateSystemUserToConfig,
  getDisplayConfig,
  saveDisplayConfig as saveDisplayConfigToConfig,
  getBattleEndTime,
  saveBattleEndTime as saveBattleEndTimeToConfig,
  getBonusRules,
  saveBonusRules as saveBonusRulesToConfig,
  getMusicConfig,
  saveMusicConfig as saveMusicConfigToConfig
} from '../services/configService';

// 初始化空数据占位符，将在initializeData中正确加载
export let individualRankings = [];
export let teamRankings = [];
export let bonusRules = [
  { rank: '1-3', description: '前三名', individualBonus: '¥10000, ¥8000, ¥5000', teamBonus: '¥50000, ¥30000, ¥20000' },
  { rank: '4-10', description: '四至十名', individualBonus: '¥3000/人', teamBonus: '¥10000/队' },
  { rank: '11-20', description: '十一至二十名', individualBonus: '¥1000/人', teamBonus: '¥5000/队' }
];
export let systemUsers = [];
export let displayConfig = null;
export let battleEndTime = { date: new Date().toISOString().split('T')[0], time: '00:00:00' };
export let musicConfig = { enabled: false, filePath: '' };


// 保存结束时间
export const saveBattleEndTime = async (endTime) => {
  battleEndTime = { ...endTime };
  console.log('保存结束时间:', battleEndTime);
  return await saveBattleEndTimeToConfig(endTime);
};

// 保存英雄排名数据
export const saveIndividualRankings = async (data) => {
  individualRankings = [...data];
  console.log('保存英雄排名数据:', data);
  return await saveIndividualRankingsToConfig(data);
};

// 保存战区排名数据
export const saveTeamRankings = async (data) => {
  teamRankings = [...data];
  console.log('保存战区排名数据:', data);
  return await saveTeamRankingsToConfig(data);
};

// 保存显示配置
export const saveDisplayConfig = async (config) => {
  displayConfig = { ...config };
  console.log('保存显示配置:', config);
  return await saveDisplayConfigToConfig(config);
};



// 保存奖金规则
export const saveBonusRules = async (rules) => {
  bonusRules = [...rules];
  console.log('保存奖金规则:', rules);
  return await saveBonusRulesToConfig(rules);
};

// 验证用户登录
export const validateUser = (username, password) => {
  return systemUsers.find(user => user.username === username && user.password === password);
};

// 初始化数据（异步版本，用于应用启动时加载数据）
export const initializeData = async () => {
  try {
    await refreshData();
  } catch (error) {
    console.error('数据初始化失败:', error);
  }
};

// 刷新数据
export const refreshData = async () => {
  try {
    individualRankings = await getIndividualRankings();
    teamRankings = await getTeamRankings();
    bonusRules = await getBonusRules() || [
      { rank: '1-3', description: '前三名', individualBonus: '¥10000, ¥8000, ¥5000', teamBonus: '¥50000, ¥30000, ¥20000' },
      { rank: '4-10', description: '四至十名', individualBonus: '¥3000/人', teamBonus: '¥10000/队' },
      { rank: '11-20', description: '十一至二十名', individualBonus: '¥1000/人', teamBonus: '¥5000/队' }
    ];
    systemUsers = await getSystemUsers();
    displayConfig = await getDisplayConfig();
    battleEndTime = await getBattleEndTime();
    musicConfig = await getMusicConfig();

    return true;
  } catch (error) {
    console.error('刷新数据失败:', error);
    return false;
  }
};

// 添加系统用户
export const addSystemUser = async (user) => {
  try {
    const result = await addSystemUserToConfig(user);
    if (result) {
      // 刷新用户列表
      systemUsers = await getSystemUsers();
    }
    return result;
  } catch (error) {
    console.error('添加用户失败:', error);
    throw error;
  }
};

// 删除系统用户
export const deleteSystemUser = async (userId) => {
  try {
    const result = await deleteSystemUserToConfig(userId);
    if (result) {
      // 刷新用户列表
      systemUsers = await getSystemUsers();
    }
    return result;
  } catch (error) {
    console.error('删除用户失败:', error);
    throw error;
  }
};

// 更新系统用户
export const updateSystemUser = async (userId, updatedData) => {
  try {
    const result = await updateSystemUserToConfig(userId, updatedData);
    if (result) {
      // 刷新用户列表
      systemUsers = await getSystemUsers();
    }
    return result;
  } catch (error) {
    console.error('更新用户失败:', error);
    throw error;
  }
};