<template>
  <view class="dialog">
    <image
      class="top-background"
      src="https://oss-lock.xhjcn.ltd/mp/background_main.jpg"
      mode="aspectFill"
    ></image>
    <view class="switch" @click="openDoorOperate">
      <SwitchLoading :size="220" ref="sLoading"></SwitchLoading>
    </view>
    <view class="switch-text">点击开锁</view>
  </view>
</template>

<script setup>
  import { ref, onMounted } from 'vue'
  import SwitchLoading from '@/components/SwitchLoading/SwitchLoading.vue'
  import { useBluetoothStore } from '@/stores/bluetooth'
  import { useBasicStore } from '@/stores/basic'
  import { useUserStore } from '@/stores/user'
  import { getLockDetailRequest, getLockNetTokenRequest } from '@/api/lock'

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

  const sLoading = ref(null)

  const pending = ref(false)

  const lockInfo = ref(null)

  const onlineToken = ref('0')

  const lockId = ref(2712)

  const time = ref(0)

  onMounted(async () => {
    const { code, data, message } = await getLockDetailRequest({
      lockId: lockId.value
    })
    if (code === 0) {
      lockInfo.value = data
      $bluetooth.updateCurrentLockInfo({
        ...lockInfo.value,
        name: lockInfo.value.lockName,
        deviceId: lockInfo.value.lockName,
        commKey: lockInfo.value.privateKey
      })
    } else {
      uni.showToast({
        title: message,
        icon: 'none'
      })
    }
    await getServeTime()
  })

  const getServeTime = async () => {
    const { code, data } = await $bluetooth.updateServerTimestamp()
    if (code === 0) {
      time.value = parseInt((data.date - new Date().getTime()) / 1000, 10)
    }
  }

  const openDoorOperate = async () => {
    const timestamp = new Date().getTime()
    if (pending.value) {
      return
    }

    const netWork = await $basic.getNetworkType()
    if (!netWork) {
      return
    }

    if (lockInfo.value.appUnlockOnline) {
      const result = await getNetToken()
      if (!result) {
        sLoading.value.close()
        pending.value = false
        return
      }
    }

    uni.vibrateLong()
    pending.value = true
    sLoading.value.open()
    const openMode = lockInfo.value.appUnlockOnline ? 1 : 0

    const { code } = await $bluetooth.openDoor({
      name: lockInfo.value.lockName,
      uid: $user.userInfo.uid.toString(),
      openMode,
      openTime: parseInt(new Date().getTime() / 1000, 10) + time.value,
      onlineToken: onlineToken.value
    })

    $bluetooth
      .syncRecord({
        keyId: lockInfo.value.keyId.toString(),
        uid: $user.userInfo.uid.toString()
      })
      .then(() => {
        $bluetooth.closeBluetoothConnection()
      })

    uni.reportEvent('open_door', {
      result: code,
      duration: new Date().getTime() - timestamp
    })

    if (code === 0) {
      uni.showToast({
        title: `开门成功`,
        icon: 'none'
      })
    } else if (code === 7) {
      uni.showToast({
        title: `钥匙过期`,
        icon: 'none'
      })
    } else if (code === 13) {
      uni.showToast({
        title: `钥匙当前不可用`,
        icon: 'none'
      })
    } else if (code === -1) {
      uni.showToast({
        title: `开锁失败`,
        icon: 'none'
      })
    }
    sLoading.value.close()
    pending.value = false
  }

  const getNetToken = async () => {
    const { code, data, message } = await getLockNetTokenRequest({
      lockId: lockId.value
    })
    if (code === 0) {
      onlineToken.value = data.token
      return true
    }
    uni.showToast({
      title: message,
      icon: 'none'
    })
    return false
  }
</script>

<style lang="scss" scoped>
  .dialog {
    position: relative;
    display: flex;
    align-items: center;
    justify-content: center;
    width: 100%;
    height: 75vh;
    background-color: #f3f3f3;

    .top-background {
      position: absolute;
      width: 686rpx;
      height: 464rpx;
      border-radius: 32rpx;
    }

    .switch {
      z-index: 99;
      display: flex;
      align-items: center;
      justify-content: center;
      width: 250rpx;
      height: 250rpx;
      margin-top: 20rpx;
      background: #ffffff;
      border-radius: 50%;
      box-shadow: 0 8rpx 36rpx 0 rgba(0, 0, 0, 0.12);
    }

    .switch-text {
      z-index: 99;
      margin-top: 10rpx;
      text-align: center;
    }
  }
</style>
