// 🎨 聊天设置页面逻辑
const app = getApp();

Page({
  data: {
    // 系统信息
    statusBarHeight: 44,
    navBarHeight: 88,
    
    // 当前设置
    currentBackground: 'default',
    fontSize: 'medium',
    showTimestamp: true,
    showReadStatus: true,
    bubbleStyle: 'classic',
    bubbleStyleName: '经典样式',
    enableReactions: true,
    burnAfterReading: false,
    endToEndEncryption: false,
    
    // 预设背景
    presetBackgrounds: [
      {
        id: 'gradient1',
        name: '渐变蓝',
        thumbnail: '/images/backgrounds/gradient1-thumb.jpg',
        url: '/images/backgrounds/gradient1.jpg'
      },
      {
        id: 'gradient2',
        name: '渐变紫',
        thumbnail: '/images/backgrounds/gradient2-thumb.jpg',
        url: '/images/backgrounds/gradient2.jpg'
      },
      {
        id: 'nature1',
        name: '自然风光',
        thumbnail: '/images/backgrounds/nature1-thumb.jpg',
        url: '/images/backgrounds/nature1.jpg'
      },
      {
        id: 'abstract1',
        name: '抽象艺术',
        thumbnail: '/images/backgrounds/abstract1-thumb.jpg',
        url: '/images/backgrounds/abstract1.jpg'
      }
    ],
    
    // 气泡样式选项
    bubbleStyles: [
      {
        id: 'classic',
        name: '经典样式',
        class: 'classic'
      },
      {
        id: 'modern',
        name: '现代样式',
        class: 'modern'
      },
      {
        id: 'minimal',
        name: '简约样式',
        class: 'minimal'
      }
    ],
    
    // 弹窗状态
    showBubbleModal: false
  },

  onLoad(options) {
    console.log('🎨 聊天设置页面加载');
    
    // 获取系统信息
    this.getSystemInfo();
    
    // 加载用户设置
    this.loadUserSettings();
  },

  onShow() {
    console.log('🎨 聊天设置页面显示');
  },

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

  // 加载用户设置
  loadUserSettings() {
    try {
      const settings = wx.getStorageSync('chatSettings') || {};
      
      this.setData({
        currentBackground: settings.background || 'default',
        fontSize: settings.fontSize || 'medium',
        showTimestamp: settings.showTimestamp !== false,
        showReadStatus: settings.showReadStatus !== false,
        bubbleStyle: settings.bubbleStyle || 'classic',
        enableReactions: settings.enableReactions !== false,
        burnAfterReading: settings.burnAfterReading || false,
        endToEndEncryption: settings.endToEndEncryption || false
      });
      
      // 更新气泡样式名称
      this.updateBubbleStyleName();
      
      console.log('✅ 用户设置加载完成');
      
    } catch (error) {
      console.error('❌ 加载用户设置失败:', error);
    }
  },

  // 🎨 ===== 背景设置 =====

  // 选择背景
  selectBackground(e) {
    const type = e.currentTarget.dataset.type;
    const id = e.currentTarget.dataset.id;
    
    console.log('🎨 选择背景:', type, id);
    
    let backgroundId = type;
    if (type === 'preset') {
      backgroundId = id;
    }
    
    this.setData({
      currentBackground: backgroundId
    });
    
    // 立即应用背景
    this.applyBackground(backgroundId);
  },

  // 选择自定义背景
  selectCustomBackground() {
    console.log('🎨 选择自定义背景');
    
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        const tempFilePath = res.tempFilePaths[0];
        
        // 保存自定义背景
        this.saveCustomBackground(tempFilePath);
      },
      fail: (error) => {
        console.error('❌ 选择图片失败:', error);
        wx.showToast({
          title: '选择图片失败',
          icon: 'none'
        });
      }
    });
  },

  // 保存自定义背景
  async saveCustomBackground(tempFilePath) {
    try {
      wx.showLoading({
        title: '设置背景中...'
      });
      
      // 保存图片到本地
      const savedFilePath = await new Promise((resolve, reject) => {
        wx.saveFile({
          tempFilePath: tempFilePath,
          success: (res) => resolve(res.savedFilePath),
          fail: reject
        });
      });
      
      // 更新设置
      this.setData({
        currentBackground: 'custom'
      });
      
      // 保存自定义背景路径
      wx.setStorageSync('customBackground', savedFilePath);
      
      // 应用背景
      this.applyBackground('custom');
      
      wx.hideLoading();
      wx.showToast({
        title: '背景设置成功',
        icon: 'success'
      });
      
    } catch (error) {
      wx.hideLoading();
      console.error('❌ 保存自定义背景失败:', error);
      wx.showToast({
        title: '设置背景失败',
        icon: 'none'
      });
    }
  },

  // 应用背景
  applyBackground(backgroundId) {
    try {
      let backgroundUrl = '';
      
      if (backgroundId === 'default') {
        backgroundUrl = '';
      } else if (backgroundId === 'custom') {
        backgroundUrl = wx.getStorageSync('customBackground') || '';
      } else {
        // 预设背景
        const preset = this.data.presetBackgrounds.find(bg => bg.id === backgroundId);
        if (preset) {
          backgroundUrl = preset.url;
        }
      }
      
      // 保存到全局状态
      app.globalData.chatBackground = {
        id: backgroundId,
        url: backgroundUrl
      };
      
      console.log('✅ 背景应用成功:', backgroundId);
      
    } catch (error) {
      console.error('❌ 应用背景失败:', error);
    }
  },

  // 🔤 ===== 字体设置 =====

  // 选择字体大小
  selectFontSize(e) {
    const size = e.currentTarget.dataset.size;
    console.log('🔤 选择字体大小:', size);
    
    this.setData({
      fontSize: size
    });
    
    // 立即应用字体大小
    this.applyFontSize(size);
  },

  // 应用字体大小
  applyFontSize(size) {
    try {
      // 保存到全局状态
      app.globalData.fontSize = size;
      
      console.log('✅ 字体大小应用成功:', size);
      
    } catch (error) {
      console.error('❌ 应用字体大小失败:', error);
    }
  },

  // ⚙️ ===== 消息设置 =====

  // 时间戳设置变化
  onTimestampChange(e) {
    const checked = e.detail.value;
    console.log('⚙️ 时间戳设置变化:', checked);
    
    this.setData({
      showTimestamp: checked
    });
  },

  // 已读状态设置变化
  onReadStatusChange(e) {
    const checked = e.detail.value;
    console.log('⚙️ 已读状态设置变化:', checked);
    
    this.setData({
      showReadStatus: checked
    });
  },

  // 显示气泡样式选项
  showBubbleStyleOptions() {
    console.log('🎨 显示气泡样式选项');
    
    this.setData({
      showBubbleModal: true
    });
  },

  // 关闭气泡样式弹窗
  closeBubbleModal() {
    this.setData({
      showBubbleModal: false
    });
  },

  // 选择气泡样式
  selectBubbleStyle(e) {
    const styleId = e.currentTarget.dataset.id;
    console.log('🎨 选择气泡样式:', styleId);
    
    this.setData({
      bubbleStyle: styleId
    });
    
    this.updateBubbleStyleName();
    this.closeBubbleModal();
  },

  // 更新气泡样式名称
  updateBubbleStyleName() {
    const style = this.data.bubbleStyles.find(s => s.id === this.data.bubbleStyle);
    if (style) {
      this.setData({
        bubbleStyleName: style.name
      });
    }
  },

  // 表情回应设置变化
  onReactionsChange(e) {
    const checked = e.detail.value;
    console.log('⚙️ 表情回应设置变化:', checked);
    
    this.setData({
      enableReactions: checked
    });
  },

  // 🔒 ===== 隐私设置 =====

  // 阅后即焚设置变化
  onBurnAfterReadingChange(e) {
    const checked = e.detail.value;
    console.log('🔒 阅后即焚设置变化:', checked);
    
    this.setData({
      burnAfterReading: checked
    });
  },

  // 加密设置变化
  onEncryptionChange(e) {
    const checked = e.detail.value;
    console.log('🔒 加密设置变化:', checked);
    
    this.setData({
      endToEndEncryption: checked
    });
  },

  // 💾 ===== 设置保存 =====

  // 保存设置
  saveSettings() {
    console.log('💾 保存设置');
    
    try {
      const settings = {
        background: this.data.currentBackground,
        fontSize: this.data.fontSize,
        showTimestamp: this.data.showTimestamp,
        showReadStatus: this.data.showReadStatus,
        bubbleStyle: this.data.bubbleStyle,
        enableReactions: this.data.enableReactions,
        burnAfterReading: this.data.burnAfterReading,
        endToEndEncryption: this.data.endToEndEncryption
      };
      
      // 保存到本地存储
      wx.setStorageSync('chatSettings', settings);
      
      // 应用到全局状态
      app.globalData.chatSettings = settings;
      
      wx.showToast({
        title: '设置保存成功',
        icon: 'success'
      });
      
      console.log('✅ 设置保存成功');
      
    } catch (error) {
      console.error('❌ 保存设置失败:', error);
      wx.showToast({
        title: '保存失败',
        icon: 'none'
      });
    }
  },

  // 恢复默认设置
  resetSettings() {
    console.log('🔄 恢复默认设置');
    
    wx.showModal({
      title: '恢复默认设置',
      content: '确定要恢复所有设置到默认值吗？',
      success: (res) => {
        if (res.confirm) {
          this.performReset();
        }
      }
    });
  },

  // 执行重置
  performReset() {
    try {
      // 重置所有设置
      this.setData({
        currentBackground: 'default',
        fontSize: 'medium',
        showTimestamp: true,
        showReadStatus: true,
        bubbleStyle: 'classic',
        enableReactions: true,
        burnAfterReading: false,
        endToEndEncryption: false
      });
      
      this.updateBubbleStyleName();
      
      // 清除本地存储
      wx.removeStorageSync('chatSettings');
      wx.removeStorageSync('customBackground');
      
      // 重置全局状态
      app.globalData.chatSettings = {};
      app.globalData.chatBackground = {};
      app.globalData.fontSize = 'medium';
      
      wx.showToast({
        title: '已恢复默认设置',
        icon: 'success'
      });
      
      console.log('✅ 默认设置恢复成功');
      
    } catch (error) {
      console.error('❌ 恢复默认设置失败:', error);
      wx.showToast({
        title: '恢复失败',
        icon: 'none'
      });
    }
  },

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

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

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