<script>
import Vue from 'vue'
import {
  getUserInfo,
  getConfigInfo,
  webLogin,
  wxConfig,
  redirection,
  mini_env,
  getQueryVariable
} from '@/common/utils/util'
import wx from 'weixin-js-sdk'
import api from '@/common/http/'
var getUserValTimeId = null
import store from '@/store/index.js'
export default {
  async onLaunch() {
    api
      .get('/user/user/log', {})
      .then(res => {})
      .catch(() => {})

    mini_env(bool => {
      if (bool) {
        api
          .post('/user/open/bindOpenId', {})
          .then(res => {})
          .catch(() => {})
      }
    })

    // #ifdef MP-WEIXIN
    // 小程序更新
    const updateManager = uni.getUpdateManager()
    // 请求完新版本信息
    updateManager.onCheckForUpdate(res => {
      // console.log(res.hasUpdate);
    })
    // 新的版本已经下载好
    updateManager.onUpdateReady(res => {
      uni.showModal({
        title: '更新提示',
        content: '新版本已经准备好，是否重启应用？',
        success(res) {
          if (res.confirm) {
            // 调用 applyUpdate 应用新版本并重启
            updateManager.applyUpdate()
          }
        }
      })
    })
    // 新的版本下载失败
    updateManager.onUpdateFailed(res => {})
    // #endif

    uni.$on('updateUserInfo', () => {
      this.updateUserInfo()
    })

    uni.getSystemInfo({
      success: function (e) {
        console.log(e)
        Vue.prototype.StatusBar = e.statusBarHeight
        // #ifdef MP-WEIXIN
        let custom = wx.getMenuButtonBoundingClientRect()
        Vue.prototype.Custom = custom
        Vue.prototype.CustomBar = custom.bottom + custom.top - e.statusBarHeight + 4
        // #endif
        // #ifndef MP-WEIXIN
        Vue.prototype.CustomBar = 48
        // #endif
        //用来判断是否iphoneX类型的全面屏设备
        if (e.model.indexOf('iPhone X') == 0) {
          Vue.prototype.isIphoneX = 68
        } else {
          Vue.prototype.isIphoneX = 0
        }
      }
    })

    this.$setStorage('realAuthUrl', window.location.href.split('#')[0])

    // #ifdef MP-WEIXIN
    this.wxLogin()
    // #endif

    // #ifdef H5
    webLogin().then(async res => {
      redirection()
      const userInfo = await getUserInfo()
      console.log(userInfo)
      if (!userInfo?.avatar || !userInfo?.nickName) {
        let randomNum = new Date().getTime().toString().substr(-6)
        let configInfo = await getConfigInfo()
        api
          .post('/user/userinfo/save', {
            userId: store.state.user.userId,
            avatarUrl: configInfo.minLogo3,
            nickName: `微信用户_${randomNum}`
          })
          .then(res => {
            wxConfig(configInfo, res.data)
          })
      } else {
        let configInfo = await getConfigInfo()
        wxConfig(configInfo, {
          nickName: store.state.user.name,
          userId: store.state.user.userId
        })
      }

      // 如果链接带有serviceId，则绑定用户
      if (getQueryVariable('serviceId')) {
        api
          .post('/user/bind', {
            serviceId: getQueryVariable('serviceId'),
            userId: store.state.user.userId
          })
          .then(res => {
            console.log('绑定成功：' + res.message)
          })
      }
    })
    this.$isResolve()
    // #endif
  },
  onShow: function () {},
  onHide: function () {},
  methods: {
    wxLogin() {
      uni.login({
        provider: 'weixin',
        success: loginRes => {
          this.$api
            .post('/user/auth', {
              code: loginRes.code
            })
            .then(async res => {
              this.$store.commit('user/set_token', res.data.token)
              this.$store.commit('user/set_openId', res.data.openId)
              this.$store.commit('user/set_name', res.data.nickName)
              this.$store.commit('user/set_avatar', res.data.avatar)
              this.$store.commit('user/set_userId', res.data.userId)
              if (res.data.mobile) {
                this.$store.commit('user/set_mobile', res.data.mobile)
              }
              if (!res.data.avatar || !res.data.nickName) {
                await this.saveUserInfo(res.data)
              }
              this.$isResolve()
            })
            .catch(res => {
              this.$isReject()
            })
        }
      })
    },

    // 保存用户信息
    async saveUserInfo(userInfo) {
      let randomNum = new Date().getTime().toString().substr(-6)
      let configInfo = await this.$getConfigInfo()
      return new Promise((resolve, reject) => {
        this.$api
          .post('/user/userinfo/save', {
            userId: userInfo.userId,
            avatarUrl: configInfo.minLogo3,
            nickName: `微信用户_${randomNum}`
          })
          .then(res => {
            resolve(res.data)
          })
      })
    },

    async updateUserInfo() {}
  }
}
</script>

<style lang="scss">
/*每个页面公共css */
@import 'uview-ui/index.scss';

@import 'styles/iconfont.css';
</style>
