<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="#19A497"
               @getphonenumber="handleGetPhone">去登录
    </uv-button>-->
    <uv-button class="login-bar_btn" size="mini" shape="circle" type="primary"
               color="#19A497"
               @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);
  console.log("login bar onLoad>>>>", userData, state.isLogin)
})


onShow(()=>{
  let userData = getApp<any>().globalData.user;
  state.isLogin =!!(userData&&userData.id);
  console.log("login bar onShow>>>>", userData, state.isLogin)
  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 handleGetPhone = (e:any) => {
  console.log(e)
  login(e).then((token: string) => {
    console.log(">>>>>>>>>",token)
      state.isLogin =true;
  })
}

const handleGotoLoginPage = () => {
/*  uni.navigateTo({
    url: '/pages-user/login/index'
  })*/
  tryLogin().then((token)=>{
    console.log(">>>>>>>>>",token)

  }).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: #eee;
  border-radius: 8rpx;
  padding: 16rpx 10rpx;
  margin: 20rpx;
  box-shadow: 5px 5px 15px 5px rgba(0, 0, 0, 0.3);
  position: fixed;
  bottom: 160rpx;
  left: 0;

  &_title{
    font-size: 12px;
    height: 22px;
    line-height: 22px;
  }

  &_btn {
    margin-right: 30rpx;
  }
}
</style>