// 配置文件API路径
const CONFIG_API_URL = '/api/config';

/**
 * 读取配置文件
 * @returns {Object} 配置数据
 */
export const readConfig = async () => {
  try {
    const response = await fetch(CONFIG_API_URL);
    if (response.ok) {
      return await response.json();
    } else if (response.status === 404) {
      // 配置文件不存在，使用默认配置
      console.log('配置文件不存在，使用默认配置');
      return getDefaultConfig();
    }
    throw new Error(`获取配置失败: ${response.status}`);
  } catch (error) {
    console.error('读取配置失败:', error);
    return getDefaultConfig();
  }
};

/**
 * 写入配置文件
 * @param {Object} config 新的配置数据
 * @returns {boolean} 是否写入成功
 */
export const writeConfig = async (config) => {
  try {
    const response = await fetch(CONFIG_API_URL, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(config)
    });
    
    if (response.ok) {
      const result = await response.json();
      return result.success;
    }
    
    throw new Error(`保存配置失败: ${response.status}`);
  } catch (error) {
    console.error('写入配置失败:', error);
    return false;
  }
};

// 同步版本的readConfig（用于向后兼容）
export const getConfig = async () => {
  return await readConfig();
};

/**
 * 获取默认配置（用于兜底）
 * @returns {Object} 默认配置
 */
const getDefaultConfig = () => ({
  individualRankings: [],
  teamRankings: [],
  bonusRules: [],
  systemUsers: [],
  displayConfig: {
    showBonusModule: true, // 控制奖金设置模块的显示，默认不显示
    individual: {
      showLevel: false,
      showDepartment: false,
      scoreColumn: {
        displayName: '分数',
        displayStyle: 'number'
      },
      teamColumn: {
        displayName: '战区',
        displayStyle: 'text'
      },
      columnWidths: {
        rank: '80px',
        name: '150px',
        dept: '150px',
        team: '120px',
        score: '100px',
        level: '80px',
        bonus: '100px'
      }
    },
    team: {
      showMemberCount: false,
      showLeader: false,
      totalScoreColumn: {
        displayName: '业绩',
        displayStyle: 'number'
      },
      columnWidths: {
        rank: '80px',
        name: '150px',
        score: '100px',
        memberCount: '120px',
        bonus: '100px'
      }
    }
  },
  // ========== 音乐配置默认值（和displayConfig同级） ==========
  music: {
    enabled: false,
    filePath: '',
    volume: 0.5  // 默认音量50%
  },
  battleEndTime: {
    date: new Date().toISOString().split('T')[0],
    time: '00:00:00'
  },
  backgroundConfig: {
    useBackgroundImage: true,
    backgroundImage: '/battle-background.jpg', // 默认战旗背景图片
    backgroundSize: 'contain',
    backgroundPosition: 'center',
    backgroundColor: '#1a1a1a' // 备选背景色
  }
});

/**
 * 获取英雄排名数据
 * @returns {Array} 英雄排名数组
 */
export const getIndividualRankings = async () => {
  const config = await readConfig();
  return config.individualRankings || [];
};

/**
 * 保存英雄排名数据
 * @param {Array} rankings 英雄排名数组
 * @returns {boolean} 是否保存成功
 */
export const saveIndividualRankings = async (rankings) => {
  const config = await readConfig();
  config.individualRankings = rankings;
  return await writeConfig(config);
};

/**
 * 获取战区排名数据
 * @returns {Array} 战区排名数组
 */
export const getTeamRankings = async () => {
  const config = await readConfig();
  return config.teamRankings || [];
};

/**
 * 保存战区排名数据
 * @param {Array} rankings 战区排名数组
 * @returns {boolean} 是否保存成功
 */
export const saveTeamRankings = async (rankings) => {
  const config = await readConfig();
  config.teamRankings = rankings;
  return await writeConfig(config);
};

/**
 * 获取奖金规则
 * @returns {Array} 奖金规则数组
 */
export const getBonusRules = async () => {
  const config = await readConfig();
  return config.bonusRules || [];
};

/**
 * 保存奖金规则
 * @param {Array} rules 奖金规则数组
 * @returns {boolean} 是否保存成功
 */
export const saveBonusRules = async (rules) => {
  const config = await readConfig();
  config.bonusRules = rules;
  return await writeConfig(config);
};

/**
 * 获取系统用户
 * @returns {Array} 系统用户数组
 */
export const getSystemUsers = async () => {
  const config = await readConfig();
  return config.systemUsers || [];
};

/**
 * 保存系统用户
 * @param {Array} users 系统用户数组
 * @returns {boolean} 是否保存成功
 */
export const saveSystemUsers = async (users) => {
  const config = await readConfig();
  config.systemUsers = users;
  return await writeConfig(config);
};

/**
 * 添加用户
 * @param {Object} user 用户信息
 * @returns {boolean} 是否添加成功
 */
export const addSystemUser = async (user) => {
  try {
    const users = await getSystemUsers();
    // 检查用户名是否已存在
    const existingUser = users.find(u => u.username === user.username);
    if (existingUser) {
      throw new Error('用户名已存在');
    }
    
    users.push({
      id: Date.now(),
      ...user
    });
    
    return await saveSystemUsers(users);
  } catch (error) {
    console.error('添加用户失败:', error);
    throw error;
  }
};

/**
 * 删除用户
 * @param {number} userId 用户ID
 * @returns {boolean} 是否删除成功
 */
