<template>
  <view>
    <view class="text">如需修改名字请重新命名，点击确定添加锁</view>
    <input class="input" :value="name" maxlength="50" placeholder="请输入名称" placeholder-class="input-placeholder"
           @input="uopdateName"
    ></input>
    <view class="button" @click="bindLock">确定</view>
  </view>
</template>

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

export default {
  data () {
    return {
      name: ''
    }
  },
  computed: {
    ...mapState(useBluetoothStore, ['currentLockInfo', 'keyId']),
    ...mapState(useUserStore, ['userInfo']),
    ...mapState(useLockStore, ['lockSearch']),
  },
  onLoad() {
    this.name = this.currentLockInfo.name
    console.log(this.currentLockInfo)
    console.log(this.name)
  },
  methods: {
    ...mapActions(useBluetoothStore, ['addLockUser', 'closeBluetoothConnection', 'updateBindedDeviceName',
      'closeAllBluetooth', 'initAndListenBluetooth']),
    ...mapActions(useLockStore, ['getLockList', 'updateLockSearch']),
    ...mapActions(useBasicStore, ['backAndToast', 'getNetworkType']),
    uopdateName(data) {
      this.name = data.detail.value
    },
    async bindLock() {
      if(this.name === '') {
        uni.showToast({
          title: '请输入名称',
          icon: 'none'
        })
        return
      }
      const netWork = await this.getNetworkType()
      if(!netWork) {
        return
      }
      uni.showLoading({
        title: '添加中',
        mask: true
      })
      this.updateBindedDeviceName(this.currentLockInfo.name)
      const timestamp = parseInt(new Date().getTime() / 1000)
      const password = (Math.floor(Math.random() * 900000) + 100000).toString()
      const { code: addUserCode } = await this.addLockUser({
        name: this.currentLockInfo.name,
        keyId: this.keyId,
        authUid: this.userInfo.uid.toString(),
        uid: this.userInfo.uid.toString(),
        openMode: 1,
        keyType: 0,
        startDate: timestamp,
        expireDate: 0xffffffff,
        useCountLimit: 0xffff,
        isRound: 0,
        weekRound: 0,
        startHour: 0,
        startMin: 0,
        endHour: 0,
        endMin: 0,
        role: 0xff,
        password
      })
      if(addUserCode === 0) {
        this.closeBluetoothConnection()
        this.closeAllBluetooth()
        this.initAndListenBluetooth()
      } else if(addUserCode === -1) {
        uni.hideLoading()
        uni.showToast({
          title: '添加失败，请靠近设备并保持设备处于唤醒状态',
          icon: 'none'
        })
        return
      } else {
        uni.hideLoading()
        return
      }
      const params = {
        lockAlias: this.name,
        lockInfo: {
          ...this.currentLockInfo.lockConfig,
          adminPwd: password
        },
        bluetooth: {
          bluetoothDeviceName: this.currentLockInfo.name,
          bluetoothDeviceId: this.currentLockInfo.deviceId,
          publicKey: this.currentLockInfo.publicKey,
          privateKey: this.currentLockInfo.commKey,
          signKey: this.currentLockInfo.signKey,
        },
        lockUserNo: this.currentLockInfo.lockUserNo,
        pwdTimestamp: this.currentLockInfo.pwdTimestamp,
        featureValue: this.currentLockInfo.featureValue,
        featureSettingValue: this.currentLockInfo.featureSettingValue,
        featureSettingParams: this.currentLockInfo.featureSettingParams
      }
      if(this.currentLockInfo.position) {
        params.position = {
          latitude: this.currentLockInfo.position.latitude,
          longitude: this.currentLockInfo.position.longitude,
          province: this.currentLockInfo.position.province,
          city: this.currentLockInfo.position.city,
          district: this.currentLockInfo.position.district,
          country: this.currentLockInfo.position.country,
          township: this.currentLockInfo.position.township,
          address: this.currentLockInfo.position.address
        }
      }
      const { code, message } = await bindLockAdmin(params)
      console.log('添加锁返回', code, message)
      if(code === 0) {
        this.updateLockSearch({
          ...this.lockSearch,
          pageNo: 1
        })
        this.getLockList(this.lockSearch)
        setTimeout(() => {
          uni.hideLoading()
          this.backAndToast('添加成功')
        }, 1000)
      } else {
        uni.hideLoading()
        uni.showToast({
          title: message,
          icon: 'none'
        })
      }
    }
  },
}
</script>

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

<style lang="scss" scoped>
.text {
  color: #2b2a28;
  padding: 100rpx 0;
  font-size: 34rpx;
  text-align: center;
}

.input {
  border-radius: 16rpx;
  background: #FFFFFF;
  margin-left: 35rpx;
  margin-top: 24rpx;
  height: 108rpx;
  width: 616rpx;
  padding-left: 32rpx;
  padding-right: 32rpx;
}

.input-placeholder {
  height: 108rpx;
  font-size: 36rpx;
  font-weight: bold;
  line-height: 108rpx;
}

.button {
  margin-top: 160rpx;
  margin-left: 35rpx;
  width: 680rpx;
  height: 96rpx;
  background: #63b8af;
  border-radius: 16rpx;
  line-height: 96rpx;
  text-align: center;
  font-size: 32rpx;
  color: #FFFFFF;
}
</style>
