<template>
  <view class="login">
    <view class="login-logo">
      <image src="https://cdn.catmdogd.com/Work/image/user/logo.png"></image>
    </view>
    <view class="login-submit">
      <up-button type="primary" text="授权手机号登录"
                 open-type="getPhoneNumber" @getphonenumber="onGetPhoneNumber"
                 shape="circle" color="#FFBF60"></up-button>
    </view>
  </view>
</template>

<script setup>
import {getOpenIdKey, getToken, setIsLogin, setOpenIdKey, setStorage, setToken} from "../../utils/auth";
import {getOpenId, getPersonalInfo, getPhoneNumber} from "../../api/system/user";
// 获取openid
if (!getOpenIdKey() && !getToken()) {
  uni.login({
    provider: 'weixin',
    success: async (res) => {
      const {code, data} = await getOpenId(res.code)
      if (code === 200 && data) {
        let resData = JSON.parse(data)
        setOpenIdKey(resData.openId)
      }
    },
    fail: function (error) {
      // 授权失败处理
      uni.showToast('授权失败，请授权后再试')
    }
  });
}
// 获取token
const onGetPhoneNumber = async (e) => {
  if (e.detail.errMsg === "getPhoneNumber:ok") {
    if (getOpenIdKey()) {
      try {
        const {data} = await getPhoneNumber({"openId": getOpenIdKey(), "code": e.detail.code, sourceType: 1})
        setToken(data.token)
        setIsLogin(true)
        await getUserInfo()
      } catch (e) {
        uni.showToast({
          icon: 'error',
          title: '获取手机号失败'
        })
      }
    }
  }
}

// h获取用户信息
const getUserInfo = async () => {
  const {data} = await getPersonalInfo()
  setStorage('userInfo', data)
  uni.navigateBack()
}
</script>

<style scoped lang="scss">
@import "index";
</style>