<template>
  <view>
    <scroll-view v-if="deviceInfo" class="scroll-view" scroll-y="true" :style="{ height: deviceInfo.screenHeight - deviceInfo.statusBarHeight + 'px' }">
      <view style="padding-bottom: calc(env(safe-area-inset-bottom) + 300rpx)">
        <view class="device" v-for="device in deviceList" @click="connect(device)">
          <view class="device" style="justify-content:flex-start;">
            <image  class="device-lock" src="/static/images/icon_door_lock.png"></image>
            <view class="device-name">{{device.name}}</view>
          </view>
          <image class="device-add" src="/static/images/icon_add.png"></image>
        </view>
      </view>
    </scroll-view>
    <view class="loading">
      <up-loading-icon size="80rpx" text="搜索中" :vertical="true" textSize="32rpx"></up-loading-icon>
    </view>
  </view>
</template>

<script>
import { mapState, mapActions } from 'pinia'
import { useBluetoothStore } from '@/stores/bluetooth'
import { useBasicStore } from '@/stores/basic'
import { useUserStore } from '@/stores/user'

export default {
  data () {
    return {
      deviceInfo: null
    }
  },
  computed: {
    ...mapState(useBluetoothStore, ['deviceList', 'currentLockInfo', 'serverTimestamp', 'keyId']),
    ...mapState(useUserStore, ['userInfo'])
  },
  async onLoad() {
    this.deviceInfo = await this.getDeviceInfo()
    this.getBluetoothDevices()
  },
  onUnload() {
    this.stopGetBluetoothDevices()
  },
  methods: {
    ...mapActions(useBluetoothStore, ['getBluetoothDevices', 'stopGetBluetoothDevices', 'updateCurrentLockInfo',
      'getPublicKey', 'getCommKey', 'connectBluetoothDevice', 'updateServerTimestamp', 'getLockStatus']),
    ...mapActions(useBasicStore, ['getDeviceInfo', 'routeJump']),
    async connect(device) {
      uni.showLoading({
        title: '连接中',
        // mask: true
      })
      const { code: serverTimestampCode, message } = await this.updateServerTimestamp()
      if(serverTimestampCode !== 0) {
        uni.showToast({
          title: message,
          icon: 'none'
        })
        uni.hideLoading()
        return
      }
      this.updateCurrentLockInfo({
        name: device.name,
        deviceId: device.deviceId
      })
      const result = await this.connectBluetoothDevice()
      this.stopGetBluetoothDevices()
      if(result) {
        const { code: getPublicKeyCode } = await this.getPublicKey(this.currentLockInfo.name)
        console.log('获取公钥返回', getPublicKeyCode, [...this.currentLockInfo.publicKey])
        if(getPublicKeyCode !== 0) {
          uni.hideLoading()
          uni.showToast({
            title: '连接失败，请重试',
            icon: 'none'
          })
          return
        }
        const { code: getCommKeyCode } = await this.getCommKey(this.currentLockInfo.name, this.keyId,
            this.userInfo.uid.toString(), this.serverTimestamp)
        console.log('获取私钥返回', getCommKeyCode)
        if(getCommKeyCode !== 0) {
          uni.hideLoading()
          uni.showToast({
            title: '连接失败，请重试',
            icon: 'none'
          })
          return
        }
        const date = new Date()
        const timestamp = parseInt(date.getTime() / 1000) - date.getTimezoneOffset() * 60
        const { code } = await this.getLockStatus({
          name: this.currentLockInfo.name,
          uid: this.userInfo.uid,
          nowTime: this.serverTimestamp,
          localTime: timestamp
        })
        if (code !== 0) {
          uni.hideLoading()
          uni.showToast({
            title: '连接失败，请重试',
            icon: 'none'
          })
          return
        }
        this.routeJump({
          type: 'redirectTo',
          name: 'selectAddress'
        })
      } else {
        this.getBluetoothDevices()
        uni.showToast({
          title: '连接失败，请重试',
          icon: 'none'
        })
        uni.hideLoading()
      }
    }
  }
}
</script>

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

<style lang="scss" scoped>
.loading {
  position: fixed;
  bottom: calc(env(safe-area-inset-bottom) + 50rpx) ;
  left: 50%;
  transform: translateX(-50%);
}

.device {
  background: #ffffff;
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 100rpx;

  .device-lock {
    margin-left: 24rpx;
    width: 72rpx;
    height: 72rpx;
  }

  .device-name {
    margin-left: 24rpx;
    font-size: 28rpx;
    font-weight: bold;
  }

  .device-add {
    float: right;
    width: 60rpx;
    height: 60rpx;
    margin-right: 24rpx;
  }
}
</style>
