<template>
  <view>
    <view class="item" v-if="$lock.currentPasswordInfo.isCustom === 1">
      <view class="item-title">密码号</view>
      <view class="item-content">{{ $lock.currentPasswordInfo.pwdUserNo }}</view>
    </view>
    <view
      class="item"
      :style="{ marginTop: $lock.currentPasswordInfo.isCustom === 1 ? '2rpx' : '0' }"
      @click="() => $lock.currentPasswordInfo.isCustom === 1 && $refs.modalPassword.open()"
    >
      <view class="item-title">密码</view>
      <view class="flex items-center">
        <view class="item-content mr-2">{{ $lock.currentPasswordInfo.keyboardPwd }}</view>
        <up-icon v-if="$lock.currentPasswordInfo.isCustom === 1" name="arrow-right"></up-icon>
      </view>
    </view>
    <view class="item" style="margin-top: 2rpx" @click="() => $refs.modalInput.open()">
      <view class="item-title">姓名</view>
      <view class="flex items-center">
        <view class="item-content mr-2">{{ $lock.currentPasswordInfo.keyboardPwdName }}</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 class="mr-2">
          <view v-if="$lock.currentPasswordInfo.keyboardPwdType === 2">永久</view>
          <view v-else-if="$lock.currentPasswordInfo.keyboardPwdType <= 4">
            <view class="item-content">{{
              timeFormat($lock.currentPasswordInfo.startDate, 'yyyy-mm-dd h:M')
            }}</view>
            <view class="item-content">{{
              timeFormat($lock.currentPasswordInfo.endDate, 'yyyy-mm-dd h:M')
            }}</view>
          </view>
          <view v-else>
            {{ $lock.currentPasswordInfo.timeText.slice(0, -3) }}
          </view>
        </view>
        <up-icon v-if="$lock.currentPasswordInfo.isCustom === 1" name="arrow-right"></up-icon>
      </view>
    </view>
    <view class="item" style="margin-top: 20rpx">
      <view class="item-title">发送人</view>
      <view class="item-content">{{ $lock.currentPasswordInfo.senderUsername }}</view>
    </view>
    <view class="item" style="margin-top: 2rpx">
      <view class="item-title">发送时间</view>
      <view class="item-content">{{
        timeFormat($lock.currentPasswordInfo.sendDate, 'yyyy-mm-dd h:M')
      }}</view>
    </view>
    <view
      class="item !py-2"
      style="margin-top: 20rpx"
      v-if="$lock.currentPasswordInfo.isCustom === 1"
    >
      <view class="item-title">是否为管理员</view>
      <switch
        @click="disabled"
        :checked="$lock.currentPasswordInfo.pwdRight"
        class="transform-scale-90"
        :disabled="true"
        color="#002ce5"
      />
    </view>
    <view
      v-if="$lock.currentPasswordInfo.keyboardPwdType !== 4"
      class="item"
      style="margin-top: 20rpx"
      @click="toRecordList"
    >
      <view class="item-title">操作记录</view>
      <up-icon name="arrow-right"></up-icon>
    </view>
    <view class="text-sm text-#262626 mt-3 mx-4" v-if="$lock.currentPasswordInfo.isCustom !== 1">
      密码生成后，请在当日23:59前使用一次进行激活，否则过0点后未激活则失效。
    </view>
    <view class="button" @click="deletePassword">删除</view>
    <ModalInput
      ref="modalInput"
      title="请输入姓名"
      :autoClose="false"
      placeholder="请输入姓名"
      :value="$lock.currentPasswordInfo.keyboardPwdName"
      @confirm="changeName"
    />
    <ModalInput
      ref="modalPassword"
      title="修改密码"
      :autoClose="false"
      :maxlength="9"
      type="number"
      placeholder="密码为6-9位数字"
      :value="$lock.currentPasswordInfo.keyboardPwd"
      @confirm="changePassword"
    />
  </view>
</template>

