// 群组功能API客户端
const apiClient = require('./api-client.js');

class GroupAPI {
  constructor() {
    this.apiClient = apiClient;
  }

  // 🔥 ===== 群组管理 =====

  // 创建群组
  async createGroup(groupData) {
    try {
      const response = await this.apiClient.post('/api/v1/group/create', {
        name: groupData.name,
        avatar: groupData.avatar || '',
        description: groupData.description || '',
        notice: groupData.notice || '',
        type: groupData.type || 0,
        joinType: groupData.joinType || 0,
        memberIds: groupData.memberIds || []
      });
      return response;
    } catch (error) {
      console.error('创建群组失败:', error);
      throw error;
    }
  }

  // 获取用户群组列表
  async getGroupList() {
    try {
      const response = await this.apiClient.get('/api/v1/group/list');
      return response;
    } catch (error) {
      console.error('获取群组列表失败:', error);
      throw error;
    }
  }

  // 获取群组详情
  async getGroupDetail(groupId) {
    try {
      const response = await this.apiClient.get(`/api/v1/group/${groupId}/detail`);
      return response;
    } catch (error) {
      console.error('获取群组详情失败:', error);
      throw error;
    }
  }

  // 获取群组信息
  async getGroupInfo(groupId) {
    try {
      const response = await this.apiClient.get(`/api/v1/group/${groupId}/info`);
      return response;
    } catch (error) {
      console.error('获取群组信息失败:', error);
      throw error;
    }
  }

  // 更新群组信息
  async updateGroup(groupId, updates) {
    try {
      const response = await this.apiClient.put(`/api/v1/group/${groupId}`, updates);
      return response;
    } catch (error) {
      console.error('更新群组信息失败:', error);
      throw error;
    }
  }

  // 删除群组
  async deleteGroup(groupId) {
    try {
      const response = await this.apiClient.delete(`/api/v1/group/${groupId}`);
      return response;
    } catch (error) {
      console.error('删除群组失败:', error);
      throw error;
    }
  }

  // 申请加入群组
  async joinGroup(groupId, message = '') {
    try {
      const response = await this.apiClient.post('/api/v1/group/join', {
        groupId: groupId,
        message: message
      });
      return response;
    } catch (error) {
      console.error('申请加入群组失败:', error);
      throw error;
    }
  }

  // 通过邀请码加入群组
  async joinGroupByCode(groupCode, message = '') {
    try {
      const response = await this.apiClient.post('/api/v1/group/join-by-code', {
        groupCode: groupCode,
        message: message
      });
      return response;
    } catch (error) {
      console.error('通过邀请码加入群组失败:', error);
      throw error;
    }
  }

  // 退出群组
  async leaveGroup(groupId) {
    try {
      const response = await this.apiClient.post(`/api/v1/group/${groupId}/leave`);
      return response;
    } catch (error) {
      console.error('退出群组失败:', error);
      throw error;
    }
  }

  // 🔥 ===== 群成员管理 =====

  // 获取群成员列表
  async getGroupMembers(groupId) {
    try {
      const response = await this.apiClient.get(`/api/v1/group/${groupId}/members`);
      return response;
    } catch (error) {
      console.error('获取群成员列表失败:', error);
      throw error;
    }
  }

  // 添加群成员
  async addGroupMembers(groupId, memberIds) {
    try {
      const response = await this.apiClient.post(`/api/v1/group/${groupId}/members`, {
        memberIds: memberIds
      });
      return response;
    } catch (error) {
      console.error('添加群成员失败:', error);
      throw error;
    }
  }

  // 移除群成员
  async removeGroupMember(groupId, memberId) {
    try {
      const response = await this.apiClient.delete(`/api/v1/group/${groupId}/members/${memberId}`);
      return response;
    } catch (error) {
      console.error('移除群成员失败:', error);
      throw error;
    }
  }

  // 更新群成员信息
  async updateGroupMember(memberData) {
    try {
      const response = await this.apiClient.put('/api/v1/group/members', memberData);
      return response;
    } catch (error) {
      console.error('更新群成员信息失败:', error);
      throw error;
    }
  }

  // 🔥 ===== 群组加入请求管理 =====

