//index.js
import Toast from '@vant/weapp/toast/toast';
import {
  saveAppUserInfo,
  getMpOpenId,
  decryptEncryptedData
} from "../../api/home"

Page({
  data: {
    motto: '微信授权登录后，才可以使用大部分功能。',
    userInfo: {},
    hasUserInfo: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    defaultSize: 'default',
    primarySize: 'default',
    warnSize: 'default',
    disabled: false,
    plain: false,
    loading: false,
    showModal: false, //定义登录弹窗
    isShowUserInfoLayer: false, //是否显示自定义授权位置弹框
  },

  onLoad: function () {
    //获取应用实例
    let app = getApp()
    // console.log("****************onLoad******************");
    if (app.globalData.userInfo) {
      this.setData({
        userInfo: app.globalData.userInfo,
        hasUserInfo: true
      })
    } else if (this.data.canIUse) {
      // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
      // 所以此处加入 callback 以防止这种情况
      app.userInfoReadyCallback = res => {
        this.setData({
          userInfo: res.userInfo,
          hasUserInfo: true
        })
      }
    } else {
      // 在没有 open-type=getUserInfo 版本的兼容处理
      wx.getUserInfo({
        success: res => {
          app.globalData.userInfo = res.userInfo
          this.setData({
            userInfo: res.userInfo,
            hasUserInfo: true
          })
        }
      })
    }
    // console.log("user info:" + app.globalData.userInfo);
    // wx.login({  
    //   success: function (res) {
    //     if (res.code) {  
    //       //发起网络请求  
    //       console.log(res.code)
    //     } else {  
    //       console.log('获取用户登录态失败！' + res.errMsg)  
    //     }  
    //   }  
    // });  
  },
  //授权用户信息按钮
  bindAuthUserInfo: function (e) {
    var that = this;
    //获取授权结果查看是否已授权用户信息
    wx.getSetting({
      success: (res) => {
        if (res.authSetting['scope.userInfo'] == undefined && !res.authSetting['scope.userInfo']) //未授权获取用户信息（首次进来页面）
          that.getLocationInfo(); //获取当前用户信息
        else if (res.authSetting['scope.userInfo'] === false) //未授权获取用户信息(点击官方授权弹框取消按钮后)
          that.setData({
            isShowUserInfoLayer: true
          }) //显示自定义授权框
        else //已授权
          that.getUserInfo(); //获取当前用户信息
      }
    })
  },
  //用户信息授权框确认按钮
  bindConfirmUserInfo: function (e) {
    var that = this;
    //打开设置页面进行授权设置
    wx.openSetting({
      success: function (res) {
        if (res.authSetting['scope.userInfo']) {
          //获取当前用户信息
          that.setData({
            isShowUserInfoLayer: false,
          })
        }
      }
    });
  },

  //授权框取消按钮
  bindCancelUserInfo: function (e) {
    let that = this;
    that.setData({
      isShowUserInfoLayer: false
    })
    wx.showModal({
      title: '拒绝授权提示',
      content: '您未授权获取当前用户信息，小程序大部分功能将无法使用！是否拒绝授权？',
      showCancel: true, //是否显示取消按钮
      cancelText: "否", //默认是“取消”
      cancelColor: 'skyblue', //取消文字的颜色
      confirmText: "是", //默认是“确定”
      confirmColor: 'skyblue', //确定文字的颜色
      success: function (res) {
        if (res.cancel) { //点击否
          that.setData({
            isShowUserInfoLayer: true
          })
        } else { //点击是
          that.setData({
            isShowUserInfoLayer: false
          })
        }
      },
      fail: function (res) {}, //接口调用失败的回调函数
      complete: function (res) {}, //接口调用结束的回调函数（调用成功、失败都会执行）
    })
  },
  // 显示一键获取手机号弹窗
  showDialogBtn: function () {
    this.setData({
      showModal: true //修改弹窗状态为true，即显示
    })
  },
  // 隐藏一键获取手机号弹窗
  hideModal: function () {
    this.setData({
      showModal: false //修改弹窗状态为false,即隐藏
    });
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    // console.log("onReady@@@@@@@@@@@@@@@@@");
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    // console.log("*************onShow****************");

  },
  getUserInfo: function (e) {
    var app = getApp()
    let that = this;
    // console.log(e)
    // 获取用户信息
    wx.getSetting({
      success(res) {
        // console.log("res", res)
        if (res.authSetting['scope.userInfo']) {
          // console.log("已授权=====")
          // 已经授权，可以直接调用 getUserInfo 获取头像昵称
          wx.getUserInfo({
            success(res) {
              // console.log("获取用户信息成功", res.userInfo);
              app.globalData.userInfo = res.userInfo;
              // console.log("minaOpenid:"+app.mpOpenId);
              // console.log("blogNickName:"+res.userInfo.nickName);
              // console.log("sexFlag:"+res.userInfo.gender === 1?'M':'F');
              // console.log("blogProfilePhoto:"+res.userInfo.avatarUrl);
              that.showDialogBtn(); //调用一键获取手机号弹窗
              that.setData({
                userInfo: res.userInfo,
                hasUserInfo: true
              })
            },
            fail(res) {
              console.log("获取用户信息失败", res)
            }
          })
        } else {
          // console.log("未授权=====")
          that.bindAuthUserInfo();
        }
      }
    })
  },
  getPhoneNumber: function (e) {
    let that = this;
    let app = getApp();
    // console.log(e.detail.errMsg)
    // console.log("iv:" + e.detail.iv)
    // console.log("encryptedData:" + e.detail.encryptedData)
    let iv = e.detail.iv;
    let encryptedData = e.detail.encryptedData
    let sessionKey = null;
    let mobilePhone = null;
    wx.login({
      success: function (res) {
        if (res.code) {
          let code = res.code;
          //发起网络请求  
          getMpOpenId({
            code: code
          }).then(res => { // handle success 
            // console.log("sessionKey:" + res.session_key);
            that.sessionKey = res.session_key;
            decryptEncryptedData({
              sessionKey: that.sessionKey,
              encryptedData: encryptedData,
              iv: iv
            }).then(res => { // handle success
              mobilePhone = res.phoneNumber;
              // console.log("userType:"+2);
              // console.log("minaOpenid:"+app.mpOpenId);
              // console.log("blogNickName:"+app.globalData.userInfo.nickName);
              // console.log("sexFlag:"+app.globalData.userInfo.gender === 1 ? 'M' : 'F');
              // console.log("blogProfilePhoto:"+app.globalData.userInfo.avatarUrl);
              // console.log("mobilePhone:"+mobilePhone);
              //保存appUserInfo信息
              saveAppUserInfo({
                "userType": "2",
                "minaOpenid": app.mpOpenId,
                "blogNickName": app.globalData.userInfo.nickName,
                "sexFlag": app.globalData.userInfo.gender === 1 ? 'M' : 'F',
                "blogProfilePhoto": app.globalData.userInfo.avatarUrl,
                "mobilePhone": mobilePhone
              }).then(res => { // handle success 
                // console.log(res.data);
                if (res.retCode == 0 || res.retCode == -1) {
                  // console.log("保存app用户信息成功："+app.globalData.userInfo);
                  // console.log("保存app用户信息成功。。。");
                }
              }).catch(error => { // handle error
                console.log(error);
              })
            }).catch(error => { // handle error
              console.log(error);
            })
          }).catch(error => { // handle error
            console.log(error);
          })
        } else {
          console.log('获取用户登录态失败！' + res.errMsg)
        }
      }
    });
    if (e.detail.errMsg == 'getPhoneNumber:fail user deny') {
      wx.showModal({
        title: '提示',
        showCancel: false,
        content: '未授权',
        success: function (res) {
          //  console.log("未授权返回的res："+res);
        }
      })
    } else {
      wx.showModal({
        title: '提示',
        showCancel: false,
        content: '同意授权',
        confirmText: "确定", //默认是“确定”
        confirmColor: 'skyblue', //确定文字的颜色
        success: function (res) {
          if (res.confirm) {
            that.setData({
              showModal: false
            });
            wx.switchTab({
              url: '../gasup/index',
            });
          } else {}
        }
      })
    }
  }

  
})