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

const homeApi_empower = "https://aipush.aidsleep.cn";
Page({
  data: {
    showAuthorizedDialog: false,
    hasAuth: false,
    showTipsA: 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
    });
  },
  onCloseTipsDialog() {
    this.setData({
      showTipsA: false,
    })
  },
  //扫码
  tapScan() {
    const that = this;
    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);

        if (res.result) {
          let hotelcodeTemp = res.result.split('|')[0];
          let roomcodeTemp = res.result.split('|')[1];
          // wx.clearStorage();
          var hotelEmpower = wx.getStorageSync("hotelEmpower");
          var roomEmpower = wx.getStorageSync("roomEmpower");
          if (hotelcodeTemp == hotelEmpower && roomcodeTemp == roomEmpower) {
            wx.setStorageSync('res', res);
            wx.setStorageSync('scanResultExpiresAt', Date.now() + 2 * 60 * 60 * 1000); // 超时时间戳，例如设置为2小时后过期
            wx.reLaunch({
              url: '/subpages/main/main?res=' + res,//传res
            })
          } else {
            that.checkwxstatus(res, hotelcodeTemp, roomcodeTemp);
          }
        }

      }
    })
  },
  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") || false;
    this.setData({
      hasAuth: hasAuth
    })
    if (hasAuth) {
      //   var userInfo = wx.getStorageSync("userInfo");
      //   this.setData({
      //     userName: userInfo.userName || "用户登录",
      //     avatarUrl: userInfo.avatarUrl || defaultAvatarUrl,
      //     phoneNumber: userInfo.phoneNumber || ""
      //   })

      // 判断扫码控制权限
      wx.request({
        url: `${homeApi_empower}/wxstatus`,
        data: {
          unionid: wx.getStorageSync('unionid'),
          openid: wx.getStorageSync('openid'),
          token: wx.getStorageSync('token'),
        },
        method: 'POST',
        success: function (intervalRes) {
          console.log('intervalRes=' + JSON.stringify(intervalRes));
          console.log('intervalRes.data=' + JSON.stringify(intervalRes.data));
          //empower.js? [sm]:152 intervalRes.data={"st":"success","status":"0"}
          if (intervalRes.data && intervalRes.data.st && intervalRes.data.status && intervalRes.data.st == 'success' && intervalRes.data.status == '1') {
            wx.setStorageSync('hasHotelAuth', true);
            wx.setStorageSync('hotelEmpower', intervalRes.data.hotel);
            wx.setStorageSync('roomEmpower', intervalRes.data.room);
            wx.setStorageSync('hname', intervalRes.data.hname);
            wx.setStorageSync('rname', intervalRes.data.rname);
            
          } else {
            wx.setStorageSync('hasHotelAuth', false);
          }
        },
        fail: function (error) {

        }
      });
    }
    return hasAuth;
  },
  // 扫码后判断是否有权限 针对特权用户
  checkwxstatus(res, hotelcodeTem, roomcodeTemp) {
    const that = this;
    wx.request({
      url: `${homeApi_empower}/wxstatus`,
      data: {
        unionid: wx.getStorageSync('unionid'),
        openid: wx.getStorageSync('openid'),
        token: wx.getStorageSync('token'),
        "hotel": hotelcodeTem,
        "room": roomcodeTemp
      },
      method: 'POST',
      success: function (intervalRes) {
        console.log('intervalRes=' + JSON.stringify(intervalRes));
        console.log('intervalRes.data=' + JSON.stringify(intervalRes.data));
        //empower.js? [sm]:152 intervalRes.data={"st":"success","status":"0"}
        if (intervalRes.data && intervalRes.data.st && intervalRes.data.status && intervalRes.data.st == 'success' && intervalRes.data.status == '1') {
          wx.setStorageSync('hasHotelAuth', true);
          wx.setStorageSync('hotelEmpower', intervalRes.data.hotel);
          wx.setStorageSync('roomEmpower', intervalRes.data.room);
          wx.setStorageSync('hname', intervalRes.data.hname);
          wx.setStorageSync('rname', intervalRes.data.rname);

          wx.setStorageSync('res', res);
          wx.setStorageSync('scanResultExpiresAt', Date.now() + 2 * 60 * 60 * 1000); // 超时时间戳，例如设置为2小时后过期
          wx.reLaunch({
            url: '/subpages/main/main?res=' + res,//传res
          })
        } else {
          wx.setStorageSync('hasHotelAuth', false);
          that.setData({
            showTipsA: true
          })
        }
      },
      fail: function (error) {
        that.setData({
          showTipsA: true
        })
      }
    });
  },
  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
      });
    }
  }
})
