<template>
  <view class="min-height bg-white flex flex-col justify-center items-center" @click="openDoor()">
    <u-icon name="/userPages/static/开锁.png" size="300rpx"/>
    <text class="mt-20 font-bold text-25">开门</text>
    <Login ref="Login" @done="getUserData"/>
  </view>
</template>

<script>
import {openDoorReq} from "@/api/common";
import Login from "@/components/Login.vue";
import {userInfoReq} from "@/api/user";
import {getUserInfo} from "@/util/user";

export default {
  name: "remote-door-access",
  components: {Login},
  data() {
    return {
      serial: ''
    }
  },
  methods: {
    async openDoor() {
      uni.showLoading({
        title: '正在开锁...',
        mask: true
      })
      const res = await openDoorReq(this.serial).finally(() => {
        uni.hideLoading()
      })
      if (res) {
        this.$toast('开锁成功')
        setTimeout(() => {
          uni.switchTab({url: '/pages/index/index'})
        }, 1500)
      }
    },
    async getUserData() {
      const {data} = await userInfoReq().catch(() => {
        this.login()
      })
      this.userData = data
      this.isLogin = true
    },
    login() {
      this.$refs.Login.open()
    }
  },
  onLoad(query) {
    const url = decodeURIComponent(query.q)
    this.serial = url.split('=')[1]
    if (getUserInfo().token) this.getUserData()
    else this.login()
  }
}
</script>