import {
  get,
  post,
  login,
  getWxLoginCode,
  clearWxLoginCode
} from '../../utils/http'
import { objToParam } from '../../utils/util'
Page({
  /**
   * 页面的初始数据
   */
  data: {
    userInfo: null,
    prePage: 0,
    showPhoneBtn: false,
    agreeStatus: true,
    currentLoginStatus: false // 本次登录状态
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(options)
    if (options.prePage) {
      this.setData({
        prePage: options.prePage
      })
    }
    // 清理+更新微信code
    this.refreshWxCode()
  },

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

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    // 本次已登录成功
    if (this.data.currentLoginStatus) {
      this.setData({ currentLoginStatus: false }, () => {
        this.loginSuccRedirect(1)
      })
    }
  },

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

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

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

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

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {},

  /**
   * 获取用户信息
   */
  getUserInfo(e) {
    let that = this
    if (!that.data.agreeStatus) {
      wx.showToast({
        title: '请同意用户协议和隐私政策',
        icon: 'none'
      })
      return
    }
    wx.getUserProfile({
      desc: 'desc',
      success: (res) => {
        console.log(res,'res');
        that.setData(
          {
            userInfo: JSON.parse(res.rawData)
          },
          () => {
            login().then((data) => {
              let phoneStatus = data.status
              // 状态值，0.需要获取授权信息，1.不需再获取授权信息
              if (phoneStatus == 1) {
                that.loginSucc(data, data)
              }
              that.setData({ showPhoneBtn: !phoneStatus })
            })
          }
        )
        console.log(JSON.parse(res.rawData))
      }
    })
  },

  /**
   * 获取用户手机号
   */
  getPhoneNumber(e) {
    let that = this
    if (!that.data.agreeStatus) {
      wx.showToast({
        title: '请同意用户协议和隐私政策',
        icon: 'none'
      })
      return
    }
    login().then((resLogin) => {
      console.log(resLogin,'resLogin')
      let invite = {} 
      if (getApp().invite_id) {
        invite['invite_id'] = getApp().invite_id
      }
      post(
        'api/user/wxData',
        {
          avatar_url: this.data.userInfo.avatarUrl,
          nickname: this.data.userInfo.nickName,
          iv: e.detail.iv,
          encrypted_data: e.detail.encryptedData,
          wx_data: JSON.stringify(this.data.userInfo),
          ticket: resLogin.ticket,
          ...invite
        },
        (res) => {
          that.loginSucc(resLogin, res.data)
        },
        (err) => {}
      )
    })
    return
  },

  /**
   * 登录成功逻辑
   */
  loginSucc(loginRes, wxDataRes) {
    console.log(wxDataRes,'wxDataReswxDataReswxDataRes')
    if (loginRes.status == 0 && wxDataRes.coupon&& Object.keys(wxDataRes.coupon).length>0) {
      getApp().globalData.couponPopup = true 
      getApp().globalData.coupon = wxDataRes.coupon
    }
    wx.setStorageSync('userInfo', wxDataRes)
    wx.setStorageSync('token', loginRes.token)

    get('api/user', {}, (res) => {
      if (res.data) {
        getApp().globalData.userInfo = res.data
        wx.setStorageSync('userInfo', res.data)
      }
    })
    // 标记此次登录成功
    this.setData({
      currentLoginStatus: true
    })
    // 获取用户问诊信息
    get(
      'api/user/investigation',
      {},
      (res) => {
        console.log(res)
        // 用户是否已填写，1是，0否
        // if (res.data.is_finished == 1) {
          wx.showToast({
            title: '登录成功',
            icon: 'none'
          })
          this.loginSuccRedirect()
        //   return
        // }
        // wx.navigateTo({
        //   url: `/pages/member/investigation/investigation`
        // })
      },
      () => {
        this.loginSuccRedirect()
      }
    )
  },

  /**
   * 登录成功后重定向到特定页面
   */
  loginSuccRedirect(sec = 1500) {
    let that = this
    setTimeout(() => {
      if (that.data.prePage == 1) {
        wx.navigateBack()
      } else {
        let sceneData = getApp().globalData.sceneData
        sceneData.path =
          sceneData.path == 'pages/login/login'
            ? 'pages/home/home'
            : sceneData.path
        wx.reLaunch({
          url: `/${sceneData.path}?${objToParam(sceneData.query)}`
        })
      }
    }, sec)
  },

  /**
   * 清理+更新微信code
   */
  refreshWxCode() {
    clearWxLoginCode()
    getWxLoginCode()
  },

  /**
   * 跳转去用户协议
   */
  goToAgree(e) {
    wx.navigateTo({
      url: '/pages/agreement/agreement?agree=' + e.currentTarget.dataset.agree
    })
  },

  /**
   * 同意隐私政策
   */
  rulesAgree() {
    this.setData({
      agreeStatus: !this.data.agreeStatus
    })
  }
})
