<template>
  <view>
    <view class="flex justify-center flex-col pt-20">
      <image
        src="/static/images/icon_add_card.png"
        mode="aspectFill"
        class="mx-[200rpx] w-350 h-350"
      ></image>
      <view class="mt-5">
        <up-loading-icon size="70rpx" text="" :vertical="true" textSize="32rpx"></up-loading-icon>
      </view>
      <view
        class="text-base rounded-xl mt-15 bg-black mx-[75rpx] w-600 h-80 text-align-center line-height-[80rpx] text-white shadow-sm"
        >{{ text }}</view
      >
    </view>
  </view>
</template>

<script setup>
  import { ref, onUnmounted, getCurrentInstance } from 'vue'
  import { onLoad } from '@dcloudio/uni-app'
  import { useBluetoothStore } from '@/stores/bluetooth'
  import { useBasicStore } from '@/stores/basic'
  import { useUserStore } from '@/stores/user'
  import { addCardRequest } from '@/api/card'

  const instance = getCurrentInstance().proxy
  const eventChannel = instance.getOpenerEventChannel()

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

  const bindFlag = ref(false)

  const text = ref('尝试连接设备…')

  onLoad(async options => {
    if (options.card) {
      const params = JSON.parse(options.card)
      const { code } = await $bluetooth.registerAuthentication(params)

      if (code === 0) {
        text.value = '已连接到锁，请将卡靠近锁的读卡区'
      } else {
        $basic.backAndToast('操作失败，请重试')
      }

      uni.$on('registerCardConfirm', async data => {
        if (data.status === 0) {
          bindFlag.value = true
          const { code, message } = await addCardRequest({
            lockId: $bluetooth.currentLockInfo.lockId,
            startDate: params.startDate,
            endDate: params.endDate,
            cardName: params.cardName,
            cardNumber: String(data.cardNumber),
            cardType: params.cardType,
            addType: 1,
            cardRight: params.isAdmin,
            isCoerced: params.isForce === 1 ? 2 : 1
          })
          if (code === 0) {
            eventChannel.emit('refresherList', {})
            $basic.backAndToast('绑卡成功', 2)
          } else {
            $basic.backAndToast(message)
          }
        }
      })
    }
  })

  onUnmounted(async () => {
    uni.$off('registerCardConfirm')
    if (!bindFlag.value) {
      await $bluetooth.registerAuthenticationCancel({
        type: 'card',
        keyId: $bluetooth.keyId.toString(),
        uid: $user.userInfo.uid.toString()
      })
    }
    $bluetooth.closeBluetoothConnection()
  })
</script>

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