import {
  imgServerUrl
} from '../../config/config.js'
import {
  getWxCode,
  getUserInfo
} from '../../utils/wx.js'
import {
  wxLogin,
  saveLogin
} from '../../services/wx.js'
import { saveHpUserLog } from '../../services/index'
import {
  showToast
} from '../../utils/tips.js'
var app = getApp()
Page({
  data: {
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    imgServerUrl: imgServerUrl,
    disabled: false,
    title: '登录开心工作'
  },
  onLoad: function () {

  },
  // 获取验证码
  toCheck(e) {
    const { phone } = e.detail;
    wx.navigateTo({
      url: `/pages/check-iphone/index?phone=${phone}&&title=${this.data.title}&&url=${'/pages/index/index'}&&auto_send=${true}`,
    })
  },
  //用户授权
  bindGetUserInfo: function (e) {
    var self = this;
    if (!self.data.disabled) {
      self.setData({
        disabled: true
      })
      //检查登录态
      wx.checkSession({
        success() {
          //session_key 未过期，并且在本生命周期一直有效
          getWxCode().then(code => {
            return wxLogin({
              code: code
            })
          })
            .then(res => {
              wx.aldPushSendOpenid(res.data.openId)
              app.globalData.openId = res.data.openId ? res.data.openId : '';
              app.globalData.sessionKey = res.data.sessionKey ? res.data.sessionKey : '';
            })
            .then(() => {
              if (e.detail.userInfo) {
                return getUserInfo()
              } else {

              }
            })
            .then(res => {
              if (res) {
                wx.setStorageSync("userInfo", res.userInfo);
                saveLogin({
                  encryptedData: encodeURIComponent(res.encryptedData),
                  iv: encodeURIComponent(res.iv),
                  openid: app.globalData.openId,
                  session_key: app.globalData.sessionKey
                }).then(data => {
                  wx.setStorageSync("hpuser", data.data.hpUser);
                  wx.setStorageSync("hpMember", data.data.hpMember);
                  wx.setStorageSync("user_id", data.data.hpUser.id);
                  wx.setStorageSync("member_id", data.data.hpMember.id);
                  wx.setStorageSync("user_token", data.data.hpUser.userToken);
                  wx.setStorageSync("phone", data.data.hpUser.phone);
                  // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
                  // 所以此处加入 callback 以防止这种情况
                  if (app.userInfoReadyCallback) {
                    app.userInfoReadyCallback(res)
                  }
                  showToast("登录成功");
                  saveHpUserLog({
                    user_id: data.data.hpUser.id,
                    user_token: data.data.hpUser.userToken,
                    member_id: data.data.hpMember.id,
                    login_type: 0
                  })
                  setTimeout(function () {
                    wx.navigateBack({
                      delta: 1,
                      fail: () => {
                        wx.switchTab({
                          url: '/pages/index/index',
                        })
                      }
                    });
                  }, 500)
                }).catch(data => {
                  console.log("fgh", data)
                })
              }
            })
        },
        fail() {
          // session_key 已经失效，需要重新执行登录流程
          getWxCode().then(code => {
            return wxLogin({
              code: code
            })
          })
            .then(res => {
              app.globalData.openId = res.data.openId ? res.data.openId : '';
              app.globalData.sessionKey = res.data.sessionKey ? res.data.sessionKey : '';
            })
            .then(() => {
              if (e.detail.userInfo) {
                return getUserInfo()
              } else {

              }
            })
            .then(res => {
              if (res) {
                wx.setStorageSync("userInfo", res.userInfo);
                saveLogin({
                  encryptedData: encodeURIComponent(res.encryptedData),
                  iv: encodeURIComponent(res.iv),
                  openid: app.globalData.openId,
                  session_key: app.globalData.sessionKey
                }).then(data => {
                  wx.setStorageSync("hpuser", data.data.hpUser);
                  wx.setStorageSync("hpMember", data.data.hpMember);
                  wx.setStorageSync("user_id", data.data.hpUser.id);
                  wx.setStorageSync("member_id", data.data.hpMember.id);
                  wx.setStorageSync("user_token", data.data.hpUser.userToken);
                  wx.setStorageSync("phone", data.data.hpUser.phone);
                  // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
                  // 所以此处加入 callback 以防止这种情况
                  if (app.userInfoReadyCallback) {
                    app.userInfoReadyCallback(res)
                  }
                  showToast("登录成功");
                  setTimeout(function () {
                    wx.navigateBack({
                      fail: () => {
                        wx.switchTab({
                          url: '/pages/index/index',
                        })
                      }
                    });
                  }, 500)
                }).catch(data => {
                  console.log("fgh", data)
                })
              }
            })
        }
      })
      // 用户登录首页
      wx.aldPushSubscribeMessage({
        eventId: '5ea25b117739104342928e97'
      });
    }
    setTimeout(function () {
      self.setData({
        disabled: false
      })
    }, 1000)
  },
  privacyCancel(){
    wx.switchTab({
      url: '/pages/index/index',
    })
  }
})