// 🔔 通知设置页面逻辑
const notificationManager = require('../../../utils/notification-manager.js');

Page({
  data: {
    // 系统信息
    statusBarHeight: 44,
    navBarHeight: 88,
    
    // 通知设置
    notificationSettings: {
      enabled: true,
      message: {
        enabled: true,
        showPreview: true,
        sound: true,
        vibrate: true,
        groupByChat: true
      },
      group: {
        enabled: true,
        mentionOnly: false,
        sound: true,
        vibrate: true
      },
      friend: {
        enabled: true,
        sound: true
      },
      system: {
        enabled: true
      }
    },
    
    // 免打扰设置
    doNotDisturb: {
      enabled: false,
      startTime: '22:00',
      endTime: '08:00',
      allowUrgent: true,
      allowMentions: true
    },
    
    // 未读计数
    unreadCount: 0,
    
    // 时间选择器
    showTimePicker: false,
    selectedTime: '22:00',
    timePickerType: 'start', // start, end
    
    // 加载状态
    loading: false
  },

  onLoad(options) {
    console.log('🔔 通知设置页面加载');
    
    // 获取系统信息
    this.getSystemInfo();
    
    // 加载通知设置
    this.loadNotificationSettings();
    
    // 加载未读计数
    this.loadUnreadCount();
  },

  onShow() {
    console.log('🔔 通知设置页面显示');
    
    // 刷新未读计数
    this.loadUnreadCount();
  },

  // 获取系统信息
  getSystemInfo() {
    try {
      const windowInfo = wx.getWindowInfo();
      this.setData({
        statusBarHeight: windowInfo.statusBarHeight || 44,
        navBarHeight: 88
      });
    } catch (error) {
      console.error('获取系统信息失败:', error);
      this.setData({
        statusBarHeight: 44,
        navBarHeight: 88
      });
    }
  },

  // 加载通知设置
  loadNotificationSettings() {
    try {
      // 从通知管理器获取设置
      const settings = notificationManager.getStatus();
      
      if (settings.notificationSettings) {
        this.setData({
          notificationSettings: {
            ...this.data.notificationSettings,
            ...settings.notificationSettings
          }
        });
      }
      
      // 加载免打扰设置
      const doNotDisturbSettings = wx.getStorageSync('doNotDisturbSettings');
      if (doNotDisturbSettings) {
        this.setData({
          doNotDisturb: {
            ...this.data.doNotDisturb,
            ...doNotDisturbSettings
          }
        });
      }
      
      console.log('✅ 通知设置加载完成');
      
    } catch (error) {
      console.error('❌ 加载通知设置失败:', error);
    }
  },

  // 加载未读计数
  loadUnreadCount() {
    try {
      const totalUnread = notificationManager.getTotalUnreadCount();
      this.setData({
        unreadCount: totalUnread
      });
    } catch (error) {
      console.error('❌ 加载未读计数失败:', error);
    }
  },

  // 🔔 ===== 通知设置变更 =====

  // 通知总开关变更
  onNotificationEnabledChange(e) {
    const enabled = e.detail.value;
    console.log('🔔 通知总开关变更:', enabled);
    
    this.setData({
      'notificationSettings.enabled': enabled
    });
    
    this.saveNotificationSettings();
  },

  // 消息通知变更
  onMessageNotificationChange(e) {
    const enabled = e.detail.value;
    console.log('💬 消息通知变更:', enabled);
    
    this.setData({
      'notificationSettings.message.enabled': enabled
    });
    
    this.saveNotificationSettings();
  },

  // 消息预览变更
  onMessagePreviewChange(e) {
    const enabled = e.detail.value;
    console.log('👁️ 消息预览变更:', enabled);
    
    this.setData({
      'notificationSettings.message.showPreview': enabled
    });
    
    this.saveNotificationSettings();
  },

  // 消息提示音变更
  onMessageSoundChange(e) {
    const enabled = e.detail.value;
    console.log('🔊 消息提示音变更:', enabled);
    
    this.setData({
      'notificationSettings.message.sound': enabled
    });
    
    this.saveNotificationSettings();
  },

  // 消息震动变更
  onMessageVibrateChange(e) {
    const enabled = e.detail.value;
    console.log('📳 消息震动变更:', enabled);
    
    this.setData({
      'notificationSettings.message.vibrate': enabled
    });
    
    this.saveNotificationSettings();
  },

  // 消息分组变更
  onMessageGroupChange(e) {
    const enabled = e.detail.value;
    console.log('📂 消息分组变更:', enabled);
    
    this.setData({
      'notificationSettings.message.groupByChat': enabled
    });
    
    this.saveNotificationSettings();
  },

  // 群聊通知变更
  onGroupNotificationChange(e) {
    const enabled = e.detail.value;
    console.log('👥 群聊通知变更:', enabled);
    
    this.setData({
      'notificationSettings.group.enabled': enabled
    });
    
    this.saveNotificationSettings();
  },

  // 群聊仅@提醒变更
  onGroupMentionOnlyChange(e) {
    const enabled = e.detail.value;
    console.log('@ 群聊仅@提醒变更:', enabled);
    
    this.setData({
      'notificationSettings.group.mentionOnly': enabled
    });
    
    this.saveNotificationSettings();
  },

  // 群聊提示音变更
  onGroupSoundChange(e) {
    const enabled = e.detail.value;
    console.log('🔊 群聊提示音变更:', enabled);
    
    this.setData({
      'notificationSettings.group.sound': enabled
    });
    
    this.saveNotificationSettings();
  },

  // 群聊震动变更
  onGroupVibrateChange(e) {
    const enabled = e.detail.value;
    console.log('📳 群聊震动变更:', enabled);
    
    this.setData({
      'notificationSettings.group.vibrate': enabled
    });
    
    this.saveNotificationSettings();
  },

  // 好友通知变更
  onFriendNotificationChange(e) {
    const enabled = e.detail.value;
    console.log('👤 好友通知变更:', enabled);
    
    this.setData({
      'notificationSettings.friend.enabled': enabled
    });
    
    this.saveNotificationSettings();
  },

  // 好友提示音变更
  onFriendSoundChange(e) {
    const enabled = e.detail.value;
    console.log('🔊 好友提示音变更:', enabled);
    
    this.setData({
      'notificationSettings.friend.sound': enabled
    });
    
    this.saveNotificationSettings();
  },

  // 系统通知变更
  onSystemNotificationChange(e) {
    const enabled = e.detail.value;
    console.log('⚙️ 系统通知变更:', enabled);
    
    this.setData({
      'notificationSettings.system.enabled': enabled
    });
    
    this.saveNotificationSettings();
  },

  // 🔕 ===== 免打扰设置 =====

  // 免打扰模式变更
  onDoNotDisturbChange(e) {
    const enabled = e.detail.value;
    console.log('🔕 免打扰模式变更:', enabled);
    
    this.setData({
      'doNotDisturb.enabled': enabled
    });
    
    this.saveDoNotDisturbSettings();
  },

  // 选择开始时间
  selectStartTime() {
    console.log('⏰ 选择开始时间');
    
    this.setData({
      showTimePicker: true,
      selectedTime: this.data.doNotDisturb.startTime,
      timePickerType: 'start'
    });
  },

  // 选择结束时间
  selectEndTime() {
    console.log('⏰ 选择结束时间');
    
    this.setData({
      showTimePicker: true,
      selectedTime: this.data.doNotDisturb.endTime,
      timePickerType: 'end'
    });
  },

  // 时间选择变更
  onTimeChange(e) {
    const time = e.detail.value;
    console.log('⏰ 时间选择变更:', time, this.data.timePickerType);
    
    if (this.data.timePickerType === 'start') {
      this.setData({
        'doNotDisturb.startTime': time,
        showTimePicker: false
      });
    } else {
      this.setData({
        'doNotDisturb.endTime': time,
        showTimePicker: false
      });
    }
    
    this.saveDoNotDisturbSettings();
  },

  // 取消时间选择
  onTimeCancel() {
    this.setData({
      showTimePicker: false
    });
  },

  // 允许紧急通知变更
  onAllowUrgentChange(e) {
    const enabled = e.detail.value;
    console.log('🚨 允许紧急通知变更:', enabled);
    
    this.setData({
      'doNotDisturb.allowUrgent': enabled
    });
    
    this.saveDoNotDisturbSettings();
  },

  // 允许@提醒变更
  onAllowMentionsChange(e) {
    const enabled = e.detail.value;
    console.log('@ 允许@提醒变更:', enabled);
    
    this.setData({
      'doNotDisturb.allowMentions': enabled
    });
    
    this.saveDoNotDisturbSettings();
  },

  // 📋 ===== 通知管理 =====

  // 查看通知历史
  viewNotificationHistory() {
    console.log('📋 查看通知历史');
    
    wx.navigateTo({
      url: '/pages/settings/notification-history/notification-history'
    });
  },

  // 清空通知历史
  clearNotificationHistory() {
    console.log('🗑️ 清空通知历史');
    
    wx.showModal({
      title: '清空通知历史',
      content: '确定要删除所有通知记录吗？此操作不可恢复。',
      confirmText: '清空',
      confirmColor: '#FF3B30',
      success: (res) => {
        if (res.confirm) {
          this.performClearHistory();
        }
      }
    });
  },

  // 执行清空历史
  performClearHistory() {
    try {
      // 清空通知历史
      wx.removeStorageSync('notificationHistory');
      
      // 重置未读计数
      notificationManager.reset();
      
      this.setData({
        unreadCount: 0
      });
      
      wx.showToast({
        title: '历史已清空',
        icon: 'success'
      });
      
      console.log('✅ 通知历史清空完成');
      
    } catch (error) {
      console.error('❌ 清空通知历史失败:', error);
      wx.showToast({
        title: '清空失败',
        icon: 'none'
      });
    }
  },

  // 📱 ===== 订阅消息 =====

  // 请求订阅消息权限
  async requestSubscribeMessage() {
    console.log('📝 请求订阅消息权限');
    
    try {
      const templateIds = [
        'template_id_1', // 新消息通知
        'template_id_2', // 好友请求通知
        'template_id_3'  // 系统通知
      ];
      
      const result = await notificationManager.requestSubscribeMessage(templateIds);
      
      if (result) {
        wx.showToast({
          title: '权限设置完成',
          icon: 'success'
        });
      } else {
        wx.showToast({
          title: '权限设置失败',
          icon: 'none'
        });
      }
      
    } catch (error) {
      console.error('❌ 请求订阅消息权限失败:', error);
      wx.showToast({
        title: '权限设置失败',
        icon: 'none'
      });
    }
  },

  // 查看订阅状态
  viewSubscribeStatus() {
    console.log('📊 查看订阅状态');
    
    wx.showToast({
      title: '功能开发中',
      icon: 'none'
    });
  },

  // ⚙️ ===== 设置管理 =====

  // 保存通知设置
  saveNotificationSettings() {
    try {
      // 更新通知管理器设置
      notificationManager.updateNotificationSettings(this.data.notificationSettings);
      
      console.log('✅ 通知设置保存成功');
      
    } catch (error) {
      console.error('❌ 保存通知设置失败:', error);
    }
  },

  // 保存免打扰设置
  saveDoNotDisturbSettings() {
    try {
      wx.setStorageSync('doNotDisturbSettings', this.data.doNotDisturb);
      console.log('✅ 免打扰设置保存成功');
      
    } catch (error) {
      console.error('❌ 保存免打扰设置失败:', error);
    }
  },

  // 重置设置
  resetSettings() {
    console.log('🔄 重置设置');
    
    wx.showModal({
      title: '重置通知设置',
      content: '确定要将所有通知设置恢复为默认值吗？',
      confirmText: '重置',
      confirmColor: '#FF3B30',
      success: (res) => {
        if (res.confirm) {
          this.performResetSettings();
        }
      }
    });
  },

  // 执行重置设置
  performResetSettings() {
    try {
      // 重置为默认设置
      this.setData({
        notificationSettings: {
          enabled: true,
          message: {
            enabled: true,
            showPreview: true,
            sound: true,
            vibrate: true,
            groupByChat: true
          },
          group: {
            enabled: true,
            mentionOnly: false,
            sound: true,
            vibrate: true
          },
          friend: {
            enabled: true,
            sound: true
          },
          system: {
            enabled: true
          }
        },
        doNotDisturb: {
          enabled: false,
          startTime: '22:00',
          endTime: '08:00',
          allowUrgent: true,
          allowMentions: true
        }
      });
      
      // 保存设置
      this.saveNotificationSettings();
      this.saveDoNotDisturbSettings();
      
      wx.showToast({
        title: '设置已重置',
        icon: 'success'
      });
      
      console.log('✅ 通知设置重置完成');
      
    } catch (error) {
      console.error('❌ 重置通知设置失败:', error);
      wx.showToast({
        title: '重置失败',
        icon: 'none'
      });
    }
  },

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

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