// 📢 群公告页面逻辑
const app = getApp();
const groupChatManager = require('../../../utils/group-chat-manager.js');
const apiClient = require('../../../utils/api-client.js');

Page({
  data: {
    // 系统信息
    statusBarHeight: 44,
    navBarHeight: 88,
    
    // 群信息
    groupId: '',
    groupInfo: {},
    
    // 页面模式
    mode: 'view', // view, edit
    
    // 用户权限
    currentUserId: '',
    userRole: 'member',
    canEdit: false,
    
    // 公告数据
    currentAnnouncement: null,
    announcementHistory: [],
    
    // 编辑状态
    editContent: '',
    maxLength: 500,
    canSave: false,
    
    // 弹窗状态
    showHistoryDetail: false,
    selectedHistory: {},
    showDeleteConfirm: false,
    
    // 加载状态
    loading: false,
    loadingText: '加载中...'
  },

  onLoad(options) {
    console.log('📢 群公告页面加载:', options);
    
    // 获取系统信息
    this.getSystemInfo();
    
    // 获取参数
    if (options.groupId) {
      this.setData({
        groupId: options.groupId,
        mode: options.mode || 'view'
      });
      
      // 加载群公告
      this.loadGroupAnnouncement();
    } else {
      wx.showToast({
        title: '群聊ID不能为空',
        icon: 'none'
      });
      setTimeout(() => {
        wx.navigateBack();
      }, 1500);
    }
  },

  onShow() {
    console.log('📢 群公告页面显示');
  },

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

  // 加载群公告
  async loadGroupAnnouncement() {
    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);
      if (membersResult.success) {
        const currentUser = membersResult.data.find(member => member.userId === this.data.currentUserId);
        const userRole = currentUser ? currentUser.role : 'member';
        const canEdit = userRole === 'owner' || userRole === 'admin';
        
        this.setData({
          userRole: userRole,
          canEdit: canEdit
        });
      }
      
      // 获取群公告
      const announcementResponse = await apiClient.request({
        url: `/api/v1/groups/${this.data.groupId}/announcements`,
        method: 'GET'
      });
      
      if (announcementResponse.success) {
        const announcements = announcementResponse.data || [];
        const currentAnnouncement = announcements.find(a => a.isCurrent);
        const history = announcements.filter(a => !a.isCurrent);
        
        // 处理时间显示
        if (currentAnnouncement) {
          currentAnnouncement.publishTimeText = this.formatDateTime(new Date(currentAnnouncement.publishTime));
        }
        
        history.forEach(item => {
          item.publishTimeText = this.formatDateTime(new Date(item.publishTime));
        });
        
        this.setData({
          groupInfo: groupResponse.data,
          currentAnnouncement: currentAnnouncement,
          announcementHistory: history,
          loading: false
        });
        
        // 如果是编辑模式，设置编辑内容
        if (this.data.mode === 'edit' && currentAnnouncement) {
          this.setData({
            editContent: currentAnnouncement.content
          });
          this.updateCanSave();
        }
      }
      
      console.log('✅ 群公告加载完成');
      
    } catch (error) {
      this.setData({
        loading: false
      });
      
      console.error('❌ 加载群公告失败:', error);
      wx.showToast({
        title: error.message || '加载群公告失败',
        icon: 'none'
      });
    }
  },

  // 📝 ===== 编辑功能 =====

  // 创建公告
  createAnnouncement() {
    if (!this.data.canEdit) {
      wx.showToast({
        title: '没有发布权限',
        icon: 'none'
      });
      return;
    }
    
    console.log('📝 创建公告');
    
    this.setData({
      mode: 'edit',
      editContent: ''
    });
    this.updateCanSave();
  },

  // 编辑公告
  editAnnouncement() {
    if (!this.data.canEdit) {
      wx.showToast({
        title: '没有编辑权限',
        icon: 'none'
      });
      return;
    }
    
    console.log('📝 编辑公告');
    
    this.setData({
      mode: 'edit',
      editContent: this.data.currentAnnouncement ? this.data.currentAnnouncement.content : ''
    });
    this.updateCanSave();
  },

  // 内容输入
  onContentInput(e) {
    const content = e.detail.value;
    this.setData({
      editContent: content
    });
    this.updateCanSave();
  },

  // 更新是否可以保存
  updateCanSave() {
    const canSave = this.data.editContent.trim().length > 0;
    this.setData({
      canSave: canSave
    });
  },

  // 取消编辑
  cancelEdit() {
    console.log('📝 取消编辑');
    
    if (this.data.editContent.trim() && this.data.editContent !== (this.data.currentAnnouncement?.content || '')) {
      wx.showModal({
        title: '取消编辑',
        content: '确定要取消编辑吗？未保存的内容将丢失。',
        success: (res) => {
          if (res.confirm) {
            this.setData({
              mode: 'view',
              editContent: '',
              canSave: false
            });
          }
        }
      });
    } else {
      this.setData({
        mode: 'view',
        editContent: '',
        canSave: false
      });
    }
  },

  // 保存公告
  async saveAnnouncement() {
    if (!this.data.canSave) {
      return;
    }
    
    const content = this.data.editContent.trim();
    if (!content) {
      wx.showToast({
        title: '公告内容不能为空',
        icon: 'none'
      });
      return;
    }
    
    console.log('📝 保存公告');
    
    try {
      this.setData({
        loading: true,
        loadingText: '发布公告中...'
      });
      
      const result = await groupChatManager.setGroupAnnouncement(this.data.groupId, content);
      
      this.setData({
        loading: false
      });
      
      if (result.success) {
        wx.showToast({
          title: '公告发布成功',
          icon: 'success'
        });
        
        // 切换到查看模式
        this.setData({
          mode: 'view',
          editContent: '',
          canSave: false
        });
        
        // 重新加载公告
        this.loadGroupAnnouncement();
      } else {
        throw new Error(result.error || '发布公告失败');
      }
      
    } catch (error) {
      this.setData({
        loading: false
      });
      
      console.error('❌ 保存公告失败:', error);
      wx.showToast({
        title: error.message || '发布公告失败',
        icon: 'none'
      });
    }
  },

  // 删除公告
  deleteAnnouncement() {
    if (!this.data.canEdit) {
      wx.showToast({
        title: '没有删除权限',
        icon: 'none'
      });
      return;
    }
    
    console.log('📝 删除公告');
    
    this.setData({
      showDeleteConfirm: true
    });
  },

  // 确认删除公告
  async confirmDeleteAnnouncement() {
    try {
      this.setData({
        loading: true,
        loadingText: '删除公告中...',
        showDeleteConfirm: false
      });
      
      const result = await groupChatManager.setGroupAnnouncement(this.data.groupId, '');
      
      this.setData({
        loading: false
      });
      
      if (result.success) {
        wx.showToast({
          title: '公告已删除',
          icon: 'success'
        });
        
        // 重新加载公告
        this.loadGroupAnnouncement();
      } else {
        throw new Error(result.error || '删除公告失败');
      }
      
    } catch (error) {
      this.setData({
        loading: false
      });
      
      console.error('❌ 删除公告失败:', error);
      wx.showToast({
        title: error.message || '删除公告失败',
        icon: 'none'
      });
    }
  },

  // 关闭删除确认弹窗
  closeDeleteConfirm() {
    this.setData({
      showDeleteConfirm: false
    });
  },

  // 📜 ===== 历史公告 =====

  // 查看历史公告
  viewHistoryAnnouncement(e) {
    const announcement = e.currentTarget.dataset.announcement;
    console.log('📜 查看历史公告:', announcement);
    
    this.setData({
      selectedHistory: announcement,
      showHistoryDetail: true
    });
  },

  // 关闭历史公告详情
  closeHistoryDetail() {
    this.setData({
      showHistoryDetail: false,
      selectedHistory: {}
    });
  },

  // 🔧 ===== 工具方法 =====

  // 格式化日期时间
  formatDateTime(date) {
    const now = new Date();
    const diff = now.getTime() - date.getTime();
    
    if (diff < 60000) { // 1分钟内
      return '刚刚';
    } else if (diff < 3600000) { // 1小时内
      return `${Math.floor(diff / 60000)}分钟前`;
    } else if (diff < 86400000) { // 1天内
      return `${Math.floor(diff / 3600000)}小时前`;
    } else if (diff < 604800000) { // 1周内
      return `${Math.floor(diff / 86400000)}天前`;
    } else {
      return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`;
    }
  },

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

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

  // 返回上一页
  goBack() {
    if (this.data.mode === 'edit') {
      this.cancelEdit();
    } else {
      wx.navigateBack();
    }
  }
});
