<template>
  <view>
    <view class="item" @click="() => $refs.modalInput.open()">
      <view class="item-title" style="width: 350rpx">姓名</view>
      <view class="flex items-center">
        <view class="item-content mr-2">{{ $lock.currentKeyInfo.keyName }}</view>
        <up-icon name="arrow-right"></up-icon>
      </view>
    </view>
    <view class="item" style="margin-top: 2rpx" @click="updateTime">
      <view class="item-title">有效期</view>
      <view class="flex items-center">
        <view v-if="$lock.currentKeyInfo.keyType === 1" class="mr-2">永久</view>
        <view v-else-if="$lock.currentKeyInfo.keyType === 3">单次</view>
        <view v-else-if="$lock.currentKeyInfo.keyType === 4" class="mr-2">
          <view class="item-content">{{
            timeFormat($lock.currentKeyInfo.startDate, 'yyyy-mm-dd')
          }}</view>
          <view class="item-content">{{
            timeFormat($lock.currentKeyInfo.endDate, 'yyyy-mm-dd')
          }}</view>
        </view>
        <view v-else class="mr-2">
          <view class="item-content">{{
            timeFormat($lock.currentKeyInfo.startDate, 'yyyy-mm-dd h:M')
          }}</view>
          <view class="item-content">{{
            timeFormat($lock.currentKeyInfo.endDate, 'yyyy-mm-dd h:M')
          }}</view>
        </view>
        <up-icon v-if="$lock.currentKeyInfo.keyType !== 3" name="arrow-right"></up-icon>
      </view>
    </view>
    <view
      v-if="$lock.currentKeyInfo.keyType === 4"
      class="item"
      style="margin-top: 2rpx"
      @click="updateTime"
    >
      <view class="item-title">有效日</view>
      <view class="flex items-center">
        <view class="item-content mr-2">{{
          $lock.convertWeekDaysToChineseString($lock.currentKeyInfo.weekDays)
        }}</view>
        <up-icon name="arrow-right"></up-icon>
      </view>
    </view>
    <view
      class="item"
      v-if="$lock.currentKeyInfo.keyType === 4"
      style="margin-top: 2rpx"
      @click="updateTime"
    >
      <view class="item-title">有效时间</view>
      <view class="flex items-center">
        <view class="item-content mr-2">
          {{ timeFormat($lock.currentKeyInfo.startDate, 'h:M') }}～{{
            timeFormat($lock.currentKeyInfo.endDate, 'h:M')
          }}</view
        >
        <up-icon name="arrow-right"></up-icon>
      </view>
    </view>
    <view class="item" style="margin-top: 20rpx">
      <view class="item-title">接收者</view>
      <view class="item-content">{{ $lock.currentKeyInfo.username }}</view>
    </view>
    <view class="item" style="margin-top: 2rpx">
      <view class="item-title">发送人</view>
      <view class="item-content">{{ $lock.currentKeyInfo.senderUsername }}</view>
    </view>
    <view class="item" style="margin-top: 2rpx">
      <view class="item-title">发送时间</view>
      <view class="item-content">{{
        timeFormat($lock.currentKeyInfo.sendDate, 'yyyy-mm-dd h:M')
      }}</view>
    </view>
    <view class="item !py-2" style="margin-top: 20rpx" v-if="$lock.currentKeyInfo.keyRight === 1">
      <view class="item-title">仅管理自己创建的用户</view>
      <switch
        :checked="$lock.currentKeyInfo.isOnlyManageSelf"
        class="transform-scale-90"
        @click="changeManageSelf"
        :disabled="true"
        color="#002ce5"
      />
    </view>
    <view class="item" style="margin-top: 20rpx" @click="toRecordList">
      <view class="item-title">操作记录</view>
      <up-icon name="arrow-right"></up-icon>
    </view>
    <view class="m-4 flex items-center justify-between text-base">
      <view
        :class="[$lock.currentKeyInfo.keyStatus === 110405 ? 'text-#63b8af' : 'text-red']"
        @click="freeze"
        >{{ $lock.currentKeyInfo.keyStatus === 110405 ? '解冻' : '冻结' }}</view
      >
      <view
        :class="[$lock.currentKeyInfo.keyRight === 1 ? 'text-red' : 'text-#63b8af']"
        @click="authorize"
        >{{ $lock.currentKeyInfo.keyRight === 1 ? '取消授权管理员' : '授权管理员' }}</view
      >
    </view>
    <view class="button" @click="deleteKey">删除</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>
    <up-modal
      :show="showModalFreeze"
      title="提示"
      :showCancelButton="true"
      width="600rpx"
      @cancel="cancelModalFreeze"
      @confirm="confirmModalFreeze"
    >
      <view
        v-if="$lock.currentKeyInfo.keyRight === 1"
        class="slot-content"
        @click="changeRadioFreeze"
      >
        <view style="display: flex; align-items: center">
          <radio :checked="checkedFreeze"></radio>
          <view
            >同时{{ $lock.currentKeyInfo.keyStatus === 110405 ? '解冻' : '冻结' }}其发送的钥匙</view
          >
        </view>
      </view>
      <view v-else class="slot-content">
        <view
          >{{
            $lock.currentKeyInfo.keyStatus === 110405 ? '取消冻结' : '冻结'
          }}会在用户APP连网后生效</view
        >
      </view>
    </up-modal>
    <up-modal
      :show="showModalAuthorize"
      title="提示"
      :showCancelButton="true"
      width="600rpx"
      @cancel="cancelModalAuthorize"
      @confirm="confirmModalAuthorize"
    >
      <view class="slot-content">
        <view>{{
          $lock.currentKeyInfo.keyRight === 1
            ? '取消授权会在用户APP连网后生效'
            : '授权用户拥有管理员的大部分权限，比如发送要是、发送密码'
        }}</view>
      </view>
    </up-modal>
    <ModalInput
      ref="modalInput"
      title="请输入姓名"
      :autoClose="false"
      placeholder="请输入姓名"
      :value="$lock.currentKeyInfo.keyName"
      @confirm="changeName"
    />
  </view>
