<template>
  <view v-if="requestFinished" class="pb-100rpx">
    <view
      class="py-3 px-4 bg-white flex items-center justify-between text-base"
      @click="toJump('lockInfo')"
    >
      <view class="item-title">基本信息</view>
      <view><up-icon name="arrow-right"></up-icon></view>
    </view>
    <view class="mt-2.5"></view>
    <view
      class="py-3 px-4 bg-white flex items-center justify-between text-base mb-4rpx"
      v-if="$bluetooth.currentLockSetting.lockFeature.autoLock === 1"
      @click="toJump('autoLock')"
    >
      <view class="item-title">自动闭锁</view>
      <view class="flex items-center">
        <view class="mr-2 max-w-400">
          {{
            $bluetooth.currentLockSetting.lockSettingInfo.autoLock === 1
              ? $bluetooth.currentLockSetting.lockSettingInfo.autoLockSecond + 's'
              : '已关闭'
          }}
        </view>
        <up-icon name="arrow-right"></up-icon>
      </view>
    </view>
    <view
      v-if="
        $bluetooth.currentLockSetting.lockFeature.lockSound === 1 &&
        $bluetooth.currentLockSetting.lockBasicInfo.keyRight === 1
      "
      class="py-3 px-4 bg-white flex items-center justify-between text-base mb-4rpx"
      @click="toJump('lockSound')"
    >
      <view class="item-title">锁声音</view>
      <view class="flex items-center">
        <view class="mr-2 max-w-400">
          {{
            $bluetooth.currentLockSetting.lockSettingInfo.lockSound === 1
              ? volumeList[$bluetooth.currentLockSetting.lockSettingInfo.lockSoundVolume - 1]
              : '已关闭'
          }}
        </view>
        <up-icon name="arrow-right"></up-icon>
      </view>
    </view>
    <view
      v-if="
        $bluetooth.currentLockSetting.lockFeature.antiPrySwitch === 1 &&
        $bluetooth.currentLockSetting.lockBasicInfo.keyRight === 1
      "
      class="py-3 px-4 bg-white flex items-center justify-between text-base"
      @click="toUpdateSetting('antiPrySwitch')"
    >
      <view class="item-title">防撬报警</view>
      <view class="flex items-center">
        <view class="mr-2 max-w-400">
          {{
            $bluetooth.currentLockSetting.lockSettingInfo.antiPrySwitch === 1 ? '已开启' : '已关闭'
          }}
        </view>
        <up-icon name="arrow-right"></up-icon>
      </view>
    </view>
    <view class="mt-2.5"></view>
    <view
      v-if="
        $bluetooth.currentLockSetting.lockFeature.remoteUnlock === 1 &&
        $bluetooth.currentLockSetting.lockBasicInfo.keyRight === 1
      "
      class="py-3 px-4 bg-white flex items-center justify-between text-base mb-4rpx"
      @click="toUpdateSetting('remoteUnlock')"
    >
      <view class="item-title">远程开锁</view>
      <view class="flex items-center">
        <view class="mr-2 max-w-400">
          {{
            $bluetooth.currentLockSetting.lockSettingInfo.remoteUnlock === 1 ? '已开启' : '已关闭'
          }}
        </view>
        <up-icon name="arrow-right"></up-icon>
      </view>
    </view>
    <view
      v-if="
        $bluetooth.currentLockSetting.lockFeature.resetSwitch === 1 &&
        $bluetooth.currentLockSetting.lockBasicInfo.isLockOwner === 1
      "
      class="py-3 px-4 bg-white flex items-center justify-between text-base"
      @click="toUpdateSetting('resetSwitch')"
    >
      <view class="item-title">重置键</view>
      <view class="flex items-center">
        <view class="mr-2 max-w-400">
          {{
            $bluetooth.currentLockSetting.lockSettingInfo.resetSwitch === 1 ? '已开启' : '已关闭'
          }}
        </view>
        <up-icon name="arrow-right"></up-icon>
      </view>
    </view>
    <view class="mt-2.5"></view>
    <view
      v-if="
        $bluetooth.currentLockSetting.lockFeature.d3Face === 1 &&
        $bluetooth.currentLockSetting.lockBasicInfo.keyRight === 1
      "
      class="py-3 px-4 bg-white flex items-center justify-between text-base"
      @click="toJump('faceSetting')"
    >
      <view class="item-title">面容开锁</view>
      <view><up-icon name="arrow-right"></up-icon></view>
    </view>
    <view
      v-if="$bluetooth.currentLockSetting.lockBasicInfo.keyRight === 1"
      class="py-3 px-4 bg-white flex items-center justify-between text-base mt-4rpx"
      @click="toJump('messageReminder')"
    >
      <view class="item-title">消息提醒</view>
      <view><up-icon name="arrow-right"></up-icon></view>
    </view>
    <view
      v-if="
        $bluetooth.currentLockSetting.lockFeature.isSupportCatEye !== 1 &&
        $bluetooth.currentLockSetting.lockBasicInfo.keyRight === 1
      "
      class="py-3 px-4 bg-white flex items-center justify-between text-base mt-4rpx"
      @click="toJump('catEye')"
    >
      <view class="item-title">猫眼设置</view>
      <view><up-icon name="arrow-right"></up-icon></view>
    </view>
    <view
      v-if="
        $bluetooth.currentLockSetting.lockFeature.openDirection === 1 &&
        $bluetooth.currentLockSetting.lockBasicInfo.keyRight === 1
      "
      class="py-3 px-4 bg-white flex items-center justify-between text-base mt-4rpx"
      @click="toJump('openDirection')"
    >
      <view class="item-title">开门方向设置</view>
      <view><up-icon name="arrow-right"></up-icon></view>
    </view>
    <view
      v-if="
        $bluetooth.currentLockSetting.lockFeature.motorTorsion === 1 &&
        $bluetooth.currentLockSetting.lockBasicInfo.keyRight === 1
      "
      class="py-3 px-4 bg-white flex items-center justify-between text-base mt-4rpx"
      @click="toJump('motorTorsion')"
    >
      <view class="item-title">电机功率设置</view>
      <view><up-icon name="arrow-right"></up-icon></view>
    </view>
    <view class="mt-2.5"></view>
    <view
      class="py-3 px-4 bg-white !py-2 flex items-center justify-between text-base"
      v-if="
        $bluetooth.currentLockSetting.lockFeature.unlockReminder === 1 &&
        $bluetooth.currentLockSetting.lockBasicInfo.isLockOwner === 1
      "
    >
      <view class="item-title">开锁提醒</view>
      <switch
        @click="changeSetting('unlockReminder')"
        :checked="$bluetooth.currentLockSetting.lockSettingInfo.unlockReminder === 1"
        class="transform-scale-90"
        :disabled="true"
        color="#002ce5"
      />
    </view>
    <view
      v-if="
        $bluetooth.currentLockSetting.lockFeature.appUnlockOnline === 1 &&
        $bluetooth.currentLockSetting.lockBasicInfo.isLockOwner === 1
      "
      class="py-3 px-4 bg-white !py-2 flex items-center justify-between text-base mt-4rpx"
    >
      <view class="item-title">开锁时是否需联网</view>
      <switch
        @click="changeSetting('appUnlockOnline')"
        :checked="$bluetooth.currentLockSetting.lockSettingInfo.appUnlockOnline === 1"
        class="transform-scale-90"
        :disabled="true"
        color="#002ce5"
      />
    </view>
    <view
      class="py-3 px-4 bg-white flex items-center justify-between text-base mt-2.5"
      @click="toJump('lockDate')"
    >
      <view class="item-title">锁时间</view>
      <view><up-icon name="arrow-right"></up-icon></view>
    </view>
    <view
      v-if="$bluetooth.currentLockSetting.lockBasicInfo.keyRight === 1"
      class="py-3 px-4 bg-white flex items-center justify-between text-base mt-4rpx"
      @click="toJump('uploadLockData')"
    >
      <view class="item-title">上传数据</view>
      <view><up-icon name="arrow-right"></up-icon></view>
    </view>
    <!--    <view class="py-3 px-4 bg-white flex items-center justify-between text-base mt-4rpx">-->
    <!--      <view class="item-title">锁升级</view>-->
    <!--      <view><up-icon name="arrow-right"></up-icon></view>-->
    <!--    </view>-->
    <view
      class="mt-4 rounded-3xl w-600 h-80 line-height-80rpx text-center mx-75rpx bg-#ec433c text-white text-xl font-bold"
      @click="deleteLock"
      >删除</view
    >
    <up-modal
      :show="showModal"
      title="是否删除授权管理员钥匙？"
      :showCancelButton="true"
      width="600rpx"
      @cancel="cancelModal"
      @confirm="confirmModal"
    >
      <view class="slot-content" @click="changeRadio">
        <view style="display: flex; align-items: center">
          <radio :checked="checked"></radio>
          <view>同时删除其发送的所有钥匙，钥匙删除后不能恢复</view>
        </view>
      </view>
    </up-modal>
  </view>
