// 👥 创建群聊页面逻辑
const app = getApp();
const groupChatManager = require('../../../utils/group-chat-manager.js');
const apiClient = require('../../../utils/api-client.js');

Page({
  data: {
    // 系统信息
    statusBarHeight: 44,
    navBarHeight: 88,

    // 群信息
    groupName: '',
    groupDescription: '',
    groupAvatar: '',

    // 配置限制
    maxGroupNameLength: 20,
    maxDescriptionLength: 200,

    // 成员选择
    friendsList: [],
    filteredFriends: [],
    selectedMembers: [],
    searchKeyword: '',

    // 群设置
    allowMemberInvite: true,
    saveToContacts: true,
    showQRCode: true,

    // 状态
    isCreating: false,
    canCreate: false
  },

  onLoad(options) {

    // 获取系统信息
    this.getSystemInfo();

    // 加载好友列表
    this.loadFriendsList();

    // 处理预选成员
    if (options.preSelectedMembers) {
      try {
        const preSelected = JSON.parse(decodeURIComponent(options.preSelectedMembers));
        this.setData({
          selectedMembers: preSelected
        });
        this.updateCanCreate();
      } catch (error) {
        console.error('❌ 解析预选成员失败:', error);
      }
    }
  },

  onShow() {

  },

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

  // 加载好友列表
  async loadFriendsList() {
    try {
      wx.showLoading({
        title: '加载好友列表...'
      });

      const response = await apiClient.request({
        url: '/api/v1/friends',
        method: 'GET'
      });

      wx.hideLoading();

      if (response.success) {
        const friends = response.data || [];

        // 标记已选择的好友
        const friendsWithSelection = friends.map(friend => ({
          ...friend,
          selected: this.data.selectedMembers.some(member => member.userId === friend.userId)
        }));

        this.setData({
          friendsList: friendsWithSelection,
          filteredFriends: friendsWithSelection
        });

      } else {
        throw new Error(response.error || '加载好友列表失败');
      }

    } catch (error) {
      wx.hideLoading();
      console.error('❌ 加载好友列表失败:', error);
      wx.showToast({
        title: '加载好友列表失败',
        icon: 'none'
      });
    }
  },

  // 👥 ===== 群信息设置 =====

  // 选择群头像
  selectGroupAvatar() {

    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        const tempFilePath = res.tempFilePaths[0];
        this.setData({
          groupAvatar: tempFilePath
        });

      },
      fail: (error) => {
        console.error('❌ 选择群头像失败:', error);
        wx.showToast({
          title: '选择头像失败',
          icon: 'none'
        });
      }
    });
  },

  // 群名称输入
  onGroupNameInput(e) {
    const value = e.detail.value;
    this.setData({
      groupName: value
    });
    this.updateCanCreate();
  },

  // 群描述输入
  onGroupDescInput(e) {
    const value = e.detail.value;
    this.setData({
      groupDescription: value
    });
  },

  // 👤 ===== 成员选择 =====

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

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

  // 过滤好友
  filterFriends(keyword) {
    let filtered = this.data.friendsList;

    if (keyword.trim()) {
      filtered = this.data.friendsList.filter(friend => {
        const name = (friend.nickname || friend.username || '').toLowerCase();
        return name.includes(keyword.toLowerCase());
      });
    }

    this.setData({
      filteredFriends: filtered
    });
  },

  // 切换成员选择
  toggleMember(e) {
    const userId = e.currentTarget.dataset.userId;
    const friend = this.data.friendsList.find(f => f.userId === userId);

    if (!friend) return;

    let selectedMembers = [...this.data.selectedMembers];
    let friendsList = [...this.data.friendsList];
    let filteredFriends = [...this.data.filteredFriends];

    const isSelected = selectedMembers.some(member => member.userId === userId);

    if (isSelected) {
      // 移除选择
      selectedMembers = selectedMembers.filter(member => member.userId !== userId);
    } else {
      // 添加选择
      selectedMembers.push(friend);
    }

    // 更新好友列表的选择状态
    friendsList = friendsList.map(f => ({
      ...f,
      selected: selectedMembers.some(member => member.userId === f.userId)
    }));

    filteredFriends = filteredFriends.map(f => ({
      ...f,
      selected: selectedMembers.some(member => member.userId === f.userId)
    }));

    this.setData({
      selectedMembers: selectedMembers,
      friendsList: friendsList,
      filteredFriends: filteredFriends
    });

    this.updateCanCreate();
  },

  // 移除成员
  removeMember(e) {
    const userId = e.currentTarget.dataset.userId;

    let selectedMembers = this.data.selectedMembers.filter(member => member.userId !== userId);
    let friendsList = [...this.data.friendsList];
    let filteredFriends = [...this.data.filteredFriends];

    // 更新好友列表的选择状态
    friendsList = friendsList.map(f => ({
      ...f,
      selected: selectedMembers.some(member => member.userId === f.userId)
    }));

    filteredFriends = filteredFriends.map(f => ({
      ...f,
      selected: selectedMembers.some(member => member.userId === f.userId)
    }));

    this.setData({
      selectedMembers: selectedMembers,
      friendsList: friendsList,
      filteredFriends: filteredFriends
    });

    this.updateCanCreate();
  },

  // ⚙️ ===== 群设置 =====

  // 允许成员邀请设置变化
  onAllowInviteChange(e) {
    this.setData({
      allowMemberInvite: e.detail.value
    });
  },

  // 保存到通讯录设置变化
  onSaveContactsChange(e) {
    this.setData({
      saveToContacts: e.detail.value
    });
  },

  // 显示群二维码设置变化
  onShowQRCodeChange(e) {
    this.setData({
      showQRCode: e.detail.value
    });
  },

  // 🎯 ===== 群聊创建 =====

  // 更新是否可以创建
  updateCanCreate() {
    const canCreate = this.data.groupName.trim().length > 0 && this.data.selectedMembers.length > 0;
    this.setData({
      canCreate: canCreate
    });
  },

  // 创建群聊
  async createGroup() {
    if (!this.data.canCreate || this.data.isCreating) {
      return;
    }

    try {
      this.setData({
        isCreating: true
      });

      // 构建群聊信息
      const groupInfo = {
        name: this.data.groupName.trim(),
        description: this.data.groupDescription.trim(),
        avatar: this.data.groupAvatar,
        memberIds: this.data.selectedMembers.map(member => member.userId),
        settings: {
          allowMemberInvite: this.data.allowMemberInvite,
          saveToContacts: this.data.saveToContacts,
          showQRCode: this.data.showQRCode
        }
      };

      // 调用群聊管理器创建群聊
      const result = await groupChatManager.createGroup(groupInfo);

      this.setData({
        isCreating: false
      });

      if (result.success) {
        wx.showToast({
          title: '群聊创建成功',
          icon: 'success'
        });

        // 跳转到群聊页面
        setTimeout(() => {
          wx.redirectTo({
            url: `/pages/message/chat/chat?chatType=1&targetId=${result.data.groupId}&chatName=${encodeURIComponent(result.data.name)}`
          });
        }, 1500);

      } else {
        wx.showToast({
          title: result.error || '创建群聊失败',
          icon: 'none'
        });
      }

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

      console.error('❌ 创建群聊失败:', error);
      wx.showToast({
        title: '创建群聊失败',
        icon: 'none'
      });
    }
  },

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

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

