<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="permanentName"
          title="姓名"
          placeholder="请输入"
          @change-input="changePermanentInput"
        ></LockInput>
        <view class="mt-3">
          <LockSwitch
            :value="false"
            title="是否为管理员"
            @change="changePermanentInput"
          ></LockSwitch>
        </view>
        <view class="mt-3 mb-3">
          <LockSwitch
            :value="false"
            title="胁迫卡"
            @change="changePermanentInput"
            :placeholder="placeholder"
          ></LockSwitch>
        </view>
        <view class="button" @click="createPassword('permanent')">下一步</view>
      </swiper-item>
      <swiper-item :style="{ height: deviceInfo.windowHeight - 44 + 'px' }">
        <LockInput
          :value="temporaryName"
          title="姓名"
          placeholder="请输入"
          @change-input="changeTemporaryInput"
        ></LockInput>
        <view class="mt-3">
          <LockDatetimePicker
            title="生效时间"
            :value="temporaryTime"
            :minDate="minDate"
            :maxDate="maxDate"
            type="datehour"
            @change-time="changeTemporaryTime"
          ></LockDatetimePicker>
        </view>
        <view class="mt-3">
          <LockDatetimePicker
            title="失效时间"
            :value="temporaryTime"
            :minDate="minDate"
            :maxDate="maxDate"
            type="datehour"
            @change-time="changeTemporaryTime"
          ></LockDatetimePicker>
        </view>
        <view class="mt-3">
          <LockSwitch
            :value="false"
            title="是否为管理员"
            @change="changePermanentInput"
          ></LockSwitch>
        </view>
        <view class="mt-3 mb-3">
          <LockSwitch
            :value="false"
            title="胁迫卡"
            @change="changePermanentInput"
            :placeholder="placeholder"
          ></LockSwitch>
        </view>
        <view class="button" @click="createPassword('temporary')">下一步</view>
      </swiper-item>
    </swiper>
  </view>
</template>

<script setup>
  import { ref } from 'vue'
  import { onLoad } from '@dcloudio/uni-app'
  import { createPsaawordRequest } from '@/api/keyboardPwd'
  import { useBasicStore } from '@/stores/basic'

  const $basic = useBasicStore()

  const tabs = [
    {
      name: '永久'
    },
    {
      name: '限时'
    }
  ]
  const permanentName = ref('')
  const temporaryName = ref('')
  const temporaryTime = ref(Number(new Date()))
  const minDate = ref(Number(new Date()))
  const maxDate = ref(Number(4133951940000))
  const currentIndex = ref(0)
  const deviceInfo = ref(null)
  const pending = ref(false)
  const placeholder =
    '当被胁迫要求强行开锁时，使用胁迫卡会触发报警，报警信息会推送给管理员，该功能需要锁联网。\n请不要将胁迫卡用于日常开锁'

  onLoad(async () => {
    deviceInfo.value = await $basic.getDeviceInfo()
    temporaryTime.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 createPassword = async type => {
    if (
      (type === 'temporary' && temporaryName.value === '') ||
      (type === 'permanent' && permanentName.value === '')
    ) {
      uni.showToast({
        title: '名称不能为空',
        icon: 'none'
      })
      return
    }

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

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

    let params = {
      lockId: this.currentLockInfo.lockId,
      isCoerced: 2,
      pwdRight: 0
    }
    if (type === 'temporary') {
      params.keyboardPwdName = this.temporaryName
      params.keyboardPwdType = 3
      params.startDate = new Date().getTime()
      params.endDate = this.temporaryTime
      params.hoursStart = 0
      params.hoursEnd = 0
    } else {
      params.startDate = 0
      params.endDate = 0
      params.keyboardPwdName = this.permanentName
      params.keyboardPwdType = 2
      params.hoursStart = 0
      params.hoursEnd = 0
    }
    const { code, data, message } = await createPsaawordRequest(params)
    if (code === 0) {
      uni.reportEvent('create_password', {})
      this.updatePasswordSearch({
        ...this.passwordSearch,
        pageNo: 1
      })
      this.getPasswordList(this.passwordSearch)
      uni.showModal({
        title: '密码生成成功',
        content: `密码：${data.keyboardPwd}`,
        cancelText: '复制',
        success: res => {
          if (res.confirm) {
            uni.navigateBack()
          } else {
            uni.setClipboardData({
              data: data.keyboardPwd,
              success: () => {
                $basic.backAndToast('复制成功')
              }
            })
          }
        }
      })
    } else {
      uni.showToast({
        title: message,
        icon: 'none'
      })
    }
    pending.value = false
  }

  const changePermanentInput = e => {
    permanentName.value = e
  }

  const changeTemporaryInput = e => {
    temporaryName.value = e
  }

  const changeTemporaryTime = e => {
    temporaryTime.value = e
  }

  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 {
    margin-top: 40rpx;
    margin-bottom: 50rpx;
    color: #262626;
    font-size: 26rpx;
    padding: 0 32rpx;
  }

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