</template>

<script setup>
  import { onMounted, ref } from 'vue'
  import { useBluetoothStore } from '@/stores/bluetooth'
  import { useUserStore } from '@/stores/user'
  import { deleteLockRequest } from '@/api/lock'
  import { useLockStore } from '@/stores/lock'
  import { deleteKeyRequest } from '@/api/key'
  import { useBasicStore } from '@/stores/basic'
  import { getLockSettingRequest, updateLockSettingRequest } from '@/api/setting'

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

  const showModal = ref(false)
  const checked = ref(false)
  const requestFinished = ref(false)

  const pending = ref(false)

  const volumeList = ['低', '较低', '中', '较高', '高']

  onMounted(async () => {
    uni.showLoading({
      title: '加载中'
    })
    const { code, data, message } = await getLockSettingRequest({
      lockId: $bluetooth.currentLockInfo.lockId
    })
    uni.hideLoading()
    if (code === 0) {
      requestFinished.value = true
      $bluetooth.updateCurrentLockSetting(data)
    } else {
      uni.showToast({
        title: message,
        icon: 'none'
      })
    }
  })

  const toUpdateSetting = key => {
    $basic.routeJump({
      name: 'updateSetting',
      params: {
        key
      },
      events: {
        changeSetting() {
          changeSetting(key)
        }
      }
    })
  }

  const changeSetting = async key => {
    if (pending.value) return
    pending.value = true
    uni.showLoading({
      title: '更新中'
    })
    let featureBit
    if (key === 'unlockReminder') {
      featureBit = 47
    } else if (key === 'appUnlockOnline') {
      featureBit = 55
    } else if (key === 'remoteUnlock') {
      featureBit = 28
    } else if (key === 'resetSwitch') {
      featureBit = 31
    } else if (key === 'antiPrySwitch') {
      featureBit = 30
    }
    const { code } = await $bluetooth.updateSetting({
      keyId: $bluetooth.keyId.toString(),
      uid: $user.userInfo.uid.toString(),
      featureBit,
      featureEnable: $bluetooth.currentLockSetting.lockSettingInfo[key] === 1 ? 0 : 1,
      withParams: false
    })
    $bluetooth.closeBluetoothConnection()
    if (code === 0) {
      const { code, message } = await updateLockSettingRequest({
        lockId: $bluetooth.currentLockInfo.lockId,
        [key]: $bluetooth.currentLockSetting.lockSettingInfo[key] === 1 ? 0 : 1
      })
      pending.value = false
      uni.hideLoading()
      if (code === 0) {
        $bluetooth.updateCurrentLockSetting({
          ...$bluetooth.currentLockSetting,
          lockSettingInfo: {
            ...$bluetooth.currentLockSetting.lockSettingInfo,
            [key]: $bluetooth.currentLockSetting.lockSettingInfo[key] === 1 ? 0 : 1
          }
        })
        $lock.updateLockSearch({
          ...$lock.lockSearch,
          pageNo: 1
        })
        $lock.getLockList($lock.lockSearch)
        uni.showToast({
          title: '更新成功',
          icon: 'none'
        })
      } else {
        uni.showToast({
          title: message,
          icon: 'none'
        })
      }
    } else {
      pending.value = false
      uni.hideLoading()
      uni.showToast({
        title: '更新失败，请保持在锁附近',
        icon: 'none'
      })
    }
  }

  const toJump = name => {
    $basic.routeJump({
      name
    })
  }

  const changeRadio = () => {
    checked.value = !checked.value
  }

  const cancelModal = () => {
    showModal.value = false
    checked.value = false
  }

  const confirmModal = async () => {
    uni.showLoading({
      title: '删除中',
      mask: true
    })
    const { code } = await deleteKeyRequest({
      keyId: $lock.keyId,
      includeUnderlings: checked.value ? 1 : 0
    })
    showModal.value = false
    if (code === 0) {
      uni.hideLoading()
      $lock.updateLockSearch({
        ...$lock.lockSearch,
        pageNo: 1
      })
      $lock.getLockList($lock.lockSearch)
      $basic.backAndToast('删除成功', 2)
    } else {
      uni.hideLoading()
      uni.showToast({
        title: 'message',
        icon: 'none'
      })
    }
  }

  const deleteLock = async () => {
    const netWork = await $basic.getNetworkType()
    if (!netWork) {
      return
    }
    if (
      $bluetooth.currentLockInfo.userType !== 110301 &&
      $bluetooth.currentLockInfo.keyRight === 1
    ) {
      showModal.value = true
      return
    }
    const message =
      $bluetooth.currentLockInfo.userType === 110301
        ? '删除锁后，所有信息都会一起删除，确定删除锁吗？'
        : '确定删除该钥匙吗？'
    uni.showModal({
      title: '提示',
      content: message,
      async success(res) {
        if (res.confirm) {
          uni.showLoading({
            title: '删除中'
          })
          if ($bluetooth.currentLockInfo.userType === 110301) {
            const { code: resetDeviceCode } = await $bluetooth.resetDevice({
              name: $bluetooth.currentLockInfo.name,
              authUid: $user.userInfo.uid.toString(),
              keyId: $bluetooth.keyId.toString()
            })
            if (resetDeviceCode === 0 || resetDeviceCode === -2) {
              const { code } = await deleteLockRequest({
                lockId: $bluetooth.currentLockInfo.lockId
              })
              if (code === 0) {
                uni.hideLoading()
                $lock.updateLockSearch({
                  ...$lock.lockSearch,
                  pageNo: 1
                })
                $lock.getLockList($lock.lockSearch)
                $basic.backAndToast('删除成功', 2)
              } else {
                uni.hideLoading()
                uni.showToast({
                  title: 'message',
                  icon: 'none'
                })
              }
            } else if (resetDeviceCode === -1) {
              uni.hideLoading()
              uni.showToast({
                title: '删除失败，请保持在锁附近',
                icon: 'none'
              })
            }
          } else {
            const { code } = await deleteKeyRequest({
              keyId: $bluetooth.keyId
            })
            if (code === 0) {
              uni.hideLoading()
              $lock.updateLockSearch({
                ...$lock.lockSearch,
                pageNo: 1
              })
              $lock.getLockList($lock.lockSearch)
              $basic.backAndToast('删除成功', 2)
            } else {
              uni.hideLoading()
              uni.showToast({
                title: 'message',
                icon: 'none'
              })
            }
          }
        }
      }
    })
  }
</script>

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