<template>
  <view>
    <view class="font-bold text-base bg-white">
      <view class="border-b-solid border-b-1 border-b-gray-200" @click="showStartDate = true">
        <view class="mx-3 flex items-center h-100">
          <view class="w-168">生效时间</view>
          <view class="ml-a flex items-center">
            <view v-if="startDate" class="mr-2">
              <view>{{ timeFormat(startDate, 'yyyy-mm-dd h:M') }}</view>
            </view>
            <up-icon name="arrow-right"></up-icon>
          </view>
        </view>
      </view>
      <view>
        <view class="mx-3 flex items-center h-100" @click="showEndDate = true">
          <view class="w-168">失效时间</view>
          <view class="ml-a flex items-center">
            <view v-if="endDate" class="mr-2">
              <view>{{ timeFormat(endDate, 'yyyy-mm-dd h:M') }}</view>
            </view>
            <up-icon name="arrow-right"></up-icon>
          </view>
        </view>
      </view>
    </view>
    <view
      :class="[
        canSubmit ? 'bg-[#4777ee]' : 'bg-[#9d9da3]',
        'mx-4',
        'h-100',
        'text-white',
        'text-center',
        'font-bold',
        'mt-4',
        'flex',
        'items-center',
        'justify-center'
      ]"
      style="border-radius: 50rpx"
      @click="save"
      >保存</view
    >
    <up-datetime-picker
      :hasInput="false"
      :show="showStartDate"
      v-model="defaultStartDate"
      mode="datetime"
      closeOnClickOverlay
      :visibleItemCount="5"
      @close="showStartDate = false"
      @confirm="confirmDate('start', $event)"
      @cancel="showStartDate = false"
    ></up-datetime-picker>
    <up-datetime-picker
      :hasInput="false"
      :show="showEndDate"
      v-model="defaultEndDate"
      mode="datetime"
      closeOnClickOverlay
      :visibleItemCount="5"
      @close="showEndDate = false"
      @confirm="confirmDate('end', $event)"
      @cancel="showEndDate = false"
    ></up-datetime-picker>
  </view>
</template>

