<template>
  <view>
    <scroll-view
      v-if="deviceInfo"
      class="scroll-view"
      scroll-y="true"
      :style="{ height: deviceInfo.windowHeight - deviceInfo.statusBarHeight + 'px' }"
    >
      <view style="padding-bottom: calc(env(safe-area-inset-bottom) + 300rpx)">
        <view
          class="device"
          v-for="(device, index) in deviceList"
          :key="index"
          @click="connect(device)"
        >
          <view class="device" style="justify-content: flex-start">
            <image
              class="device-lock"
              src="https://oss-lock.xhjcn.ltd/mp/icon_door_lock.png"
            ></image>
            <view class="device-name">{{ device.name }}</view>
          </view>
          <image class="device-add" src="https://cos-lock.skychip.top/mp/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'
  import { model } from '@/constant/transportType'

  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',
        'getLockStatusInfo'
      ]),
      ...mapActions(useBasicStore, ['getDeviceInfo', 'routeJump', 'getNetworkType']),
      async connect(device) {
        const netWork = await this.getNetworkType()
        if (!netWork) {
          return
        }
        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
        })
        try {
          const result = await this.connectBluetoothDevice()
          if (result) {
            this.stopGetBluetoothDevices()
            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 = this.serverTimestamp - date.getTimezoneOffset() * 60
            const { code } = await this.getLockStatusInfo({
              name: this.currentLockInfo.name,
              uid: this.userInfo.uid.toString(),
              nowTime: this.serverTimestamp,
              localTime: timestamp
            })
            uni.hideLoading()
            if (code !== 0) {
              uni.showToast({
                title: '连接失败，请靠近设备并保持设备处于唤醒状态',
                icon: 'none'
              })
              return
            }
            this.routeJump({
              type: 'redirectTo',
              name:
                this.currentLockInfo.lockConfig.model === model.TENCENT_YUN_LOCK
                  ? 'distributionNetwork'
                  : 'bindLock'
            })
          } else {
            uni.hideLoading()
            uni.showToast({
              title: '连接失败，请靠近设备并保持设备处于唤醒状态',
              icon: 'none'
            })
          }
        } catch (error) {
          console.log('连接失败', error)
          uni.hideLoading()
          uni.showToast({
            title: '连接失败，请靠近设备并保持设备处于唤醒状态',
            icon: 'none'
          })
        }
      }
    }
  }
</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 {
    display: flex;
    align-items: center;
    justify-content: space-between;
    height: 100rpx;
    background: #ffffff;

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

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

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