<template>
  <view>
    <view class="py-3 px-4 bg-white !py-2 flex items-center justify-between text-base">
      <view class="item-title">自动闭锁</view>
      <switch
        @click="changeCheck"
        :checked="check"
        class="transform-scale-90"
        :disabled="true"
        :color="$bluetooth.currentLockSetting.lockBasicInfo.keyRight === 1 ? '#002ce5' : '#71acff'"
      />
    </view>
    <view
      v-if="check"
      class="py-3 px-4 bg-white !py-2 flex items-center justify-between text-base mt-1"
      @click="open"
    >
      <view class="item-title">延迟时间</view>
      <view class="flex items-center">
        <view class="mr-2">{{ custom ? '自定义' : value + 's' }}</view>
        <up-icon name="arrow-right"></up-icon>
      </view>
    </view>
    <view class="mt-1" v-if="custom && check">
      <LockInput
        :value="text"
        title="时间"
        type="number"
        :maxlength="2"
        placeholder="请输入时间，范围为5-60"
        @change-input="changeDuration"
      ></LockInput>
    </view>
    <view class="m-4 text-sm">
      经过以上设定的时间，锁会自动关闭。开启或修改设置后，请先开一次锁，使时间生效。
    </view>
    <view
      v-if="$bluetooth.currentLockSetting.lockBasicInfo.keyRight === 1"
      :class="[canUpdate ? 'bg-#63b8af' : 'bg-#a3a3a3']"
      class="mt-4 rounded-3xl w-600 h-80 line-height-80rpx text-center mx-75rpx text-white text-xl font-bold"
      @click="update"
    >
      保存
    </view>
    <up-picker
      :show="show"
      :columns="columns"
      :defaultIndex="picker"
      title="选择时间"
      keyName="name"
      :itemHeight="70"
      :visibleItemCount="5"
      @close="show = false"
      @cancel="show = false"
      @confirm="confirm"
    ></up-picker>
  </view>
</template>

<script setup>
  import { computed, onMounted, ref } from 'vue'
  import { useBluetoothStore } from '@/stores/bluetooth'
  import { updateLockSettingRequest } from '@/api/setting'
  import { useUserStore } from '@/stores/user'
  import { useBasicStore } from '@/stores/basic'

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

  const check = ref(false)
  const value = ref(0)
  const picker = ref([0])

  const text = ref('')

  const show = ref(false)
  const pending = ref(false)
  const custom = ref(false)

  const columns = ref([
    [
      { name: '5s', value: 5 },
      { name: '10s', value: 10 },
      { name: '15s', value: 15 },
      { name: '30s', value: 30 },
      { name: '60s', value: 60 },
      { name: '自定义', value: -1 }
    ]
  ])

  const canUpdate = computed(() => {
    return (
      (($bluetooth.currentLockSetting.lockSettingInfo.autoLock === 1) !== check.value ||
        value.value !== $bluetooth.currentLockSetting.lockSettingInfo.autoLockSecond) &&
      ((check.value && value.value >= 5 && value.value <= 60) || !check.value)
    )
  })

  onMounted(() => {
    check.value = $bluetooth.currentLockSetting.lockSettingInfo.autoLock === 1
    value.value = $bluetooth.currentLockSetting.lockSettingInfo.autoLockSecond
    const index = columns.value[0].findIndex(item => item.value === value.value)
    if (check.value && index === -1) {
      custom.value = true
      picker.value = [5]
      text.value = $bluetooth.currentLockSetting.lockSettingInfo.autoLockSecond.toString()
    } else {
      picker.value = [index]
    }
  })

  const open = () => {
    if ($bluetooth.currentLockSetting.lockBasicInfo.keyRight !== 1) return
    show.value = true
  }

  const changeDuration = data => {
    if (custom.value) {
      value.value = Number(data)
    }
  }

  const update = async () => {
    if (!canUpdate.value) return
    if (pending.value) return
    pending.value = true
    uni.showLoading({
      title: '保存中'
    })
    const featureBit = 29
    const { code } = await $bluetooth.updateSetting({
      keyId: $bluetooth.keyId.toString(),
      uid: $user.userInfo.uid.toString(),
      featureBit,
      params: [Number(value.value)],
      withParams: true
    })
    $bluetooth.closeBluetoothConnection()
    if (code === 0) {
      const { code, message } = await updateLockSettingRequest({
        lockId: $bluetooth.currentLockInfo.lockId,
        autoLock: check.value ? 1 : 0,
        autoLockSecond: value.value
      })
      pending.value = false
      uni.hideLoading()
      if (code === 0) {
        $bluetooth.updateCurrentLockSetting({
          ...$bluetooth.currentLockSetting,
          lockSettingInfo: {
            ...$bluetooth.currentLockSetting.lockSettingInfo,
            autoLock: check.value ? 1 : 0,
            autoLockSecond: value.value
          }
        })
        $basic.backAndToast('更新成功')
      } else {
        uni.showToast({
          title: message,
          icon: 'none'
        })
      }
    } else {
      pending.value = false
      uni.hideLoading()
      uni.showToast({
        title: '更新失败，请保持在锁附近',
        icon: 'none'
      })
    }
  }

  const confirm = data => {
    if (data.indexs[0] === 5) {
      custom.value = true
    } else {
      custom.value = false
      value.value = columns.value[0][data.indexs[0]].value
    }
    show.value = false
  }

  const changeCheck = () => {
    if ($bluetooth.currentLockSetting.lockBasicInfo.keyRight !== 1) return
    check.value = !check.value
    if (!check.value) {
      value.value = 0
    } else {
      value.value = 5
    }
  }
</script>

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