// logs.js
const util = require('../../utils/util.js')

Page({
  data: {
    showAuthorizedDialog: false,
    hasAuth: false,
    activeIcon: "/subpages/icons/ic_selected_radio.svg",
    normalIcon: "/subpages/icons/ic_radio.svg",
    logs: [],
    checkedPrivacy: false,
    canGetPhoneNumber: false,
  },
  onSaveExitState: function () {
    wx.clearStorage();
    console.log("onSaveExitState=");
    // 返回保存的数据和超时时间（可选）  
    return {
      expireTimeStamp: Date.now() + 24 * 60 * 60 * 1000 // 超时时间戳，例如设置为1天后过期  
    };
  },
  onChangePrivacy(event) {
    const check = event.detail;

    this.setData({
      checkedPrivacy: check
    });
  },
  //扫码
  tapScan() {
    if (!this.data.hasAuth) {
      this.showDialog();
      return;
    }
    if (!this.data.checkedPrivacy) {
      wx.showToast({
        title: '请先阅读并同意《舒眠大健康用户服务协议》和《舒眠大健康隐私保护政策》',
        icon: 'none',
        duration: 2000
      })
      return;
    }
    wx.scanCode({
      success: function (res) {
        console.log('扫码获取的参数', res);
        wx.clearStorage();
        wx.setStorageSync('res', res);
        wx.setStorageSync('scanResultExpiresAt', Date.now() + 2 * 60 * 60 * 1000); // 超时时间戳，例如设置为2小时后过期
        wx.reLaunch({
          url: '/pages/index/index?res=' + res,//传res
        })
      }
    })
  },
  onLoad() {
    console.log("scan页面");
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    const app = getApp();
    app.globalData.selectedTabIndex = 4;
    this.getTabBar().setData({
      selected: 4
    })

    this.checkAuth()
  },
  showDialog() {
    this.setData({
      showAuthorizedDialog: true
    })
  },
  checkAuth() {
    var hasAuth = wx.getStorageSync("hasAuth");
    this.setData({
      hasAuth: hasAuth
    })
    // if (hasAuth) {
    //   var userInfo = wx.getStorageSync("userInfo");
    //   this.setData({
    //     userName: userInfo.userName || "用户登录",
    //     avatarUrl: userInfo.avatarUrl || defaultAvatarUrl,
    //     phoneNumber: userInfo.phoneNumber || ""
    //   })
    // }
    return hasAuth;
  },
  authorizationSuccessful() {
    console.log("授权成功");
    this.setData({ showAuthorizedDialog: false })
    this.checkAuth();
  },

  login: function () {
    var that = this;
    wx.login({
      success: res => {
        if (res.code) {
          // 发送 code 到服务器换取 session_key, openid  
          wx.request({
            url: 'https://yourserver.com/api/login',
            data: {
              code: res.code
            },
            success: function (loginRes) {
              if (loginRes.data.success) {
                wx.setStorageSync('session_key', loginRes.data.session_key);
                wx.setStorageSync('openid', loginRes.data.openid);
                // 可以在这里提示用户进行手机号授权  
                this.setData({
                  canGetPhoneNumber: true
                });
              }
            }
          });
        }
      }
    });
  },
  getPhoneNumber: function (e) {
    if (e.detail.errMsg !== "getPhoneNumber:ok") {
      return;
    }
    const { encryptedData, iv } = e.detail;
    wx.request({
      url: 'https://yourserver.com/api/decrypt_phone',
      data: {
        encryptedData,
        iv,
        session_key: wx.getStorageSync('session_key')
      },
      success: function (decryptRes) {
        if (decryptRes.data.success) {
          console.log('解密后的手机号:', decryptRes.data.phoneNumber);
          // 处理解密后的手机号  
        }
      }
    });
  },

  // 绑定按钮点击事件  
  bindGetPhoneNumber: function () {
    if (this.data.canGetPhoneNumber) {
      wx.getPhoneNumber({
        success: this.getPhoneNumber
      });
    }
  }
})