<script setup>
  import { timeFormat } from 'uview-plus'
  import { computed, getCurrentInstance, ref } from 'vue'
  import { onLoad } from '@dcloudio/uni-app'
  import { useBluetoothStore } from '@/stores/bluetooth'
  import { useUserStore } from '@/stores/user'
  import { updateCardRequest } from '@/api/card'
  import { useBasicStore } from '@/stores/basic'
  import { updateFingerprintRequest } from '@/api/fingerprint'
  import { updateRemoteRequest } from '@/api/remote'
  import { updateFaceRequest } from '@/api/face'
  import { updatePalmVeinRequest } from '@/api/palmVein'
  import { updateKeyDateRequest } from '@/api/key'
  import { updatePasswordRequest } from '@/api/keyboardPwd'

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

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

  const showStartDate = ref(false)
  const showEndDate = ref(false)

  const info = ref(null)

  const startDate = ref(null)
  const endDate = ref(null)

  const defaultStartDate = ref(0)
  const defaultEndDate = ref(0)

  const pending = ref(false)

  const canSubmit = computed(() => {
    return startDate.value && endDate.value
  })

  onLoad(options => {
    if (options.info) {
      const data = JSON.parse(options.info)
      if (data.startDate) {
        startDate.value = data.startDate
        endDate.value = data.endDate === 0 ? data.startDate : data.endDate
        info.value = data
        defaultStartDate.value = data.startDate
        defaultEndDate.value = data.endDate === 0 ? data.startDate : data.endDate
      }
    }
  })

  const save = async () => {
    if (!canSubmit.value) {
      return
    }
    if (startDate.value >= endDate.value) {
      uni.showToast({
        title: '失效日期需晚于生效日期',
        icon: 'none'
      })
      return
    }

    if (endDate.value <= new Date().getTime()) {
      uni.showToast({
        title: '失效时间需晚于当前时间',
        icon: 'none'
      })
      return
    }

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

    if (pending.value) {
      return
    }

    pending.value = true

    uni.showLoading({
      title: '更新中'
    })
    if (info.value.type === 'password') {
      const params = {
        keyId: $bluetooth.keyId.toString(),
        uid: $user.userInfo.uid.toString(),
        pwdNo: info.value.pwdUserNo,
        operate: 1,
        isAdmin: info.value.pwdRight,
        pwd: info.value.keyboardPwd,
        userCountLimit: 0xffff,
        startTime: Math.floor(startDate.value / 1000),
        endTime: Math.floor(endDate.value / 1000)
      }
      const { code, data } = await $bluetooth.setLockPassword(params)

      if (code === 0) {
        const { code, message } = await updatePasswordRequest({
          lockId: $bluetooth.currentLockInfo.lockId,
          keyboardPwdId: info.value.keyboardPwdId,
          startDate: startDate.value,
          endDate: endDate.value,
          keyboardPwdType: 3,
          changeType: 1
        })
        uni.hideLoading()
        pending.value = false
        if (code === 0) {
          eventChannel.emit('refresh', {})
          $basic.backAndToast('更新成功')
        } 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'
          })
        }
      }
    } else if (info.value.type === 'key') {
      const data = await updateKeyDateRequest({
        lockId: $bluetooth.currentLockInfo.lockId,
        keyId: info.value.keyId,
        keyType: 2,
        startDate: startDate.value,
        endDate: endDate.value
      })
      uni.hideLoading()
      pending.value = false
      if (data.code === 0) {
        eventChannel.emit('refresh', {})
        $basic.backAndToast('更新成功')
      } else {
        uni.showToast({
          title: data.message,
          icon: 'none'
        })
      }
    } else {
      const { code } = await $bluetooth.registerAuthentication({
        type: info.value.type,
        operate: 1,
        isAdmin: info.value.type,
        isForce: info.value.isForce,
        isRound: 0,
        weekDays: [],
        no: info.value[`${info.value.type}Number`],
        userCountLimit: 0xffff,
        keyId: $bluetooth.keyId.toString(),
        uid: $user.userInfo.uid.toString(),
        startDate: startDate.value,
        endDate: endDate.value
      })
      if (code === 0) {
        let data
        if (info.value.type === 'card') {
          data = await updateCardRequest({
            lockId: $bluetooth.currentLockInfo.lockId,
            cardId: info.value.cardId,
            cardType: 2,
            startDate: startDate.value,
            endDate: endDate.value,
            changeType: 1
          })
        } else if (info.value.type === 'fingerprint') {
          data = await updateFingerprintRequest({
            lockId: $bluetooth.currentLockInfo.lockId,
            fingerprintId: info.value.fingerprintId,
            fingerprintType: 2,
            startDate: startDate.value,
            endDate: endDate.value,
            changeType: 1
          })
        } else if (info.value.type === 'remote') {
          data = await updateRemoteRequest({
            lockId: $bluetooth.currentLockInfo.lockId,
            remoteId: info.value.remoteId,
            remoteType: 2,
            startDate: startDate.value,
            endDate: endDate.value,
            changeType: 1
          })
        } else if (info.value.type === 'face') {
          data = await updateFaceRequest({
            lockId: $bluetooth.currentLockInfo.lockId,
            faceId: info.value.faceId,
            faceType: 2,
            startDate: startDate.value,
            endDate: endDate.value,
            changeType: 1
          })
        } else if (info.value.type === 'palmVein') {
          data = await updatePalmVeinRequest({
            lockId: $bluetooth.currentLockInfo.lockId,
            palmVeinId: info.value.palmVeinId,
            palmVeinType: 2,
            startDate: startDate.value,
            endDate: endDate.value,
            changeType: 1
          })
        }
        uni.hideLoading()
        pending.value = false
        if (data.code === 0) {
          eventChannel.emit('refresh', {})
          $basic.backAndToast('更新成功')
          uni.showToast({
            title: '更新成功',
            icon: 'none'
          })
        } else {
          uni.showToast({
            title: data.message,
            icon: 'none'
          })
        }
      } else {
        pending.value = false
        uni.hideLoading()
        uni.showToast({
          title: '操作失败，请重试',
          icon: 'none'
        })
      }
    }
  }

  const confirmDate = (type, date) => {
    if (type === 'start') {
      startDate.value = date.value
      showStartDate.value = false
    } else {
      endDate.value = date.value
      showEndDate.value = false
    }
  }
</script>

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