<template>
  <view>
    <view class="text-xl text-center py-10 h-100 line-height-100rpx">
      <view v-if="show">{{
        timeFormat($bluetooth.currentLockInfo.lockConfig.indate, 'yyyy-mm-dd hh:MM')
      }}</view>
    </view>
    <view
      class="bg-#63b8af mt-4 rounded-3xl w-600 h-80 line-height-80rpx text-center mx-75rpx text-white text-xl font-bold"
      @click="update"
    >
      校准
    </view>
  </view>
</template>

<script setup>
  import { onMounted, ref } from 'vue'
  import { timeFormat } from 'uview-plus'
  import { useBluetoothStore } from '@/stores/bluetooth'
  import { useUserStore } from '@/stores/user'

  const $bluetooth = useBluetoothStore()
  const $user = useUserStore()

  const pending = ref(false)

  const show = ref(false)

  onMounted(async () => {
    uni.showLoading({
      title: '加载中'
    })
    const { code } = await $bluetooth.updateServerTimestamp()
    if (code === 0) {
      const date = new Date()
      const timestamp = $bluetooth.serverTimestamp - date.getTimezoneOffset() * 60
      const { code: lockStatus } = await $bluetooth.getLockStatus({
        name: $bluetooth.currentLockInfo.lockId.toString(),
        uid: $user.userInfo.uid.toString(),
        nowTime: $bluetooth.serverTimestamp,
        localTime: timestamp
      })
      uni.hideLoading()
      $bluetooth.closeBluetoothConnection()
      if (lockStatus === 0) {
        show.value = true
      } else {
        uni.showToast({
          title: '获取锁时间失败，请返回重试',
          icon: 'none'
        })
      }
    } else {
      uni.hideLoading()
      uni.showToast({
        title: '获取锁时间失败，请返回重试',
        icon: 'none'
      })
    }
  })

  const update = async () => {
    if (pending.value && show.value) return
    uni.showLoading({
      title: '更新中'
    })
    pending.value = true
    const { code, message } = await $bluetooth.updateServerTimestamp()
    if (code === 0) {
      const { code: lockStatus } = await $bluetooth.calibrationTime({
        lockId: $bluetooth.currentLockInfo.lockId.toString(),
        uid: $user.userInfo.uid.toString(),
        nowTime: $bluetooth.serverTimestamp
      })
      $bluetooth.closeBluetoothConnection()
      uni.hideLoading()
      pending.value = false
      if (lockStatus === 0) {
        $bluetooth.updateCurrentLockInfo({
          ...$bluetooth.currentLockInfo,
          lockConfig: {
            ...$bluetooth.currentLockInfo.lockConfig,
            indate: $bluetooth.serverTimestamp * 1000
          }
        })
        uni.showToast({
          title: '更新成功',
          icon: 'none'
        })
      } else {
        uni.hideLoading()
        pending.value = false
        uni.showToast({
          title: '更新失败',
          icon: 'none'
        })
      }
    } else {
      uni.showToast({
        title: message,
        icon: 'none'
      })
    }
  }
</script>

<style lang="scss">
  page {
    background-color: $uni-bg-color-grey;
  }
</style>
