//const app = require('../../js/api');
import api from '../../js/api'
// pages/login/login.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    userInfo: {}
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {

  },

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

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

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

  },

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

  },

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

  },

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

  },

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

  },

  pay() {
    api.request_wechatPay(23)
      .then(res => {
        wx.requestPayment({
          timeStamp: res.data.data.unifiedOrderResult.timeStamp,
          nonceStr: res.data.data.unifiedOrderResult.nonceStr,
          package: res.data.data.unifiedOrderResult.package,
          signType: res.data.data.unifiedOrderResult.signType,
          paySign: res.data.data.unifiedOrderResult.paySign,
          success: res => {
            wx.hideLoading()
            wx.showToast({
              title: '支付成功！',
            })
            setTimeout(function () {
              wx.switchTab({
                url: '../index/index',
              })
            }, 2000)

          },
          fail: res => {
            wx.hideLoading()
            wx.showModal({
              title: '支付失败',
              content: res.errMsg + '请稍后再试',
              showCancel: false,
              success(res) {
                if (res.confirm) {
                  wx.switchTab({
                    url: '../home/home',
                  })
                }
              }
            })
          }
        })
      });
  },
  RefundTrx: function (e) {
    var RefundTrx = {
      trxId: 31,
      longitude: 116.4074,
      latitude: 39.9042
    };
    api.request_RefundTrx(RefundTrx)
      .then(res => {
        debugger
      });
  },
  handleGetPhoneNumber: function (e) {
    if (e.detail.errMsg === 'getPhoneNumber:ok') {
      // 用户同意授权，获取加密数据
      const encryptedData = e.detail.encryptedData;
      const iv = e.detail.iv;
      debugger
      // 调用后端接口进行解密
      wx.request({
        url: 'https://your-backend-api-endpoint.com/decryptPhoneNumber', // 替换为你的后端API地址
        method: 'POST',
        data: {
          encryptedData: encryptedData,
          iv: iv,
          sessionKey: 'your-session-key' // 替换为实际的session_key
        },
        success(res) {
          console.log('解密后的手机号:', res.data);
        },
        fail(err) {
          console.error('解密失败:', err);
        }
      });
    } else {
      console.log('用户拒绝授权');
    }
  },
  subMessage() {
    wx.requestSubscribeMessage({
      tmplIds: ['ldkKXfnHj-uKo6SBep08f_kaSjtxMOccJywHOEgxyPg'], // 最多支持3条
      success(res) {
        // 'accept'表示用户同意订阅该条id对应的模板消息
        if (res['ldkKXfnHj-uKo6SBep08f_kaSjtxMOccJywHOEgxyPg'] === 'accept') {
          // 用户同意订阅，调用云函数或服务器接口发送订阅消息
          wx.cloud.callFunction({
            name: 'sendSubscribeMessage',
            data: {
              templateId: '配置好的模板ID',
              openid: 'o8pFb5fB9YROMFirFYrVNE3lr4ak',
              data: {
                thing1: {
                  value: '活动名称'
                },
                // 其他参数...
              }
            },
            success(res) {
              console.log('订阅消息发送成功', res)
            },
            fail(err) {
              console.error('订阅消息发送失败', err)
            }
          })
        }
      }
    })
  },

  handleAuthLogin(e) {
    console.log('一键授权登录按钮被点击', e);
    wx.showLoading({
      title: '正在登录中...',
    })

    if (e.type == "getphonenumber") {
      console.log("添加手机信息", this.data.userInfo)
      var user = {
        UserName: this.data.userInfo.UserName,
        UserAvatarUrl: this.data.userInfo.UserAvatarUrl,
        UserPhoneNumber: '',
        Address: '',
        encryptedData: e.detail.encryptedData,
        iv: e.detail.iv
      };
      this.setData({
        userInfo: user
      })
      this.toLogin()
    }

    if (e.type == "tap") {
      console.log("添加用户信息", this.data.userInfo)
      // 获取用户信息授权
      const that = this;
      wx.getUserProfile({
        desc: '用于完善用户资料', // 声明获取用户信息的目的
        success(res) {
          console.log('用户信息:', res.userInfo);
          var user = {
            UserName: res.userInfo.nickName,
            // UserName: "测试",
            UserAvatarUrl: res.userInfo.avatarUrl,
            UserPhoneNumber: '',
            Address: '',
            encryptedData: that.data.userInfo.encryptedData,
            iv: that.data.userInfo.iv
          };
          that.setData({
            userInfo: user
          })
          that.toLogin()
          // 将用户信息发送到服务器
          // 例如：wx.request({ url: 'https://example.com/userInfo', data: res.userInfo })
        },
        fail(err) {
          console.error('获取用户信息失败:', err);
          wx.hideLoading()
        },
      });
    }

  },

  toLogin() {
    if (!this.cheackUserInfo()) {
      console.log("userInfo 信息不全", this.data.userInfo)
      wx.hideLoading()
      return
    }
    // 调用微信登录接口
    var that = this;
    wx.login({
      success(res) {
        if (res.code) {
          console.log('登录成功，code:', res.code);
          api.request_Wechatlogin(res.code)
            .then(res => {
              console.log("获取wid", res.data.data)
              wx.setStorageSync('WachatID', res.data.data)
              console.log("传递的userInfo", that.data.userInfo)
              return api.request_AddMiniprogramUser(that.data.userInfo)
            }).then(res => {
              console.log("添加user", res)
              return api.request_GetSiteInfo();
            }).then(res => {
              console.log("站点信息", res)
              wx.hideLoading()
              wx.navigateBack();
            }).catch(err => {
              console.log("报错", res)
              wx.hideLoading()
            });
        } else {
          wx.hideLoading()
          console.log('登录失败:', res.errMsg);
        }
      },
      fail(err) {
        wx.hideLoading()
        console.error('登录接口调用失败:', err);
      },
    });
  },

  cheackUserInfo() {
    var userInfo = this.data.userInfo;
    return userInfo.UserAvatarUrl != '' && userInfo.UserAvatarUrl != undefined && userInfo.UserName != '' && userInfo.UserName != undefined && userInfo.encryptedData != '' && userInfo.encryptedData != undefined && userInfo.iv != '' && userInfo.iv != undefined
  }
})