// pages/user/index.js
const {
  serverName
} = require('../../utils/services');
const {
  newRequestFns,
  newServerName
} = require('../../utils/newServices.js');
const {
  Toast
} = require('../../utils/util.js');

// 添加默认头像
const defaultAvatarUrl = 'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0'

var app = getApp();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    testImg: '../../imgs/testImg/loginBg.png',
    avatar: '../../imgs/testImg/userIcon.png',
    
    // 新增的用户信息相关数据
    userInfo: {
      avatarUrl: defaultAvatarUrl,
      nickName: '',
    },
    hasUserInfo: false,
    canIUseGetUserProfile: wx.canIUse('getUserProfile'),
    canIUseNicknameComp: wx.canIUse('input.type.nickname'),

    likeImg: '../../imgs/icon/like.png',
    commentImg: '../../imgs/icon/comment.png',
    sawImg: '../../imgs/icon/saw.png', 
    tabItem: [{
      name: '待付款',
      tag: "0",
      id: 1
    }, {
      name: '待使用',
      tag: "-1",
      id: 2
    }, {
      name: '待评论',
      tag: "-1",
      id: 3
    }],

    tabList: [{
      name: '收藏',
      img: "../../imgs/icon/like.png",
      id: 0
    }, {
      name: '评论',
      img: "../../imgs/icon/comment.png",
      id: 1
    }, {
      name: '足迹',
      img: "../../imgs/icon/saw.png",
      id: 2
    }],

    active: false,
    isLogin: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    // 加载时初始化用户信息
    if(wx.getStorageSync('userInfo')){
      this.setData({
        userInfo: wx.getStorageSync('userInfo'),
        hasUserInfo: true
      })
    }
    // this.isLongPolling()
  },

  isLongPolling: function() {
    let loginSessionKey = wx.getStorageSync("token");

    let requestTask = wx.request({
      url: newServerName + '/wx/user/longPolling',
      data: {
        loginSessionKey
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      method: "post",
      success: (res) => {
        if (res.data.code == 0) {
          if (res.data.data) {
            let tabList = this.data.tabList;
            tabList[1].img = "../../imgs/icon/comment_active.png";
            this.setData({
              tabList
            })

          } else {
            let tabList = this.data.tabList;
            tabList[1].img = "../../imgs/icon/comment.png";
            this.setData({
              tabList
            })
          }
        } else {
          return
        }
        this.isLongPolling()
      }
    })

  },

  tapByIdx: function(e) {
    let {
      idx
    } = e.currentTarget.dataset;

    this._isLogin();

    if (this.data.isLogin) {
      switch (idx) {
        case 0:
          wx.navigateTo({
            url: './my_follow/index',
            success: function(res) {},
            fail: function(res) {},
            complete: function(res) {},
          })
          break;
        case 1:
          let tabList = this.data.tabList;
          tabList[1].img = "../../imgs/icon/comment.png";
          this.setData({
            tabList
          })
          wx.navigateTo({
            url: './my_comment/index',
            success: function(res) {},
            fail: function(res) {},
            complete: function(res) {},
          })
          break;
        case 2:
          wx.navigateTo({
            url: './my_saw/index',
            success: function(res) {},
            fail: function(res) {},
            complete: function(res) {},
          })
          break;
      }
    } else {
      Toast.showToast('tip', '请登录后查看', () => {

      });
    }


  },

  bindGetUserInfo: function(e) {
    console.log(e.detail.userInfo)
  },

  _myLikes: function() {
    this._isLogin();

    if (this.data.isLogin) {
      wx.navigateTo({
        url: './my_follow/index',
        success: function(res) {},
        fail: function(res) {},
        complete: function(res) {},
      })
    } else {
      Toast.showToast('tip', '请登录后查看', () => {

      });
    }

  },
  _myOrder: function() {
    this._isLogin();

    if (this.data.isLogin) {
      wx.navigateTo({
        url: './my_order/index',
        success: function(res) {},
        fail: function(res) {},
        complete: function(res) {},
      })
    } else {
      Toast.showToast('tip', '请登录后查看', () => {

      });
    }

  },

  _isLogin: function() {
    if (wx.getStorageSync('token')) {
      let loginSessionKey = wx.getStorageSync("token");
      if (loginSessionKey != " ") {
        wx.checkSession({
          success: res => {
            wx.request({
              url: newServerName + '/wx/user/checkLoginSessionKey',
              data: {
                loginSessionKey
              },
              header: {
                'content-type': 'application/x-www-form-urlencoded'
              },
              method: "post",
              success: (res) => {
                if (res.data.code == 0) {
                  this.setData({
                    isLogin: true
                  })
                  app.globalData.isLogin = true;
                  // app.globalData.cookieIDs = res.data.data.ids.split(',');

                } else {
                  this.setData({
                    isLogin: false,
                    avatarUrl: ""
                  })
                  app.globalData.isLogin = false;
                  
                }
              }
            })
            // request['checkLoginSessionKey']({
            //   loginSessionKey
            // }, "post", res => {
            //   if (res.data.code > -1) {
            //     this.setData({
            //       isLogin: true
            //     })
            //   } else {
            //     this.setData({
            //       isLogin: false
            //     })
            //   }
            // })
          },
          fail: res => {
            this.setData({
              isLogin: false,
              avatarUrl: ""

            })
            app.globalData.isLogin = false;
            
          }
        })
      } else {
        this.setData({
          isLogin: false,
          avatarUrl: ""
        })
        app.globalData.isLogin = false;

      }


    } else {
      this.setData({
        isLogin: false
      })
      app.globalData.isLogin = false;

    }
    // console.log("isLogin",this.data.isLogin);

  },

  getUserProfile:function(e){
    // 如果已经登录，直接返回
    if (this.data.isLogin) {
      return;
    }
    
    Toast.showToast2('loading');
     // 推荐使用wx.getUserProfile获取用户信息，开发者每次通过该接口获取用户个人信息均需用户确认
    // 开发者妥善保管用户快速填写的头像昵称，避免重复弹窗
    wx.getUserProfile({
      desc: '获取您的身份信息', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
      success: (res) => {
        console.log(123456,res);
        let {
          encryptedData,
          iv,
          userInfo
        } = res;
        
        // 更新用户信息到新的数据结构
        app.globalData.userInfo = userInfo;
        wx.setStorageSync("userInfo", userInfo)
        
        this.setData({
          userInfo: userInfo,
          hasUserInfo: true,
          avatarUrl: userInfo.avatarUrl,
          avatarName: userInfo.nickName
        })
        
        wx.login({
          success: res => {
            let {
              code
            } = res;

            console.log(789,res);

            if (code) {
              wx.request({
                url: newServerName + '/wx/user/getLoginSessionKey',
                data: {
                  encryptedData,
                  iv,
                  code,
                },
                header: {
                  'content-type': 'application/x-www-form-urlencoded'
                },
                method: 'post',
                // dataType: 'json',
                // responseType: 'text',
                success: res => {
                  if (res.data.code > -1) {
                    let {
                      loginSessionKey
                    } = res.data.data;
                    wx.setStorageSync('token', loginSessionKey)
                    
                    wx.showToast({
                      title: '登录成功',
                      icon: 'success'
                    })
                  }
                  else{
                    Toast.showToast('warn', '登录失败，请重试');
                  }
                },
                fail: res => {
                  Toast.showToast('warn', '登录失败，请重试');
                  
                },
                complete: res=> {
                  this._isLogin();
                  Toast.hideLoading();
                },
              })
            }
          }
        })
  
        // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
        // 所以此处加入 callback 以防止这种情况
        if (this.userInfoReadyCallback) {
          this.userInfoReadyCallback(res)
        }
      },
      fail: (res) => {
        // 用户取消授权时的处理逻辑
        console.log('用户取消授权:', res);
        
        // 仍然执行微信登录，但使用默认头像和昵称
        wx.login({
          success: loginRes => {
            let { code } = loginRes;
            console.log('静默登录 code:', code);

            if (code) {
              wx.request({
                url: newServerName + '/wx/user/getLoginSessionKey',
                data: {
                  code,
                  // 不传加密数据，只做基础登录
                },
                header: {
                  'content-type': 'application/x-www-form-urlencoded'
                },
                method: 'post',
                success: res => {
                  if (res.data.code > -1) {
                    let { loginSessionKey } = res.data.data;
                    wx.setStorageSync('token', loginSessionKey)
                    
                    // 设置默认用户信息
                    const defaultUserInfo = {
                      avatarUrl: defaultAvatarUrl,
                      nickName: '微信用户'
                    };
                    
                    app.globalData.userInfo = defaultUserInfo;
                    wx.setStorageSync("userInfo", defaultUserInfo);
                    
                    this.setData({
                      userInfo: defaultUserInfo,
                      hasUserInfo: true,
                      avatarUrl: defaultAvatarUrl,
                      avatarName: '微信用户'
                    });
                    
                    wx.showToast({
                      title: '登录成功',
                      icon: 'success'
                    });
                  } else {
                    Toast.showToast('warn', '登录失败，请重试');
                  }
                },
                fail: res => {
                  Toast.showToast('warn', '登录失败，请重试');
                },
                complete: res=> {
                  this._isLogin();
                  Toast.hideLoading();
                },
              })
            }
          },
          fail: () => {
            Toast.showToast('warn', '登录失败，请重试');
            Toast.hideLoading();
          }
        });
      },
      complete:(res)=>{
        Toast.hideLoading();
      }
    })
  },

  _logout: function() {

    if (this.data.isLogin) {
      wx.showModal({
        title: '提示',
        content: '确定要退出登录吗？',
        success: (res) => {
          if (res.confirm) {
            Toast.showToast2('loading');
            let loginSessionKey = wx.getStorageSync('token');
            newRequestFns["logout"]({
              loginSessionKey
            }, "post", res => {
              if (res.data.code > -1) {
                // 清除所有用户相关的存储信息
                wx.removeStorageSync('userInfo');
                wx.removeStorageSync('token');
                console.log(wx.getStorageSync('token'))
                
                // 重置页面状态到未登录
                this.setData({
                  isLogin: false,
                  avatarUrl: this.data.avatar,
                  avatarName: '登录',
                  userInfo: {
                    avatarUrl: defaultAvatarUrl,
                    nickName: '',
                  },
                  hasUserInfo: false
                })
                
                app.globalData.isLogin = false;
                app.globalData.userInfo = null;
                
                wx.showToast({
                  title: '已退出登录',
                  icon: 'success'
                });
              } else {
                Toast.showToast('warn', '退出失败，请重试');
              }

            }, err => {
              Toast.showToast('warn', '网络错误，请重试');
            }, complete => {
              Toast.hideLoading();
            })
          }
        }
      })
    } else {
      wx.showToast({
        title: '您还未登录',
        icon: 'none'
      });
    }

  },

  tapToOrderByidx: function(e) {
    let {
      status,
      id
    } = e.currentTarget.dataset;
    this._isLogin();
    if (this.data.isLogin) {
      wx.navigateTo({
        url: `./my_order/index?status=${status}&&id=${id}`,
        success: function(res) {},
        fail: function(res) {},
        complete: function(res) {},
      })
    } else {
      Toast.showToast('tip', '请登录后查看', () => {

      });
    }
    // url="./my_order/index?status={{item.tag}}&&id={{item.id}}"
  },


  clickCell: function() {
    wx.navigateTo({
      url: './my_contact/index',
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    let {
      avatar = ""
    } = this.data;
    console.log(wx.getStorageSync('userInfo'))
    
    // 获取存储的用户信息
    const storedUserInfo = wx.getStorageSync('userInfo');
    let avatarUrl = storedUserInfo ? storedUserInfo.avatarUrl : "";
    let avatarName = storedUserInfo ? storedUserInfo.nickName : "";

    // 更新用户信息到新的数据结构
    if (storedUserInfo) {
      this.setData({
        userInfo: storedUserInfo,
        hasUserInfo: true,
        avatarUrl: avatarUrl || avatar,
        avatarName: avatarName || '已登录'
      })
    } else {
      this.setData({
        avatarUrl: avatar,
        avatarName: '登录'
      })
    }
    
    this._isLogin()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  },

  // 新增：选择头像功能
  onChooseAvatar(e) {
    const { avatarUrl } = e.detail
    const { nickName } = this.data.userInfo
    
    // 更新页面数据
    this.setData({
      "userInfo.avatarUrl": avatarUrl,
      hasUserInfo: true,
      avatarUrl: avatarUrl
    })
    
    // 更新本地存储和全局数据
    const updatedUserInfo = {
      ...this.data.userInfo,
      avatarUrl: avatarUrl,
      realUserInfo: true
    }
    
    wx.setStorageSync('userInfo', updatedUserInfo)
    if (app && app.globalData) {
      app.globalData.userInfo = updatedUserInfo
    }
    
    console.log('头像已更新:', avatarUrl)
    
    wx.showToast({
      title: '头像已更新',
      icon: 'success'
    })
  },

  // 新增：输入昵称功能
  onInputChange(e) {
    const nickName = e.detail.value
    const { avatarUrl } = this.data.userInfo
    
    // 更新页面数据
    this.setData({
      "userInfo.nickName": nickName || '微信用户',
      hasUserInfo: true,
      avatarName: nickName
    })
    
    // 更新本地存储和全局数据
    const updatedUserInfo = {
      ...this.data.userInfo,
      nickName: nickName,
      realUserInfo: true
    }
    
    wx.setStorageSync('userInfo', updatedUserInfo)
    if (app && app.globalData) {
      app.globalData.userInfo = updatedUserInfo
    }
    
    console.log('昵称已更新:', nickName)
  },

  // 新增：处理已登录状态下点击头像的逻辑
  handleAvatarClick() {
    if (this.data.canIUseNicknameComp) {
      wx.showToast({
        title: '请点击头像更换',
        icon: 'none'
      })
    } else {
      // 降级处理，重新获取用户信息
      this.getUserProfile()
    }
  },
})