// pages/xiugai/xiugai.js
const app = getApp()
import upload from '../../utils/upload.js'

Page({
  data: {
    avatarUrl: '',
    uid: '',
    nicheng: '',
    phone: '',
    originalAvatar: '',
    originalNicheng: '',
    isSaving: false,
    hasChanges: false,
    newAvatarFile: null,
    isLoading: true,
    isAvatarActive: false,
    nicknameError: ''
  },

  onLoad() {
    wx.setNavigationBarTitle({ title: '编辑资料' })
    this.loadUserData()
  },

  onShow() {
    this.registerNotificationComponent();
  },

  registerNotificationComponent() {
    const notificationComp = this.selectComponent('#global-notification');
    if (notificationComp && notificationComp.showNotification) {
      app.globalData.globalNotification = {
        show: (data) => notificationComp.showNotification(data),
        hide: () => notificationComp.hideNotification()
      };
    }
  },

  // 加载用户数据（手机号只读，不参与修改逻辑）
  loadUserData() {
    try {
      const uid = wx.getStorageSync('uid') || ''
      const nicheng = wx.getStorageSync('nicheng') || ''
      const phone = wx.getStorageSync('phone') || ''
      const touxiang = wx.getStorageSync('touxiang') || ''
      
      const ossImageUrl = app.globalData.ossImageUrl || ''
      const defaultAvatar = app.globalData.morentouxiang || ''
      
      let avatarUrl = ''
      if (touxiang) {
        avatarUrl = touxiang.startsWith('http') ? touxiang : `${ossImageUrl}${touxiang}`
      } else if (defaultAvatar) {
        avatarUrl = defaultAvatar.startsWith('http') ? defaultAvatar : `${ossImageUrl}${defaultAvatar}`
      }
      
      this.setData({
        avatarUrl,
        uid,
        nicheng,
        phone,                   // 仅展示
        originalAvatar: touxiang,
        originalNicheng: nicheng,
        isLoading: false
      })
    } catch (error) {
      console.error('加载用户数据失败:', error)
      this.setData({ isLoading: false })
      wx.showToast({ title: '加载数据失败', icon: 'none' })
    }
  },

  // 微信头像选择（未改动）
  onChooseAvatar(e) {
    const avatarTempPath = e.detail.avatarUrl
    this.setData({
      avatarUrl: avatarTempPath,
      newAvatarFile: avatarTempPath
    }, () => {
      this.checkChanges()
    })
  },

  chooseAvatar() {
    // 仅保留动画效果（透明按钮已触发 onChooseAvatar）
    this.setData({ isAvatarActive: true })
    setTimeout(() => {
      this.setData({ isAvatarActive: false })
    }, 500)
  },

  // 昵称输入（未改动）
  onNicknameInput(e) {
    const value = e.detail.value.trim()
    this.setData({
      nicheng: value,
      nicknameError: ''
    }, () => {
      this.checkChanges()
    })
  },

  // 检查变化（只比较昵称和头像）
  checkChanges() {
    const { originalNicheng, nicheng, newAvatarFile } = this.data;
    const hasChanges = (nicheng !== originalNicheng) || (newAvatarFile !== null);
    this.setData({ hasChanges });
  },

  // 保存（不包含手机号逻辑）
  async onSave() {
    if (!this.data.hasChanges) {
      wx.showToast({ title: '没有需要保存的更改', icon: 'none' });
      return;
    }
    if (this.data.isSaving) return;
    
    // 验证数据（昵称）
    if (!this.validateData()) return;
    
    this.setData({ isSaving: true });
    wx.showLoading({ title: '保存中...', mask: true });
    
    try {
      const formData = {};
      if (this.data.nicheng !== this.data.originalNicheng) {
        formData.nicheng = this.data.nicheng;
      }
      
      const res = await upload({
        url: '/yonghu/xiugai',
        formData,
        filePath: this.data.newAvatarFile,
        fileName: 'avatar'
      });
      
      if (res.statusCode === 200 && res.data) {
        const response = res.data;
        if (response.code === 0) {
          await this.handleUpdateSuccess(response.data);
        } else {
          throw new Error(response.msg || '保存失败');
        }
      } else {
        throw new Error('网络错误');
      }
    } catch (error) {
      console.error('保存失败:', error);
      if (error.message.includes('认证失败') || error.message.includes('401')) {
        wx.showModal({
          title: '提示',
          content: '登录已过期，请重新登录',
          complete: (res) => {
            if (res.confirm) {
              wx.removeStorageSync('token');
              wx.removeStorageSync('userInfo');
              wx.switchTab({ url: '/pages/wode/wode' });
            }
          }
        });
      } else {
        wx.showToast({ title: error.message || '保存失败', icon: 'none' });
      }
    } finally {
      wx.hideLoading();
      this.setData({ isSaving: false });
    }
  },

  // 验证数据（只验证昵称）
  validateData() {
    const { nicheng } = this.data;
    let hasError = false;
    this.setData({ nicknameError: '' });
    
    if (nicheng && nicheng.length > 20) {
      this.setData({ nicknameError: '昵称不能超过20个字符' });
      hasError = true;
    }
    if (nicheng !== this.data.originalNicheng && nicheng.trim() === '') {
      this.setData({ nicknameError: '昵称不能为空' });
      hasError = true;
    }
    if (hasError) {
      if (this.data.nicknameError) {
        wx.showToast({ title: this.data.nicknameError, icon: 'none' });
      }
      return false;
    }
    return true;
  },

  // 更新成功处理（不再处理手机号）
  async handleUpdateSuccess(updateData) {
    if (updateData.touxiang !== undefined && updateData.touxiang !== null) {
      wx.setStorageSync('touxiang', updateData.touxiang);
    }
    if (updateData.nicheng !== undefined && updateData.nicheng !== null) {
      wx.setStorageSync('nicheng', updateData.nicheng);
    }
    
    if (updateData.nicheng) {
      app.globalData.userNicheng = updateData.nicheng;
    }
    
    const ossImageUrl = app.globalData.ossImageUrl || '';
    let avatarUrl = this.data.avatarUrl;
    if (updateData.touxiang) {
      avatarUrl = updateData.touxiang.startsWith('http') ? 
        updateData.touxiang : `${ossImageUrl}${updateData.touxiang}`;
    }
    
    this.setData({
      avatarUrl,
      originalAvatar: updateData.touxiang || this.data.originalAvatar,
      originalNicheng: updateData.nicheng || this.data.originalNicheng,
      newAvatarFile: null,
      hasChanges: false
    });
    
    wx.showToast({
      title: '保存成功',
      icon: 'success',
      duration: 2000
    });
  }
});