</template>

<script setup>
  import { timeFormat } from 'uview-plus'
  import { ref } from 'vue'
  import { useLockStore } from '@/stores/lock'
  import {
    authorizeKeyRequest,
    deleteKeyRequest,
    freezeKeyRequest,
    getKeyRequest,
    unauthorizeKeyRequest,
    unfreezeKeyRequest,
    updateKeyDateRequest,
    updateKeyNameRequest
  } from '@/api/key'
  import { useBasicStore } from '@/stores/basic'
  import { useBluetoothStore } from '@/stores/bluetooth'

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

  const showModal = ref(false)
  const showModalFreeze = ref(false)
  const showModalAuthorize = ref(false)
  const checked = ref(false)
  const checkedFreeze = ref(false)

  const modalInput = ref(null)

  const pending = ref(false)

  const freeze = async () => {
    showModalFreeze.value = true
  }

  const authorize = async () => {
    showModalAuthorize.value = true
  }

  const changeManageSelf = async () => {
    if (pending.value) return
    pending.value = true
    uni.showLoading({
      title: '更新中'
    })
    const { code, message } = await updateKeyDateRequest({
      lockId: $bluetooth.currentLockInfo.lockId,
      keyId: $lock.currentKeyInfo.keyId,
      keyType: $lock.currentKeyInfo.keyType,
      startDate: $lock.currentKeyInfo.startDate,
      endDate: $lock.currentKeyInfo.endDate,
      isOnlyManageSelf: $lock.currentKeyInfo.isOnlyManageSelf === 1 ? 0 : 1
    })
    pending.value = false
    uni.hideLoading()
    if (code === 0) {
      $lock.updateCurrentKeyInfo({
        ...$lock.currentKeyInfo,
        isOnlyManageSelf: $lock.currentKeyInfo.isOnlyManageSelf === 1 ? 0 : 1
      })
      $lock.updateKeySearch({
        ...$lock.keySearch,
        pageNo: 1
      })
      $lock.getKeyList($lock.keySearch)
      uni.showToast({
        title: '更新成功',
        icon: 'none'
      })
    } else {
      uni.showToast({
        title: message,
        icon: 'none'
      })
    }
  }

  const updateTime = () => {
    if ($lock.currentKeyInfo.keyType === 3) return
    $basic.routeJump({
      name:
        $lock.currentKeyInfo.keyType === 1 || $lock.currentKeyInfo.keyType === 2
          ? 'temporaryDate'
          : 'cycleDate',
      params: {
        info: JSON.stringify({ ...$lock.currentKeyInfo, type: 'key' })
      },
      events: {
        refresh() {
          $lock.updateKeySearch({
            ...$lock.keySearch,
            pageNo: 1
          })
          $lock.getKeyList($lock.keySearch)
          getKeyRequest({
            lockId: $bluetooth.currentLockInfo.lockId,
            keyId: $lock.currentKeyInfo.keyId
          }).then(res => {
            $lock.updateCurrentKeyInfo({
              ...res.data,
              keyId: $lock.currentKeyInfo.keyId
            })
          })
        }
      }
    })
  }

  const changeName = async name => {
    if (!name) {
      uni.showToast({
        title: '请输入姓名',
        icon: 'none'
      })
      return
    }
    if (pending.value) return
    pending.value = true
    const { code, message } = await updateKeyNameRequest({
      lockId: $bluetooth.currentLockInfo.lockId,
      keyId: $lock.currentKeyInfo.keyId,
      keyNameForAdmin: name
    })
    pending.value = false
    if (code === 0) {
      modalInput.value.close()
      $lock.updateKeySearch({
        ...$lock.keySearch,
        pageNo: 1
      })
      $lock.getKeyList($lock.keySearch)
      $lock.updateCurrentKeyInfo({
        ...$lock.currentKeyInfo,
        keyName: name
      })
      uni.showToast({
        title: '更新成功',
        icon: 'none'
      })
    } else {
      uni.showToast({
        title: message,
        icon: 'none'
      })
    }
  }

  const toRecordList = () => {
    $basic.routeJump({
      name: 'typeRecordList',
      params: {
        name: $lock.currentKeyInfo.keyName,
        key: 'keyId',
        id: $lock.currentKeyInfo.keyId
      }
    })
  }

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

  const cancelModalFreeze = () => {
    showModalFreeze.value = false
    checkedFreeze.value = false
  }

  const cancelModalAuthorize = () => {
    showModalAuthorize.value = false
  }

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

  const changeRadioFreeze = () => {
    checkedFreeze.value = !checkedFreeze.value
  }

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

  const confirmModalFreeze = async () => {
    uni.showLoading({
      title: '更新中',
      mask: true
    })
    const { code, message } =
      $lock.currentKeyInfo.keyStatus === 110405
        ? await unfreezeKeyRequest({
            keyId: $lock.currentKeyInfo.keyId,
            includeUnderlings: checkedFreeze.value ? 1 : 0
          })
        : await freezeKeyRequest({
            keyId: $lock.currentKeyInfo.keyId,
            includeUnderlings: checkedFreeze.value ? 1 : 0
          })
    if (code === 0) {
      showModalFreeze.value = false
      $lock.updateKeySearch({
        ...$lock.keySearch,
        pageNo: 1
      })
      $lock.getKeyList($lock.keySearch)
      uni.hideLoading()
      $basic.backAndToast($lock.currentKeyInfo.keyStatus === 110405 ? '解冻成功' : '冻结成功')
    } else {
      uni.hideLoading()
      uni.showToast({
        title: message,
        icon: 'none'
      })
    }
  }

  const confirmModalAuthorize = async () => {
    uni.showLoading({
      title: '更新中',
      mask: true
    })
    const { code, message } =
      $lock.currentKeyInfo.keyRight === 1
        ? await unauthorizeKeyRequest({
            keyId: $lock.currentKeyInfo.keyId
          })
        : await authorizeKeyRequest({
            keyId: $lock.currentKeyInfo.keyId
          })
    if (code === 0) {
      showModalAuthorize.value = false
      $lock.updateKeySearch({
        ...$lock.keySearch,
        pageNo: 1
      })
      $lock.getKeyList($lock.keySearch)
      uni.hideLoading()
      $basic.backAndToast($lock.currentKeyInfo.keyRight === 1 ? '取消授权成功' : '授权成功')
    } else {
      uni.hideLoading()
      uni.showToast({
        title: message,
        icon: 'none'
      })
    }
  }

  const deleteKey = async () => {
    if ($lock.currentKeyInfo.keyRight === 1) {
      showModal.value = true
      return
    }
    uni.showModal({
      title: '提示',
      content: '确定要删除该钥匙',
      async success(res) {
        if (res.confirm) {
          uni.showLoading({
            title: '删除中',
            mask: true
          })
          const { code: requestCode, message } = await deleteKeyRequest({
            keyId: $lock.currentKeyInfo.keyId
          })
          if (requestCode === 0) {
            uni.hideLoading()
            $lock.updateKeySearch({
              ...$lock.keySearch,
              pageNo: 1
            })
            await $lock.getKeyList($lock.keySearch)
            $lock.backAndToast('删除成功')
          } 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>
  .item {
    padding: 24rpx 32rpx;
    background-color: #ffffff;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 32rpx;
    font-weight: 500;
  }

  .tips {
    padding: 24rpx 32rpx;
    font-size: 24rpx;
    color: #999999;
  }

  .button {
    margin: 32rpx;
    width: 686rpx;
    height: 88rpx;
    background-color: #df282d;
    color: white;
    text-align: center;
    line-height: 88rpx;
    border-radius: 44rpx;
    font-weight: bold;
  }
</style>
