<template>
  <view class="login-bar flex flex-inline" v-if="!state.isLogin">
    <text class="login-bar_title" >   请先登录以享受更多洗车功能</text>
<!--    <uv-button class="login-bar_btn" size="mini" shape="circle" type="primary" open-type="getPhoneNumber"
               color="#C6171E"
               @getphonenumber="handleGetPhone">去登录
    </uv-button>-->
    <uv-button class="login-bar_btn" size="mini" shape="circle" type="primary"
               color="#C6171E"
               @click="handleGotoLoginPage">去登录
    </uv-button>
  </view>
</template>
<script setup lang="ts" name="loginBar">
import {login, tryLogin} from "@/utils/auth";
import {onHide, onLoad, onShow} from "@dcloudio/uni-app";
import {reactive} from "vue";

const state= reactive({
  isLogin:false
});

onLoad(()=>{
  let userData = getApp<any>().globalData.user;
  state.isLogin =!!(userData&&userData.id);
})


onShow(()=>{
  let userData = getApp<any>().globalData.user;
  state.isLogin =!!(userData&&userData.id);
  addListener();
})

onHide(()=>{
  removeListener();
})

const addListener = () => {
  uni.$on('login', function (data) {
    state.isLogin = data.isLogin;
  })

  uni.$on('logout', function (data) {
    state.isLogin= false;
  })
}

const removeListener = () => {
  uni.$off('logout');
  uni.$off('login');
}


const handleGotoLoginPage = () => {
  tryLogin().then((token)=>{
    uni.$emit('login', {isLogin: true})
  }).catch(e=>{
    console.error("尝试登录失败，跳转登录页注册",e)
    uni.navigateTo({
      url: '/pages-user/login/index'
    })
  })

}
</script>

<style scoped lang="scss">
.login-bar {
  width: calc(100vw - 40rpx);
  justify-content: space-between;
  background: $uni-bg-color-card;
  border-radius: 16rpx;
  padding: 20rpx 24rpx;
  @include card-interactive(16rpx);
  position: fixed;
  bottom: 160rpx;
  left: 20rpx;

  &_title{
    font-size: 26rpx;
    height: 36rpx;
    line-height: 36rpx;
    color: $uni-text-color-secondary;
  }

  &_btn {
    flex-shrink: 0;
  }
}
</style>