<template>
  <view>
    <view class="tabs">
      <up-tabs
        :list="tabs"
        lineWidth="40rpx"
        lineHeight="5rpx"
        :current="currentIndex"
        lineColor="#63b8af"
        @click="clickTab"
        :inactiveStyle="{ color: '#a3a3a3', fontSize: '32rpx', fontWeight: 'bold' }"
        :activeStyle="{ color: '#63b8af', fontSize: '32rpx', fontWeight: 'bold' }"
      >
      </up-tabs>
    </view>
    <swiper
      :style="{ height: deviceInfo.screenHeight - deviceInfo.safeArea.top - 44 + 'px' }"
      v-if="deviceInfo"
      :list="tabs"
      :autoplay="false"
      :circular="true"
      :current="currentIndex"
      @change="changeSwiper"
    >
      <swiper-item>
        <LockInput
          :value="permanentAccount"
          title="接收者"
          placeholder="请输入手机号或者邮箱"
          @change-input="changeAccount('permanent', $event)"
        ></LockInput>
        <LockInput
          :value="permanentName"
          title="姓名"
          placeholder="请输入"
          @change-input="changeName('permanent', $event)"
        ></LockInput>
        <view class="mt-3">
          <LockSwitch
            :value="permanentManageSelf"
            title="仅管理自己创建的用户"
            :tip="tip"
            @change="changeAdmin('permanent', $event)"
          ></LockSwitch>
        </view>
        <view class="text-sm text-#262626 mt-3 mx-4">
          授权管理员拥有操作这把锁的重要权限，请确保只发给你信任的人
        </view>
        <view class="button mt-5" @click="create('permanent')">发送</view>
      </swiper-item>
      <swiper-item :style="{ height: deviceInfo.windowHeight - 44 + 'px' }">
        <LockInput
          :value="temporaryAccount"
          title="接收者"
          placeholder="请输入手机号或者邮箱"
          @change-input="changeAccount('temporary', $event)"
        ></LockInput>
        <LockInput
          :value="temporaryName"
          title="姓名"
          placeholder="请输入"
          @change-input="changeName('temporary', $event)"
        ></LockInput>
        <view class="mt-3">
          <LockDatetimePicker
            title="生效时间"
            :value="temporaryStartTime"
            :minDate="minDate"
            :maxDate="maxDate"
            @change-time="changeDate('temporaryStartTime', $event)"
          ></LockDatetimePicker>
        </view>
        <view class="mt-3">
          <LockDatetimePicker
            title="失效时间"
            :value="temporaryEndTime"
            :minDate="minDate"
            :maxDate="maxDate"
            @change-time="changeDate('temporaryEndTime', $event)"
          ></LockDatetimePicker>
        </view>
        <view class="mt-3">
          <LockSwitch
            :value="temporaryManageSelf"
            title="仅管理自己创建的用户"
            :tip="tip"
            @change="changeAdmin('temporary', $event)"
          ></LockSwitch>
        </view>
        <view class="text-sm text-#262626 mt-3 mx-4">
          授权管理员拥有操作这把锁的重要权限，请确保只发给你信任的人
        </view>
        <view class="button mt-5" @click="create('temporary')">发送</view>
      </swiper-item>
    </swiper>
  </view>
</template>