<script setup>
  import { timeFormat } from 'uview-plus'
  import { ref } from 'vue'
  import test from 'uview-plus/libs/function/test'
  import { useLockStore } from '@/stores/lock'
  import {
    deletePsaawordRequest,
    getPasswordRequest,
    updatePasswordRequest
  } from '@/api/keyboardPwd'
  import { useBluetoothStore } from '@/stores/bluetooth'
  import { useUserStore } from '@/stores/user'
  import { useBasicStore } from '@/stores/basic'

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

  const modalInput = ref(null)
  const modalPassword = ref(null)
  const pending = ref(false)

  const disabled = () => {
    uni.showToast({
      title: '暂不支持修改',
      icon: 'none'
    })
  }

  const updateTime = () => {
    if ($lock.currentPasswordInfo.isCustom !== 1) return
    $basic.routeJump({
      name: 'temporaryDate',
      params: {
        info: JSON.stringify({ ...$lock.currentPasswordInfo, type: 'password' })
      },
      events: {
        refresh() {
          $lock.updatePasswordSearch({
            ...$lock.passwordSearch,
            pageNo: 1
          })
          $lock.getPasswordList($lock.passwordSearch)
          getPasswordRequest({
            lockId: $bluetooth.currentLockInfo.lockId,
            keyboardPwdId: $lock.currentPasswordInfo.keyboardPwdId
          }).then(res => {
            $lock.updateCurrentPasswordInfo({
              ...$lock.currentPasswordInfo,
              ...res.data,
              keyboardPwdType: res.data.type
            })
          })
        }
      }
    })
  }

  const changePassword = async password => {
    if (!test.rangeLength(password, [6, 9])) {
      uni.showToast({
        title: '密码为6-9位纯数字',
        icon: 'none'
      })
      return
    }

    const netWork = await $basic.getNetworkType()
    if (!netWork) {
      return
    }

    if (pending.value) return
    pending.value = true

    uni.showLoading({
      title: '更新中'
    })

    const params = {
      keyId: $bluetooth.keyId.toString(),
      uid: $user.userInfo.uid.toString(),
      pwdNo: $lock.currentPasswordInfo.pwdUserNo,
      operate: 1,
      isAdmin: $lock.currentPasswordInfo.pwdRight,
      pwd: password,
      userCountLimit: 0xffff,
      startTime: Math.floor($lock.currentPasswordInfo.startDate / 1000),
      endTime: Math.floor($lock.currentPasswordInfo.endDate / 1000)
    }
    const { code, data } = await $bluetooth.setLockPassword(params)

    if (code === 0) {
      const { code, message } = await updatePasswordRequest({
        lockId: $bluetooth.currentLockInfo.lockId,
        keyboardPwdId: $lock.currentPasswordInfo.keyboardPwdId,
        startDate: $lock.currentPasswordInfo.startDate,
        endDate: $lock.currentPasswordInfo.endDate,
        newKeyboardPwd: password,
        changeType: 1
      })
      uni.hideLoading()
      pending.value = false
      if (code === 0) {
        modalPassword.value.close()
        $lock.updateCurrentPasswordInfo({
          ...$lock.currentPasswordInfo,
          keyboardPwd: password
        })
        $lock.updatePasswordSearch({
          ...$lock.passwordSearch,
          pageNo: 1
        })
        $lock.getPasswordList($lock.passwordSearch)
        uni.showToast({
          title: '更新成功',
          icon: 'none'
        })
      } else {
        uni.showToast({
          title: message,
          icon: 'none'
        })
      }
    } else {
      uni.hideLoading()
      if (data.status === 0xff) {
        uni.showToast({
          title: '更新失败',
          icon: 'none'
        })
      } else if (data.status === 0xfe) {
        uni.showToast({
          title: '管理员已满',
          icon: 'none'
        })
      } else if (data.status === 0xfd) {
        uni.showToast({
          title: '用户已满',
          icon: 'none'
        })
      } else if (data.status === 0xfc) {
        uni.showToast({
          title: '密码已满',
          icon: 'none'
        })
      } else if (data.status === 0xfb) {
        uni.showToast({
          title: '密码已存在',
          icon: 'none'
        })
      } else {
        uni.showToast({
          title: '更新失败，请保持在锁附近',
          icon: 'none'
        })
      }
    }
  }

  const changeName = async name => {
    if (!name) {
      uni.showToast({
        title: '请输入姓名',
        icon: 'none'
      })
      return
    }
    if (pending.value) return
    pending.value = true
    const { code, message } = await updatePasswordRequest({
      lockId: $bluetooth.currentLockInfo.lockId,
      keyboardPwdId: $lock.currentPasswordInfo.keyboardPwdId,
      startDate: $lock.currentPasswordInfo.startDate,
      endDate: $lock.currentPasswordInfo.endDate,
      keyboardPwdName: name,
      changeType: 1
    })
    pending.value = false
    if (code === 0) {
      modalInput.value.close()
      $lock.updateCurrentPasswordInfo({
        ...$lock.currentPasswordInfo,
        keyboardPwdName: name
      })
      $lock.updatePasswordSearch({
        ...$lock.passwordSearch,
        pageNo: 1
      })
      $lock.getPasswordList($lock.passwordSearch)
      uni.showToast({
        title: '更新成功',
        icon: 'none'
      })
    } else {
      uni.showToast({
        title: message,
        icon: 'none'
      })
    }
  }

  const toRecordList = async () => {
    $basic.routeJump({
      name: 'typeRecordList',
      params: {
        name: $lock.currentPasswordInfo.keyboardPwdName,
        key: 'keyboardPwdId',
        id: $lock.currentPasswordInfo.keyboardPwdId
      }
    })
  }

  const deletePassword = async () => {
    const netWork = await $basic.getNetworkType()
    if (!netWork) {
      return
    }
    uni.showModal({
      title: '提示',
      content: '确定要删除该密码',
      async success(res) {
        if (res.confirm) {
          uni.showLoading({
            title: '删除中',
            mask: true
          })
          const timestamp = parseInt(new Date().getTime() / 1000, 10)
          const { code } = await $bluetooth.setLockPassword({
            keyId: $bluetooth.keyId.toString(),
            uid: $user.userInfo.uid.toString(),
            pwdNo: $lock.currentPasswordInfo.pwdUserNo,
            operate: $lock.currentPasswordInfo.isCustom === 1 ? 2 : 3,
            isAdmin: $lock.currentPasswordInfo.pwdRight,
            pwd: $lock.currentPasswordInfo.keyboardPwd,
            userCountLimit: 0xffff,
            startTime: timestamp,
            endTime: timestamp
          })
          $bluetooth.closeBluetoothConnection()
          if (code === 0) {
            const { code: requestCode, message } = await deletePsaawordRequest({
              lockId: $bluetooth.currentLockInfo.lockId,
              keyboardPwdId: $lock.currentPasswordInfo.keyboardPwdId,
              deleteType: 1
            })
            if (requestCode === 0) {
              uni.hideLoading()
              $lock.updatePasswordSearch({
                ...$lock.passwordSearch,
                pageNo: 1
              })
              $lock.getPasswordList($lock.passwordSearch)
              $basic.backAndToast('删除成功')
            } else {
              uni.hideLoading()
              uni.showToast({
                title: message,
                icon: 'none'
              })
            }
          } else if (code === -1) {
            uni.hideLoading()
            uni.showToast({
              title: '删除失败，请保持在锁附近',
              icon: 'none'
            })
          }
        }
      }
    })
  }
</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>