  // 获取群组加入请求
  async getGroupJoinRequests(groupId) {
    try {
      const response = await this.apiClient.get(`/api/v1/group/${groupId}/join-requests`);
      return response;
    } catch (error) {
      console.error('获取群组加入请求失败:', error);
      throw error;
    }
  }

  // 处理群组加入请求
  async handleGroupJoinRequest(requestData) {
    try {
      const response = await this.apiClient.post('/api/v1/group/join-requests', requestData);
      return response;
    } catch (error) {
      console.error('处理群组加入请求失败:', error);
      throw error;
    }
  }

  // 🔥 ===== 工具方法 =====

  // 格式化群组类型
  getGroupTypeText(type) {
    const typeMap = {
      0: '普通群',
      1: '频道'
    };
    return typeMap[type] || '未知类型';
  }

  // 格式化加入方式
  getJoinTypeText(joinType) {
    const joinTypeMap = {
      0: '自由加入',
      1: '需要验证',
      2: '禁止加入'
    };
    return joinTypeMap[joinType] || '未知方式';
  }

  // 格式化群组状态
  getGroupStatusText(status) {
    const statusMap = {
      0: '已解散',
      1: '正常',
      2: '已封禁'
    };
    return statusMap[status] || '未知状态';
  }

  // 格式化成员角色
  getMemberRoleText(role) {
    const roleMap = {
      0: '普通成员',
      1: '管理员',
      2: '群主'
    };
    return roleMap[role] || '未知角色';
  }

  // 验证群组名称
  validateGroupName(name) {
    if (!name || typeof name !== 'string') {
      return { valid: false, message: '群组名称不能为空' };
    }
    
    if (name.length < 2) {
      return { valid: false, message: '群组名称至少2个字符' };
    }
    
    if (name.length > 50) {
      return { valid: false, message: '群组名称不能超过50个字符' };
    }
    
    return { valid: true, message: '' };
  }

  // 验证群组描述
  validateGroupDescription(description) {
    if (!description) {
      return { valid: true, message: '' };
    }
    
    if (description.length > 200) {
      return { valid: false, message: '群组描述不能超过200个字符' };
    }
    
    return { valid: true, message: '' };
  }

  // 验证群组公告
  validateGroupNotice(notice) {
    if (!notice) {
      return { valid: true, message: '' };
    }
    
    if (notice.length > 200) {
      return { valid: false, message: '群组公告不能超过200个字符' };
    }
    
    return { valid: true, message: '' };
  }

  // 验证邀请码格式
  validateGroupCode(groupCode) {
    if (!groupCode || typeof groupCode !== 'string') {
      return false;
    }
    
    // 邀请码应该是8-20位字符
    const codeRegex = /^[A-Z0-9]{8,20}$/;
    return codeRegex.test(groupCode);
  }

  // 生成群组默认头像
  generateGroupAvatar(groupName) {
    // 可以根据群组名称生成默认头像URL
    const firstChar = groupName ? groupName.charAt(0) : 'G';
    return `https://ui-avatars.com/api/?name=${encodeURIComponent(firstChar)}&background=random&color=fff&size=200`;
  }

  // 计算群组成员上限
  getGroupMemberLimit(type, ownerMemberLevel = 0) {
    if (type === 1) {
      // 频道类型
      return ownerMemberLevel >= 2 ? 10000 : 5000;
    } else {
      // 普通群
      const limits = {
        0: 100,   // 普通用户
        1: 200,   // 会员
        2: 500,   // 高级会员
        3: 1000   // VIP会员
      };
      return limits[ownerMemberLevel] || 100;
    }
  }

  // 检查用户权限
  checkUserPermission(userRole, action) {
    const permissions = {
      0: ['view', 'send_message'], // 普通成员
      1: ['view', 'send_message', 'manage_members', 'edit_info'], // 管理员
      2: ['view', 'send_message', 'manage_members', 'edit_info', 'delete_group', 'manage_admins'] // 群主
    };
    
    const userPermissions = permissions[userRole] || [];
    return userPermissions.includes(action);
  }
}

// 创建全局单例
const groupAPI = new GroupAPI();

module.exports = groupAPI;
