// pages/personCenter/mine/mine.js
const { baseUrl } = require("../../../request");
const { globalImgUrl } = require("../../../request")
const { notLogin } = require('../../../utils/util')


Page({

  /**
   * 页面的初始数据
   */
  data: {
    nickName: "",
    userAvatar: "",
    phoneNumber: "",
    userAccount: "",
    invitationCode: "",
    showPopup: false,  // 控制弹窗显示与否
    isShowOrder: true,
    qrcode: "",  // 设置二维码图片的路径
    userRole: "",
    title: '查看绩效',
    id: 0,
    globalImgUrl,
    showNicknamePopup: false
  },
  // 跳转课程订单页面
  courseOrder() {
    wx.navigateTo({
      url: '/pages/course/courseOrderList/courseOrderList',
    })
  },
  updateAvatar(e) {
    const { avatarUrl } = e.detail 
    this.uploadAvatar(avatarUrl)
  },
  uploadAvatar(filePath) {
    wx.showLoading({ title: '上传中...' });
    wx.uploadFile({
      url: baseUrl + '/file/upload',
      filePath,
      name: 'file',     
      formData: {
        biz: 'default'
      },
      success: res => {
        wx.hideLoading();
        let result = JSON.parse(res.data);
        console.log(result)
        if (result.code === 1) {
          this.setData({userAvatar: result.data})
          this.updateUserInfo(result.data)
        } else {
          wx.showToast({
            title: result.message || '上传失败',
            icon: 'none'
          });
        }
      },
      fail: err => {
        wx.hideLoading();
        console.error('uploadFile fail', err);
        wx.showToast({ title: '网络错误，上传失败', icon: 'none' });
      }
    });
  },
  updateUserInfo(view) {
    const token = wx.getStorageSync('token')
    wx.request({
      url: baseUrl + '/userInfo/modify/avatar',
      method: 'POST',
      header: {
        Authorization: token
      },
      data: {
        templateString: view
      },
      success: res => {
        console.log(res.data)
      },
      fail: err => {
        wx.showToast({ title: '用户头像更新失败', icon: 'none' });
      }
    })
  },
  // 跳转结算记录页面
  gotoSettlementRecord() {
    wx.navigateTo({
      url: '/pages/course/courseSettlementRecord/courseSettlementRecord',
    })
  },

  // 点击二维码时，显示弹窗
  showPromoPopup() {
    this.setData({
      showPopup: true
    });
  },
  testOrigin() {
    console.log("testOrigin");
  },

  // 关闭弹窗
  closePopup() {
    this.setData({
      showPopup: false
    });
  },
  myteam(){
    wx.navigateTo({
      url: '/pages/personCenter/teamManage/teamManage',
    })
  },
  zhijin(){
    wx.navigateTo({
      url: '/pages/personCenter/billingDetails/billingDetails',
    })
  },
  mingxi(){
    wx.navigateTo({
      url: '/pages/personCenter/fundingDetails/fundingDetails',
    })
  },
  xiangmu(){
    wx.navigateTo({
      url: '/pages/projectModule/userProject/userProject',
    })
  },
  lxsj(){
    wx.navigateTo({
      url: '/pages/personCenter/contactSuper/contactSuper',
    })
  },
  zhshezhi(){
    wx.navigateTo({
      url: '/pages/personCenter/accountSetting/accountSetting',
    })
  },
  tixianzhanghu() {
    wx.navigateTo({
      url: '/pages/personCenter/withdrawalAccount/withdrawalAccount',
    })
  },
  lijitixian() {
    wx.navigateTo({
      url: '/pages/personCenter/withdrawal/withdrawal',
    })
  },
  szcy() {
    wx.navigateTo({
      url: '/pages/personCenter/commissionSetting/commissionSetting',
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
 getUserMainInfo() {
  const token = wx.getStorageSync('token');

  // 获取用户主要信息
  wx.request({
    url: baseUrl + '/userInfo/get/main/jwt',
    method: 'GET',
    header: {
      Authorization: token
    },
    success: res => {
      if (res.data.code === 1) {
        let result = res.data.data
        console.log('====fdfs>', res)  
        this.setData({
          qrcode: globalImgUrl + result.inviteQrCode
        })
      } else {
        notLogin(res.data.message)
      }
    },
    fail: () => {
      wx.showToast({ title: '网络错误，请重试', icon: 'none' });
    }
  })

  // 获取用户信息
  wx.request({
    url: baseUrl + '/userInfo/get/jwt',
    method: 'GET',
    header: {
      Authorization: token
    },
    success: res => {
      console.log('用户信息---->',res.data);
      if (res.data.code === 1) {
        let result = res.data.data
        this.setData({
          nickName: result.nickName,
          userAvatar: result.userAvatar,
          phoneNumber: result.phoneNumber,
          userAccount: result.userAccount,
          invitationCode: result.invitationCode,
          userRole: result.userRole,
          id: result.id,
        })
        console.log(result.userRole)
        if (result.userRole !== 'user') this.setData({ isShowOrder: false});
        if (result.userRole === 'staff') this.setData({title: '客户订单'});
      }
    }
  })
 },

  onLoad() {
    this.getUserMainInfo()
  },

  // 复制邀请码到剪贴板
  copyInvitationCode() {
    wx.setClipboardData({
      data: this.data.invitationCode,
      success() {
        wx.showToast({
          title: '复制成功',
          icon: 'success',
          duration: 1500
        });
      },
      fail() {
        wx.showToast({
          title: '复制失败',
          icon: 'error',
          duration: 1500
        });
      }
    });
  },

  // 跳转仪表盘
  gotoDashboard() {

    const { userRole } = this.data
    wx.navigateTo({
      url: `/pages/dashboardModule/overviewPerformance/overviewPerformance?role=${userRole}`,
    })
  },

  // 跳转查看绩效
  checkPerformance() {
    const { userRole } = this.data;
    const { id } = this.data;

    if (userRole === 'manager') {
      wx.navigateTo({
        url: `/pages/dashboardModule/supervisorPerformance/supervisorPerformance?role=${userRole}&id=${id}`,
       })
    } else if (userRole === 'staff') {
      wx.navigateTo({
        url: `/pages/dashboardModule/userOrderPerformance/userOrderPerformance?userId=${id}`,
      })
    } else {
      wx.navigateTo({
        url: `/pages/dashboardModule/staffPerformance/staffPerformance?role=${userRole}&supId=${id}`,
      })
    }
  }, 

  // 跳转主管排名
  gotoSupervisorRank(e) {
    console.log(e)
    const {userRole} = this.data
    console.log('===========>', userRole)
    if (userRole === 'staff') {
      wx.showToast({
        title: '无权限',
        icon: 'error'
      })
      return ;
    }
    wx.navigateTo({
      url: `/pages/dashboardModule/performanceRanking/performanceRanking?role=manager&k=1`,
    })
  },
  
    // 跳转员工排名
    gotoStaffRank(e) {
      console.log(e);
      const {userRole} = this.data
      console.log('===========>', userRole)
      if (userRole === 'user') {
        wx.showToast({
          title: '无权限',
          icon: 'error'
        })
        return ;
      }
      wx.navigateTo({
        url: `/pages/dashboardModule/performanceRanking/performanceRanking?role=staff&k=0`,
      })
    },


    openNicknamePopup() {
      this.setData({ showNicknamePopup: true });
    },
    closeNicknamePopup() {
      this.setData({ showNicknamePopup: false });
    },
    updateNickname(e) {
      const { nickname } = e.detail;
      const token = wx.getStorageSync('token');
      wx.request({
        url: baseUrl + '/userInfo/modify/nickname',
        method: 'POST',
        header: {
          Authorization: token
        },
        data: { templateString: nickname },
        success: res => {
          if (res.data.code === 1) {
            wx.showToast({ title: '修改成功', icon: 'success' });
            this.setData({ 
              nickName: nickname,
              showNicknamePopup: false
            });
          } else {
            wx.showToast({ title: res.data.message || '修改失败', icon: 'none' });
          }
        },
        fail: () => {
          wx.showToast({ title: '网络错误', icon: 'none' });
        }
      });
    },
    

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

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.getUserMainInfo()
  },
  gotoCall() {
    wx.makePhoneCall({
      phoneNumber: this.data.phoneNumber
    })
  },

})