export const deleteSystemUser = async (userId) => {
  try {
    let users = await getSystemUsers();
    // 确保至少保留一个管理员用户
    if (users.length <= 1) {
      throw new Error('系统至少需要保留一个管理员用户');
    }
    
    users = users.filter(u => u.id !== userId);
    return await saveSystemUsers(users);
  } catch (error) {
    console.error('删除用户失败:', error);
    throw error;
  }
};

/**
 * 更新用户信息
 * @param {number} userId 用户ID
 * @param {Object} updatedData 更新的数据
 * @returns {boolean} 是否更新成功
 */
export const updateSystemUser = async (userId, updatedData) => {
  try {
    const users = await getSystemUsers();
    const userIndex = users.findIndex(u => u.id === userId);
    
    if (userIndex === -1) {
      throw new Error('用户不存在');
    }
    
    // 如果要更新用户名，检查是否与其他用户冲突
    if (updatedData.username && updatedData.username !== users[userIndex].username) {
      const existingUser = users.find(u => u.id !== userId && u.username === updatedData.username);
      if (existingUser) {
        throw new Error('用户名已存在');
      }
    }
    
    users[userIndex] = {
      ...users[userIndex],
      ...updatedData
    };
    
    return await saveSystemUsers(users);
  } catch (error) {
    console.error('更新用户失败:', error);
    throw error;
  }
};

/**
 * 获取显示配置
 * @returns {Object} 显示配置
 */
export const getDisplayConfig = async () => {
  const config = await readConfig();
  return config.displayConfig || getDefaultConfig().displayConfig;
};

/**
 * 保存显示配置
 * @param {Object} displayConfig 显示配置
 * @returns {boolean} 是否保存成功
 */
export const saveDisplayConfig = async (displayConfig) => {
  const config = await readConfig();
  config.displayConfig = displayConfig;
  return await writeConfig(config);
};

/**
 * 获取战斗结束时间
 * @returns {Object} 结束时间配置
 */
export const getBattleEndTime = async () => {
  const config = await readConfig();
  return config.battleEndTime || getDefaultConfig().battleEndTime;
};

/**
 * 保存战斗结束时间
 * @param {Object} endTime 结束时间配置
 * @returns {boolean} 是否保存成功
 */
export const saveBattleEndTime = async (endTime) => {
  const config = await readConfig();
  config.battleEndTime = endTime;
  return await writeConfig(config);
};

/**
 * 获取背景配置
 * @returns {Object} 背景配置
 */
export const getBackgroundConfig = async () => {
  const config = await readConfig();
  return config.backgroundConfig || getDefaultConfig().backgroundConfig;
};

/**
 * 保存背景配置
 * @param {Object} backgroundConfig 背景配置
 * @returns {boolean} 是否保存成功
 */
export const saveBackgroundConfig = async (backgroundConfig) => {
  const config = await readConfig();
  config.backgroundConfig = backgroundConfig;
  return await writeConfig(config);
};

/**
 * 获取音乐配置
 * @returns {Object} 音乐配置
 */
export const getMusicConfig = async () => {
  const config = await readConfig();
  return config.music || getDefaultConfig().music;
};

/**
 * 保存音乐配置
 * @param {Object} musicConfig 音乐配置
 * @returns {boolean} 是否保存成功
 */
export const saveMusicConfig = async (musicConfig) => {
  const config = await readConfig();
  // 确保音量是数字类型
  const normalizedMusicConfig = {
    ...musicConfig,
    volume: typeof musicConfig.volume === 'string' ? parseFloat(musicConfig.volume) : musicConfig.volume
  };
  config.music = normalizedMusicConfig;
  return await writeConfig(config);
};

/**
 * 上传音乐
 * @param {File} file 音乐文件
 * @returns {Object} 上传结果 { success: boolean, filePath?: string, filename?: string, originalName?: string, size?: number, error?: string }
 */
export const uploadMusic = async (file) => {
  try {
    const formData = new FormData();
    formData.append('music', file);
    
    const response = await fetch('/api/music', {
      method: 'POST',
      body: formData
    });
    
    const result = await response.json();
    
    if (response.ok) {
      return result;
    } else {
      throw new Error(result.error || '音乐上传失败');
    }
  } catch (error) {
    console.error('上传音乐失败:', error);
    return { success: false, error: error.message };
  }
};

/**
 * 删除音乐
 * @param {string} filename 文件名
 * @returns {Object} 删除结果 { success: boolean, error?: string }
 */
export const deleteMusic = async (filename) => {
  try {
    const response = await fetch(`/api/music/${filename}`, {
      method: 'DELETE'
    });
    
    const result = await response.json();
    
    if (response.ok) {
      return result;
    } else {
      throw new Error(result.error || '音乐删除失败');
    }
  } catch (error) {
    console.error('删除音乐失败:', error);
    return { success: false, error: error.message };
  }
};

/**
 * 获取音乐文件列表
 * @returns {Object} 列表结果 { success: boolean, files?: Array, error?: string }
 */
export const getMusicList = async () => {
  try {
    const response = await fetch('/api/music');
    
    const result = await response.json();
    
    if (response.ok) {
      return result;
    } else {
      throw new Error(result.error || '获取音乐列表失败');
    }
  } catch (error) {
    console.error('获取音乐列表失败:', error);
    return { success: false, error: error.message };
  }
};