// 👥 群成员管理页面逻辑
const app = getApp();
const groupChatManager = require('../../../utils/group-chat-manager.js');
const apiClient = require('../../../utils/api-client.js');
const screen =require('../../../utils/screen-adapter')

Page({
  data: {
    stros:[{
      nickname:'Guodong Chow',
      avatar:'../../../images/group/testImg.jpg'
    }],
    // 系统信息
    statusBarHeight: 44,
    navBarHeight: 88,

    // 群信息
    groupId: '',
    groupInfo: {},

    // 成员数据
    allMembers: [],
    groupOwner: null,
    admins: [],
    members: [],

    // 筛选后的数据
    filteredAdmins: [],
    filteredMembers: [],

    // 统计数据
    memberCount: 0,
    adminCount: 0,
    normalMemberCount: 0,

    // 用户权限
    currentUserId: '',
    userRole: 'member',
    isOwner: false,
    isOwnerOrAdmin: false,
    canInviteMembers: false,

    // 搜索和筛选
    searchKeyword: '',
    currentFilter: 'all', // all, admin, member

    // 成员操作
    showMemberActionModal: false,
    selectedMember: {},
    canRemoveMember: false,

    // 加载状态
    loading: false,
    loadingText: '加载中...'
  },

  onLoad(options) {
    const {stros} = this.data
    let testArrs= Array(20).fill(stros).flat();
    console.log('testArrs------',testArrs);
    this.setData({
      testArrs
    })

    screen.init(this)
    console.log('123---------123',this.data);
    // 获取系统信息
    this.getSystemInfo();

    // 获取群ID
    if (options.groupId) {
      this.setData({
        groupId: options.groupId
      });

      // 加载群成员
      this.loadGroupMembers();
    } else {
      wx.showToast({
        title: '群聊ID不能为空',
        icon: 'none'
      });
      setTimeout(() => {
        wx.navigateBack();
      }, 1500);
    }
  },

  onShow() {

    // 刷新成员列表
    if (this.data.groupId) {
      this.loadGroupMembers();
    }
  },

  // 获取系统信息
  getSystemInfo() {
    const systemInfo = wx.getSystemInfoSync();
    console.log('systemInfo-------systemInfo',systemInfo);
    this.setData({
      statusBarHeight: systemInfo.statusBarHeight || 44,
      navBarHeight: 88,
      currentUserId: wx.getStorageSync('userId')
    });
  },

  // 加载群成员
  async loadGroupMembers() {
    try {
      this.setData({
        loading: true,
        loadingText: '加载成员列表中...'
      });

      // 获取群基本信息
      const groupResponse = await apiClient.request({
        url: `/api/v1/groups/${this.data.groupId}`,
        method: 'GET'
      });

      if (!groupResponse.success) {
        throw new Error(groupResponse.error || '获取群信息失败');
      }

      // 获取群成员列表
      const membersResult = await groupChatManager.getGroupMembers(this.data.groupId, false);

      if (!membersResult.success) {
        throw new Error(membersResult.error || '获取群成员失败');
      }

      const allMembers = membersResult.data;

      // 分类成员
      const groupOwner = allMembers.find(member => member.role === 'owner');
      const admins = allMembers.filter(member => member.role === 'admin');
      const members = allMembers.filter(member => member.role === 'member');

      // 获取当前用户角色
      const currentUser = allMembers.find(member => member.userId === this.data.currentUserId);
      const userRole = currentUser ? currentUser.role : 'member';

      // 计算权限
      const isOwner = userRole === 'owner';
      const isOwnerOrAdmin = userRole === 'owner' || userRole === 'admin';
      const canInviteMembers = isOwnerOrAdmin || groupResponse.data.settings?.allowMemberInvite;

      this.setData({
        groupInfo: groupResponse.data,
        allMembers: allMembers,
        groupOwner: groupOwner,
        admins: admins,
        members: members,
        memberCount: allMembers.length,
        adminCount: admins.length + (groupOwner ? 1 : 0),
        normalMemberCount: members.length,
        userRole: userRole,
        isOwner: isOwner,
        isOwnerOrAdmin: isOwnerOrAdmin,
        canInviteMembers: canInviteMembers,
        loading: false
      });

      // 应用当前筛选
      this.applyFilter();

    } catch (error) {
      this.setData({
        loading: false
      });

      console.error('❌ 加载群成员失败:', error);
      wx.showToast({
        title: error.message || '加载群成员失败',
        icon: 'none'
      });
    }
  },

  // 🔍 ===== 搜索和筛选 =====

  // 搜索输入
  onSearchInput(e) {
    const keyword = e.detail.value;
    this.setData({
      searchKeyword: keyword
    });
    this.applyFilter();
  },

  // 清除搜索
  clearSearch() {
    this.setData({
      searchKeyword: ''
    });
    this.applyFilter();
  },

  // 切换筛选
  switchFilter(e) {
    const filter = e.currentTarget.dataset.filter;

    this.setData({
      currentFilter: filter
    });
    this.applyFilter();
  },

  // 应用筛选
  applyFilter() {
    const keyword = this.data.searchKeyword.toLowerCase();

    // 筛选管理员
    let filteredAdmins = this.data.admins;
    if (keyword) {
      filteredAdmins = this.data.admins.filter(member => {
        const name = (member.nickname || member.username || '').toLowerCase();
        return name.includes(keyword);
      });
    }

    // 筛选普通成员
    let filteredMembers = this.data.members;
    if (keyword) {
      filteredMembers = this.data.members.filter(member => {
        const name = (member.nickname || member.username || '').toLowerCase();
        return name.includes(keyword);
      });
    }

    this.setData({
      filteredAdmins: filteredAdmins,
      filteredMembers: filteredMembers
    });
  },

  // 👤 ===== 成员操作 =====

  // 邀请成员
  inviteMembers() {
    if (!this.data.canInviteMembers) {
      wx.showToast({
        title: '没有邀请权限',
        icon: 'none'
      });
      return;
    }

    // 跳转到邀请成员页面
    wx.navigateTo({
      url: `/subpackages/group/create-group-chat/create-group-chat?groupId=${this.data.groupId}`
    });
  },

  // 查看成员资料
  viewMemberProfile(e) {
    const userId = e.currentTarget.dataset.userId;

    // 关闭操作弹窗
    this.closeMemberActionModal();

    if (userId === this.data.currentUserId) {
      // 查看自己的资料
      wx.navigateTo({
        url: '/subpackages/profile/profile/profile'
      });
    } else {
      // 查看其他成员资料
      wx.navigateTo({
        url: `/subpackages/social/user-detail/user-detail?customId=${userId}`
      });
    }
  },

  // 显示成员操作菜单
  showMemberActions(e) {
    const member = e.currentTarget.dataset.member;

    if (!member || member.userId === this.data.currentUserId) {
      return;
    }

    // 计算是否可以移除成员
    const canRemoveMember = this.data.isOwnerOrAdmin &&
                           member.role !== 'owner' &&
                           (this.data.isOwner || member.role !== 'admin');

    this.setData({
      selectedMember: member,
      canRemoveMember: canRemoveMember,
      showMemberActionModal: true
    });
  },

  // 关闭成员操作弹窗
  closeMemberActionModal() {
    this.setData({
      showMemberActionModal: false,
      selectedMember: {},
      canRemoveMember: false
    });
  },

  // 发送消息给成员
  sendMessageToMember() {
    const member = this.data.selectedMember;

    // 关闭弹窗
    this.closeMemberActionModal();

    // 跳转到私聊页面
    wx.navigateTo({
      url: `/pages/message/chat/chat?chatType=0&targetId=${member.userId}&chatName=${encodeURIComponent(member.nickname || member.username)}`
    });
  },

  // 切换成员管理员状态
  async toggleMemberAdmin() {
    const member = this.data.selectedMember;
    const isAdmin = member.role === 'admin';

    try {
      this.setData({
        loading: true,
        loadingText: isAdmin ? '取消管理员中...' : '设置管理员中...'
      });

      const result = await groupChatManager.setAdmin(this.data.groupId, member.userId, !isAdmin);

      this.setData({
        loading: false
      });

      if (result.success) {
        wx.showToast({
          title: isAdmin ? '已取消管理员' : '已设为管理员',
          icon: 'success'
        });

        // 关闭弹窗
        this.closeMemberActionModal();

        // 刷新成员列表
        this.loadGroupMembers();
      } else {
        throw new Error(result.error || '操作失败');
      }

    } catch (error) {
      this.setData({
        loading: false
      });

      console.error('❌ 切换管理员状态失败:', error);
      wx.showToast({
        title: error.message || '操作失败',
        icon: 'none'
      });
    }
  },

  // 移出群聊
  removeMemberFromGroup() {
    const member = this.data.selectedMember;

    wx.showModal({
      title: '移出群聊',
      content: `确定要将"${member.nickname || member.username}"移出群聊吗？`,
      confirmText: '移出',
      confirmColor: '#FF3B30',
      success: (res) => {
        if (res.confirm) {
          this.performRemoveMember(member);
        }
      }
    });
  },

  // 执行移出成员
  async performRemoveMember(member) {
    try {
      this.setData({
        loading: true,
        loadingText: '移出成员中...'
      });

      const result = await groupChatManager.removeMember(this.data.groupId, member.userId);

      this.setData({
        loading: false
      });

      if (result.success) {
        wx.showToast({
          title: '成员已移出',
          icon: 'success'
        });

        // 关闭弹窗
        this.closeMemberActionModal();

        // 刷新成员列表
        this.loadGroupMembers();
      } else {
        throw new Error(result.error || '移出成员失败');
      }

    } catch (error) {
      this.setData({
        loading: false
      });

      console.error('❌ 移出成员失败:', error);
      wx.showToast({
        title: error.message || '移出成员失败',
        icon: 'none'
      });
    }
  },

  // 阻止事件冒泡
  stopPropagation() {
    // 阻止点击事件冒泡
  },

  // 🧭 ===== 页面导航 =====

  // 返回上一页
  goBack() {
    wx.navigateBack();
  }
});

