<template>
  <view>
    <view v-if="info">
      <view class="item" @click="() => $refs.modalInput.open()">
        <view class="item-title">姓名</view>
        <view class="flex items-center">
          <view class="item-content mr-2">{{ info.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="info.keyType === 1" class="mr-2">永久</view>
          <view v-else-if="info.keyType === 2" class="mr-2 w-400 text-right">
            <view class="item-content">{{ timeFormat(info.startDate, 'yyyy-mm-dd h:M') }}</view>
            <view class="item-content">{{ timeFormat(info.endDate, 'yyyy-mm-dd h:M') }}</view>
          </view>
          <view v-else class="mr-2">
            <view class="item-content">{{ timeFormat(info.startDate, 'yyyy-mm-dd') }}</view>
            <view class="item-content">{{ timeFormat(info.endDate, 'yyyy-mm-dd') }}</view>
          </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">{{ info.username }}</view>
      </view>
      <view class="item" style="margin-top: 2rpx">
        <view class="item-title">添加者</view>
        <view class="item-content">{{ info.senderUsername }}</view>
      </view>
      <view class="item" style="margin-top: 2rpx">
        <view class="item-title">发送时间</view>
        <view class="item-content">{{ timeFormat(info.sendDate, 'yyyy-mm-dd h:M') }}</view>
      </view>
      <view class="item !py-2" style="margin-top: 20rpx">
        <view class="item-title">仅管理自己创建的用户</view>
        <switch
          :checked="info.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="[info.keyStatus === 110405 ? 'text-#63b8af' : 'text-red']" @click="freeze">{{
          info.keyStatus === 110405 ? '解冻' : '冻结'
        }}</view>
        <view :class="[info.keyRight === 1 ? 'text-red' : 'text-#63b8af']" @click="authorize">{{
          info.keyRight === 1 ? '取消授权管理员' : '授权管理员'
        }}</view>
      </view>
      <view class="button" @click="showModal = true">删除</view>
      <up-modal
        :show="showModalFreeze"
        title="提示"
        :showCancelButton="true"
        width="600rpx"
        @cancel="cancelModalFreeze"
        @confirm="confirmModalFreeze"
      >
        <view v-if="info.keyRight === 1" class="slot-content" @click="changeRadioFreeze">
          <view style="display: flex; align-items: center">
            <radio :checked="checkedFreeze"></radio>
            <view>同时{{ info.keyStatus === 110405 ? '解冻' : '冻结' }}其发送的钥匙</view>
          </view>
        </view>
        <view v-else class="slot-content">
          <view>{{ info.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>{{
            info.keyRight === 1
              ? '取消授权会在用户APP连网后生效'
              : '授权用户拥有管理员的大部分权限，比如发送要是、发送密码'
          }}</view>
        </view>
      </up-modal>
      <ModalInput
        ref="modalInput"
        title="请输入姓名"
        :autoClose="false"
        placeholder="请输入姓名"
        :value="info.keyName"
        @confirm="changeName"
      />
    </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 { getCurrentInstance, ref } from 'vue'
  import { onLoad } from '@dcloudio/uni-app'
  import { timeFormat } from 'uview-plus'
  import {
    authorizeKeyRequest,
    deleteKeyRequest,
    freezeKeyRequest,
    getKeyRequest,
    unauthorizeKeyRequest,
    unfreezeKeyRequest,
    updateKeyDateRequest,
    updateKeyNameRequest
  } from '@/api/key'
  import { useBasicStore } from '@/stores/basic'
  import { useBluetoothStore } from '@/stores/bluetooth'

  const instance = getCurrentInstance().proxy
  const eventChannel = instance.getOpenerEventChannel()

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

  const info = ref(null)

  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 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: info.value.keyId,
      keyNameForAdmin: name
    })
    pending.value = false
    if (code === 0) {
      modalInput.value.close()
      eventChannel.emit('refresherList', {})
      info.value.keyName = name
      uni.showToast({
        title: '更新成功',
        icon: 'none'
      })
    } else {
      uni.showToast({
        title: message,
        icon: 'none'
      })
    }
  }

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

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

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

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

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

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

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

  onLoad(options => {
    if (options.info) {
      info.value = JSON.parse(options.info)
      console.log(info.value)
    }
  })

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

  const updateTime = () => {
    $basic.routeJump({
      name: 'temporaryDate',
      params: {
        info: JSON.stringify({ ...info.value, type: 'key' })
      },
      events: {
        refresh() {
          eventChannel.emit('refresherList', {})
          getKeyRequest({
            keyId: info.value.keyId
          }).then(res => {
            info.value = {
              ...res.data,
              keyId: info.value.keyId
            }
          })
        }
      }
    })
  }

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

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

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

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

<style lang="scss" scoped>
  .item-title {
    width: 350rpx;
  }

  .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>