<script setup>
  import { getCurrentInstance, ref } from 'vue'
  import { onLoad } from '@dcloudio/uni-app'
  import test from 'uview-plus/libs/function/test'
  import { useBasicStore } from '@/stores/basic'
  import { createKeyRequest } from '@/api/key'
  import { useBluetoothStore } from '@/stores/bluetooth'
  import { transportType } from '@/constant/transportType'

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

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

  const tabs = [
    {
      name: '永久'
    },
    {
      name: '限时'
    }
  ]

  const permanentAccount = ref('')
  const permanentName = ref('')
  const permanentManageSelf = ref(false)

  const temporaryAccount = ref('')
  const temporaryName = ref('')
  const temporaryStartTime = ref(Number(new Date()))
  const temporaryEndTime = ref(Number(new Date()))
  const temporaryManageSelf = ref(false)

  const minDate = ref(Number(new Date()))
  const maxDate = ref(Number(4133951940000))
  const currentIndex = ref(0)
  const deviceInfo = ref(null)

  const tip = '授权管理员只能查看和管理自己下发的钥匙、密码等权限'

  const pending = ref(false)

  onLoad(async () => {
    deviceInfo.value = await $basic.getDeviceInfo()
    temporaryStartTime.value = setTime()
    temporaryEndTime.value = setTime()
    minDate.value = Number(getNextFullHour())
    maxDate.value = Number(getFutureTimestamp())
  })

  const getNextFullHour = () => {
    const now = new Date()
    const currentHour = now.getHours()
    now.setHours(currentHour)
    now.setMinutes(0)
    now.setSeconds(0)
    now.setMilliseconds(0)

    return now
  }

  const getFutureTimestamp = () => {
    const currentDate = new Date()

    const year = currentDate.getFullYear()
    const month = currentDate.getMonth()
    const day = currentDate.getDate()

    const futureDate = new Date(year + 3, month, day, 23, 0, 0)

    return futureDate.getTime()
  }

  const setTime = () => {
    const now = new Date()
    now.setMinutes(0, 0, 0)

    return now.getTime()
  }

  const create = async (type, createUser = false) => {
    if (
      (type === 'temporary' && temporaryAccount.value === '') ||
      (type === 'permanent' && permanentAccount.value === '')
    ) {
      uni.showToast({
        title: '请输入接收者账号',
        icon: 'none'
      })
      return
    }
    if (
      (type === 'temporary' &&
        !(test.email(temporaryAccount.value) || test.mobile(temporaryAccount.value))) ||
      (type === 'permanent' &&
        !(test.email(permanentAccount.value) || test.mobile(permanentAccount.value)))
    ) {
      uni.showToast({
        title: '请输入格式正确的手机号或邮箱',
        icon: 'none'
      })
      return
    }

    if (type === 'temporary' && temporaryStartTime.value >= temporaryEndTime.value) {
      uni.showToast({
        title: '失效时间要大于生效时间',
        icon: 'none'
      })
      return
    }

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

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

    let params = {
      faceAuthentication: '2',
      isRemoteUnlock: '2',
      lockId: $bluetooth.currentLockInfo.lockId,
      keyRight: '1',
      remarks: '',
      countryCode: '86',
      createUser: '0'
    }
    if (createUser) {
      params.createUser = '1'
      params.usernameType = test.mobile(temporaryAccount.value) ? '1' : '2'
    }
    if (type === 'temporary') {
      params.keyNameForAdmin = temporaryName.value
      params.endDate = temporaryEndTime.value.toString()
      params.keyType = '2'
      params.receiverUsername = temporaryAccount.value
      params.startDate = temporaryStartTime.value.toString()
      params.isOnlyManageSelf = temporaryManageSelf.value ? 1 : 0
    } else {
      params.keyNameForAdmin = permanentName.value
      params.startDate = new Date().getTime().toString()
      params.endDate = '0'
      params.keyType = '1'
      params.receiverUsername = permanentAccount.value
      params.isOnlyManageSelf = permanentManageSelf.value ? 1 : 0
    }
    const { code, data, message } = await createKeyRequest(params)
    if (code === 0) {
      eventChannel.emit('refresherList', {})
      $basic.backAndToast('添加成功')
      if ($bluetooth.currentLockInfo.transportType === transportType.TRANSPORT_TENCENT_YUN) {
        $bluetooth.addLockUser({
          name: $bluetooth.currentLockInfo.name,
          keyId: $bluetooth.keyId,
          authUid: $bluetooth.currentLockInfo.uid.toString(),
          uid: data.receiverUid.toString(),
          openMode: 1,
          keyType: params.keyType,
          startDate: params.startDate.toString(),
          expireDate: params.endDate.toString(),
          useCountLimit: params.keyType === '3' ? 1 : 0xffff,
          isRound: params.keyType === '4' ? 1 : 0,
          weekRound:
            params.keyType === '4' ? $bluetooth.convertWeekdaysToNumber(params.weekDays) : 0,
          startHour: params.keyType === '4' ? new Date(params.startDate).getHours() : 0,
          startMin: params.keyType === '4' ? new Date(params.startDate).getMinutes() : 0,
          endHour: params.keyType === '4' ? new Date(params.endDate).getHours() : 0,
          endMin: params.keyType === '4' ? new Date(params.endDate).getMinutes() : 0,
          role: 1,
          password: (Math.floor(Math.random() * 900000) + 100000).toString()
        })
      }
    } else if (code === 425) {
      pending.value = false
      uni.showModal({
        title: '提示',
        content: `是否发送电子钥匙给未注册账号\n${params.receiverUsername}`,
        success: async res => {
          if (res.confirm) {
            await create(type, true)
          }
        }
      })
    } else {
      uni.showToast({
        title: message,
        icon: 'none'
      })
    }
    pending.value = false
  }

  const changeName = (type, event) => {
    if (type === 'permanent') {
      permanentName.value = event
    } else {
      temporaryName.value = event
    }
  }

  const changeDate = (type, event) => {
    if (type === 'temporaryStartTime') {
      temporaryStartTime.value = event
    } else {
      temporaryEndTime.value = event
    }
  }

  const changeAdmin = (type, event) => {
    if (type === 'permanent') {
      permanentManageSelf.value = event.detail.value
    } else {
      temporaryManageSelf.value = event.detail.value
    }
  }

  const changeAccount = (type, event) => {
    if (type === 'permanent') {
      permanentAccount.value = event
    } else {
      temporaryAccount.value = event
    }
  }

  const clickTab = data => {
    currentIndex.value = data.index
  }

  const changeSwiper = e => {
    currentIndex.value = e.detail.current
  }
</script>

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

<style lang="scss" scoped>
  .tabs {
    display: flex;
    justify-content: center;
  }

  .text {
    padding: 0 32rpx;
    margin-top: 40rpx;
    margin-bottom: 50rpx;
    font-size: 26rpx;
    color: #262626;
  }

  .button {
    width: 686rpx;
    height: 100rpx;
    margin-left: 32rpx;
    font-size: 32rpx;
    font-weight: bold;
    line-height: 100rpx;
    color: #fff;
    text-align: center;
    background-color: #63b8af;
    border-radius: 64rpx;
  }
</style>
