<template>
  <view>
    <view class="tabs">
      <up-tabs :list="tabs" lineWidth="40rpx" lineHeight="5rpx" :current="currnetIndex" 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="currnetIndex" @change="changeSwiper">
      <swiper-item>
        <LockInput :value="permanentName" title="姓名" placeholder="请给密码命名"
                   @changeInput="changePermanentInput"></LockInput>
        <view class="text">{{ text }}</view>
        <view class="button" @click="createPassword('permanent')">获取密码</view>
      </swiper-item>
      <swiper-item :style="{height: deviceInfo.windowHeight - 44 + 'px'}">
        <LockInput :value="temporaryName" title="姓名" placeholder="请给密码命名"
                   @changeInput="changeTemporaryInput"></LockInput>
        <view style="margin-top: 20rpx">
          <LockDatetimePicker title="失效时间" :value="temporaryTime" :minDate="minDate" :maxDate="maxDate" type="datehour"
                              @changeTime="changeTemporaryTime"></LockDatetimePicker>
        </view>
        <view class="text">{{ text }}</view>
        <view class="button" @click="createPassword('temporary')">获取密码</view>
      </swiper-item>
    </swiper>
  </view>
</template>

<script>

import { mapActions, mapState } from 'pinia'
import { useBasicStore } from '@/stores/basic'
import LockInput from '@/components/LockInput/LockInput.vue'
import LockDatetimePicker from '@/components/LockDatetimePicker/LockDatetimePicker.vue'
import { createPsaawordRequest } from '@/api/keyboardPwd'
import { useBluetoothStore } from '@/stores/bluetooth'
import { useLockStore } from '@/stores/lock'

export default {
  data () {
    return {
      tabs: [{
        name: '永久'
      }, {
        name: '限时'
      }],
      permanentName: '',
      temporaryName: '',
      temporaryTime: Number(new Date()),
      minDate: Number(new Date()),
      maxDate: Number(4133951940000),
      currnetIndex: 0,
      deviceInfo: null,
      pending: false,
      text: '密码生成后，请在当日23：59前使用一次进行激活，否则过0点后未激活则失效。密码激活后，有效期内不限次数使用。'
    }
  },
  components: {
    LockInput,
    LockDatetimePicker
  },
  computed: {
    ...mapState(useBluetoothStore, ['currentLockInfo']),
    ...mapState(useLockStore, ['passwordSearch']),
  },
  async onLoad() {
    this.deviceInfo = await this.getDeviceInfo()
    this.temporaryTime = this.setTime()
    this.minDate = Number(this.getNextFullHour())
    this.maxDate = Number(this.getFutureTimestamp())
  },
  methods: {
    ...mapActions(useBasicStore, ['getDeviceInfo', 'backAndToast', 'getNetworkType']),
    ...mapActions(useLockStore, ['getPasswordList', 'updatePasswordSearch']),
    // 获取下一个整点时间
    getNextFullHour() {
      const now = new Date()
      const currentHour = now.getHours()
      now.setHours(currentHour);
      now.setMinutes(0);
      now.setSeconds(0);
      now.setMilliseconds(0);

      return now;
    },
    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();
    },
    setTime() {
      const now = new Date()
      now.setMinutes(0, 0, 0)

      return now.getTime()
    },
    async createPassword(type) {
      const that = this
      if((type === 'temporary' && this.temporaryName === '') || (type === 'permanent' && this.permanentName === '')) {
        uni.showToast({
          title: '名称不能为空',
          icon: 'none'
        })
        return
      }

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

      if(this.pending) {
        return
      }
      this.pending = 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: () => {
                  that.backAndToast('复制成功')
                }
              })
            }
          }
        })
      } else {
        uni.showToast({
          title: message,
          icon: 'none'
        })
      }
      this.pending = false
    },
    changePermanentInput(e) {
      this.permanentName = e
    },
    changeTemporaryInput(e) {
      this.temporaryName = e
    },
    changeTemporaryTime(e) {
      this.temporaryTime = e
    },
    clickTab(data) {
      this.currnetIndex = data.index
    },
    changeSwiper(e) {
      this.currnetIndex = 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>
