// index.js
const defaultAvatarUrl = 'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0'
const app = getApp();
Page({
  data: {
    motto: 'Hello World',
    userInfo: {
      avatarUrl: defaultAvatarUrl,
      nickName: '',
    },
    hasUserInfo: false,
    canIUseGetUserProfile: wx.canIUse('getUserProfile'),
    canIUseNicknameComp: wx.canIUse('input.type.nickname'),
    isLoggedIn: false,
  },
  onLoad() {
    if(wx.getStorageSync('userInfo')){
      this.setData({
        userInfo: wx.getStorageSync('userInfo'),
        hasUserInfo: true
      })
    }
    this.checkLoginStatus();
  },

  onShow() {
    // 同步底部导航高亮
    if (typeof this.getTabBar === 'function' && this.getTabBar()) {
      this.getTabBar().setData({
        selected: 4,
        isShowTabar: true
      })
    }
    // 每次显示页面时检查登录状态
    this.checkLoginStatus();
  },

  bindViewTap() {
    wx.navigateTo({
      url: '../logs/logs'
    })
  },
  onChooseAvatar(e) {
    const { avatarUrl } = e.detail
    const { nickName } = this.data.userInfo
    
    // 更新页面数据
    this.setData({
      "userInfo.avatarUrl": avatarUrl,
      hasUserInfo: nickName && avatarUrl && avatarUrl !== defaultAvatarUrl,
      hasUserInfo: true
    })
    
    // 更新本地存储和全局数据
    const updatedUserInfo = {
      ...this.data.userInfo,
      avatarUrl: avatarUrl,
      realUserInfo: true
    }
    
    wx.setStorageSync('userInfo', updatedUserInfo)
    if (app && app.globalData) {
      app.globalData.userInfo = updatedUserInfo
    }
    
    console.log('头像已更新:', avatarUrl)
  },
  onInputChange(e) {
    const nickName = e.detail.value
    const { avatarUrl } = this.data.userInfo
    
    // 更新页面数据
    this.setData({
      "userInfo.nickName": nickName,
      hasUserInfo: nickName && avatarUrl && avatarUrl !== defaultAvatarUrl,
      hasUserInfo: true
    })
    
    // 更新本地存储和全局数据
    const updatedUserInfo = {
      ...this.data.userInfo,
      nickName: nickName,
      realUserInfo: true
    }
    
    wx.setStorageSync('userInfo', updatedUserInfo)
    if (app && app.globalData) {
      app.globalData.userInfo = updatedUserInfo
    }
    
    console.log('昵称已更新:', nickName)
  },
  getUserProfile(e) {
    // 推荐使用wx.getUserProfile获取用户信息，开发者每次通过该接口获取用户个人信息均需用户确认，开发者妥善保管用户快速填写的头像昵称，避免重复弹窗
    wx.getUserProfile({
      desc: '展示用户信息', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
      success: (res) => {
        console.log(res)
        this.setData({
          userInfo: res.userInfo,
          hasUserInfo: true
        })
      }
    })
  },
  // 跳转到我的参观人页面
  goToUserList() {
    if (!this.data.isLoggedIn) {
      this.startLogin();
      return;
    }
    wx.navigateTo({
      url: '/pages/user/userList/index'
    })
  },

  // 跳转到我的预约
  startPreview() {
    if (!this.data.isLoggedIn) {
      this.startLogin();
      return;
    }
    console.log(11111)
    wx.navigateTo({
      url: '/pages/user/my-preview/index'
    })
  },

  // 意见反馈
  goToFeedback() {
    if (!this.data.isLoggedIn) {
      this.startLogin();
      return;
    }
    wx.navigateTo({
      url: '/pages/user/feedback/index'
    });
  },

  // 退出登录
  logout() {
    const token = wx.getStorageSync('token');
    if (!token) {
      wx.showToast({
        title: '您还未登录',
        icon: 'none'
      });
      return;
    }
    
    wx.showModal({
      title: '提示',
      content: '确定要退出登录吗？',
      success: (res) => {
        if (res.confirm) {
          // 清除本地存储的token和用户信息
          wx.removeStorageSync('token');
          wx.removeStorageSync('userInfo');
          if (app && app.globalData) {
            app.globalData.token = null;
            app.globalData.userInfo = null;
          }
          
          // 调用app的logout方法统一处理退出登录
          if (app && app.logout) {
            app.logout();
          }
          
          // 清除页面用户信息，设置为未登录状态
          this.setData({
            userInfo: {
              avatarUrl: defaultAvatarUrl,
              nickName: '',
            },
            hasUserInfo: false,
            isLoggedIn: false,
          });
          
          wx.showToast({
            title: '已退出登录',
            icon: 'success',
            duration: 1500
          });
          
          // // 延迟跳转到首页
          // setTimeout(() => {
          //   wx.switchTab({
          //     url: '/pages/index/index'
          //   });
          // }, 1500);
        }
      }
    });
  },
  startLogin() {
    // 触发自动登录
    wx.showModal({
      title: '登录授权',
      content: '为了给您提供更好的服务，需要获取您的微信登录信息，是否同意？',
      confirmText: '同意',
      cancelText: '暂不',
      success: (res) => {
        if (res.confirm) {
          if (app && app.wxLogin) {
            wx.showToast({
              title: '正在登录',
              icon: 'none',
              duration: 1000
            });
            app.wxLogin();
            this.setData({
              userInfo: {
                avatarUrl: defaultAvatarUrl,
                nickName: '微信用户',
              },
              hasUserInfo: true,
            });
          }
        } else {
          // 用户拒绝，保持未登录状态
          console.log('用户拒绝登录授权，保持未登录状态')
          this.globalData.isGuest = true
        }
      }
    })
  },

  /**
   * 检查登录状态
   */
  checkLoginStatus() {
    const app = getApp();
    const token = wx.getStorageSync('token');
    const isLoggedIn = !!(token && !app.globalData.isGuest);
    
    this.setData({
      isLoggedIn: isLoggedIn
    });
  }
})
