<template>
  <view>
    <view class="mt-4">
      <view class="mt-18 mx-8 flex flex-col">
        <view class="text-lg font-bold mb-4">请选择WiFi并输入密码</view>
        <view class="pt-2 pb-3 border-b-2 border-b-solid border-gray-200">
          <picker
            mode="selector"
            :range="wifiList"
            :value="wifiIndex"
            @change="changeWifi"
            range-key="SSID"
          >
            <view class="flex items-center">
              <view class="mr-4">WiFi</view>
              <view>{{ wifiList[wifiIndex]?.SSID ?? '请选择WiFi' }}</view>
              <view class="ml-a">
                <up-icon name="arrow-right" size="24rpx"></up-icon>
              </view>
            </view>
          </picker>
        </view>
        <view class="py-2 border-b-2 border-b-solid border-gray-200 flex items-center">
          <view>密码</view>
          <view class="flex-1">
            <up-input
              :customStyle="{
                padding: '0 28rpx',
                outline: 'none',
                height: '80rpx',
                backgroundColor: '#FFFFFF',
                border: 0
              }"
              :maxlength="20"
              placeholder-class="!text-base !line-height-[80rpx]"
              placeholder="请输入密码"
              :type="showPassword ? 'text' : 'password'"
              @change="handleInput"
            >
              <template #suffix>
                <up-icon
                  :name="showPassword ? 'eye-fill' : 'eye-off'"
                  size="42rpx"
                  @click="togglePassword"
                ></up-icon>
              </template>
            </up-input>
          </view>
        </view>
      </view>
      <view
        class="fixed bottom-[calc(env(safe-area-inset-bottom)+32rpx)] w-686rpx mx-4 h-88rpx text-center text-white bg-[#63b8af] leading-[88rpx] rounded-44rpx font-bold"
        @click="connectWifi"
      >
        连接
      </view>
    </view>
  </view>
</template>

<script setup>
  import { onMounted, onUnmounted, ref } from 'vue'
  import { useBluetoothStore } from '@/stores/bluetooth'
  import { useUserStore } from '@/stores/user'
  import { useBasicStore } from '@/stores/basic'
  import { passthrough } from '@/api/sdk'

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

  const wifiList = ref([])
  const wifiIndex = ref()
  const password = ref('')

  const showPassword = ref(false)

  const pending = ref(false)

  const result = ref(false)

  onMounted(async () => {
    uni.showLoading({
      title: '搜索中'
    })
    const result = await $bluetooth.getWifiList({
      uid: $user.userInfo.uid.toString()
    })
    if (result.code !== 0) {
      uni.showModal({
        title: '提示',
        content: '搜索失败，请返回重试',
        showCancel: false,
        success: () => {
          uni.navigateBack()
        }
      })
    }
    listenEvent()
  })

  onUnmounted(() => {
    uni.$off('wifiList')
    uni.$off('distributionNetworkResult')
  })

  const listenEvent = () => {
    uni.$on('wifiList', async data => {
      if (data.status === 0) {
        wifiList.value = data.wifiList
        if (wifiList.value.length > 0) {
          wifiIndex.value = 0
        }
        uni.hideLoading()
      } else {
        uni.showModal({
          title: '提示',
          content: '搜索失败，请返回重试',
          showCancel: false,
          success: () => {
            uni.navigateBack()
          }
        })
      }
    })
    uni.$on('distributionNetworkResult', async data => {
      result.value = false
      uni.hideLoading()
      pending.value = false
      if (data.status === 0) {
        $basic.routeJump({
          type: 'redirectTo',
          name: 'selectAddress'
        })
        setTimeout(() => {
          uni.showToast({
            title: '连接成功',
            icon: 'none'
          })
        }, 1000)
      } else {
        uni.showToast({
          title: '连接失败，请重试',
          icon: 'none'
        })
      }
    })
  }

  const togglePassword = () => {
    showPassword.value = !showPassword.value
  }

  const changeWifi = e => {
    wifiIndex.value = e.detail.value
  }

  const connectWifi = async () => {
    if (password.value.length < 8) {
      uni.showToast({
        title: '密码长度不能小于8位',
        icon: 'none'
      })
      return
    }

    if (pending.value) return
    pending.value = true
    uni.showLoading({
      title: '连接中...'
    })

    const result = await passthrough({
      request_method: 'GET',
      request_uri: '/api/v1/tencentYun/getTencentTriple',
      post_args: {
        serialNum0: $bluetooth.currentLockInfo.lockConfig.serialNum0
      }
    })
    if (result.code === 0) {
      $bluetooth.updateCurrentLockInfo({
        ...$bluetooth.currentLockInfo,
        tencentYunLock: result.data
      })

      const res = await $bluetooth.distributionNetwork({
        SSID: wifiList.value[wifiIndex.value].SSID,
        password: password.value,
        json: JSON.stringify(result.data)
      })

      if (res.code === 0) {
        result.value = true
        setTimeout(() => {
          pending.value = false
          if (result.value) {
            uni.showToast({
              title: '配网失败，请检查密码是否正确',
              icon: 'none'
            })
          }
        }, 10000)
      } else {
        pending.value = false
        uni.showToast({
          title: res.message,
          icon: 'none'
        })
      }
    } else {
      uni.hideLoading()
      pending.value = false
      uni.showToast({
        title: result.message,
        icon: 'none'
      })
    }
  }

  const handleInput = e => {
    password.value = e
  }
</script>
