<template>
  <view>
    <view class="mt-4">
      <up-steps :current="current" activeColor="#63b8af" class="custom-steps">
        <up-steps-item title="设置WiFi" :itemStyle="{ fontSize: '48rpx' }"> </up-steps-item>
        <up-steps-item title="连接设备蓝牙" :itemStyle="{ fontSize: '48rpx' }"></up-steps-item>
        <up-steps-item title="开始配网" :itemStyle="{ fontSize: '48rpx' }"></up-steps-item>
      </up-steps>
      <view class="mt-8 mx-8 flex flex-col h-[calc(100vh-300rpx)]">
        <view v-if="current === 0">
          <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 ?? '加载中...' }}</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
                }"
                placeholder-class="!text-base !line-height-[80rpx]"
                v-model="password"
                placeholder="请输入密码"
                :type="showPassword ? 'text' : 'password'"
              >
                <template #suffix>
                  <up-icon
                    :name="showPassword ? 'eye-fill' : 'eye-off'"
                    size="42rpx"
                    @click="togglePassword"
                  ></up-icon>
                </template>
              </up-input> -->
            </view>
          </view>
        </view>
        <view v-if="current === 1" class="flex flex-col h-[calc(100vh-230rpx)]">
          <view class="text-lg font-bold mb-2">请连接设备蓝牙</view>
          <view class="text-[#999999]">已发现设备如下</view>
          <scroll-view scroll-y class="flex-1 mt-4 overflow-hidden">
            <view
              v-for="item in deviceList"
              :key="item.deviceId"
              @click="connectDevice(item)"
              class="bg-[#efedf1] rounded-xl py-4 px-3 mt-2 flex justify-between"
            >
              <view>{{ item.name }}</view>
              <view class="text-[#63b8af]">连接</view>
            </view>
          </scroll-view>
          <view class="flex justify-center items-center mt-2">
            <up-loading-icon
              size="70rpx"
              text="搜索中"
              :vertical="true"
              textSize="28rpx"
            ></up-loading-icon>
          </view>
        </view>
        <view v-if="current === 2">
          <view class="flex justify-center mt-10">
            <image
              src="https://oss-lock.xhjcn.ltd/mp/cloud_server.png"
              mode="aspectFill"
              class="w-200rpx h-200rpx p-4"
            ></image>
          </view>
          <view
            v-for="(item, index) in stepList"
            :key="item"
            class="flex items-center mt-4 justify-center w-full"
          >
            <view class="flex items-center justify-start w-400rpx">
              <up-loading-icon mode="circle" v-if="step < index + 1" size="36rpx"></up-loading-icon>
              <up-icon name="checkbox-mark" color="#63b8af" size="36rpx" v-else></up-icon>
              <view class="ml-3">{{ item }}</view>
            </view>
          </view>
        </view>
      </view>
      <view
        v-if="current === 0"
        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="handleNext"
        >下一步</view
      >
    </view>
  </view>
</template>

<script setup>
  import { onMounted, ref } from 'vue'
  import { constants as WifiConfConstants } from 'qcloud-iotexplorer-appdev-plugin-wificonf-core'
  import { BlueToothAdapter } from 'qcloud-iotexplorer-bluetooth-adapter'
  import {
    BleComboEspDeviceAdapter,
    BleComboLLSyncDeviceAdapter
  } from 'qcloud-iotexplorer-appdev-plugin-wificonf-blecombo'
  import { useBasicStore } from '@/stores/basic'
  import { useSdkStore } from '@/stores/sdk'

  const bluetoothAdapter = new BlueToothAdapter({
    deviceAdapters: [BleComboEspDeviceAdapter, BleComboLLSyncDeviceAdapter]
  })

  const { WifiConfStepCode, WifiConfErrorMsg } = WifiConfConstants

  const $basic = useBasicStore()
  const $sdk = useSdkStore()

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

  const step = ref(1)

  const deviceList = ref([])

  const showPassword = ref(false)

  const stepList = ref([
    '手机与设备连接成功',
    '向设备发送信息成功',
    '设备连接云端成功',
    '初始化成功'
  ])

  const wifiInfo = ref({
    SSID: '',
    password: ''
  })

  const deviceInfo = $basic.deviceInfo

  onMounted(() => {
    if (deviceInfo.platform !== 'android' && deviceInfo.platform !== 'ios') {
      uni.showToast({
        title: '当前设备不支持WiFi功能',
        icon: 'none'
      })
      return
    }

    uni.authorize({
      scope: 'scope.userLocation',
      success: () => {
        const getWifiListFn = () => {
          uni.getWifiList({
            success: () => {
              uni.onGetWifiList(res => {
                const uniqueWifiList = res.wifiList
                  .filter(wifi => wifi.SSID && wifi.SSID.trim() !== '')
                  .reduce((acc, current) => {
                    const exists = acc.find(item => item.SSID === current.SSID)
                    if (!exists) {
                      acc.push(current)
                    }
                    return acc
                  }, [])
                wifiList.value = uniqueWifiList
                wifiIndex.value = 0
              })
            },
            fail: err => {
              console.error('获取WiFi列表失败：', err)
              uni.showToast({
                title: '获取WiFi列表失败',
                icon: 'none'
              })
            }
          })
        }

        if (deviceInfo.platform === 'android') {
          uni.startWifi({
            success: () => {
              getWifiListFn()
            },
            fail: err => {
              console.error('初始化WiFi失败：', err)
              uni.showToast({
                title: '初始化WiFi失败',
                icon: 'none'
              })
            }
          })
        } else {
          getWifiListFn()
        }
      },
      fail: () => {
        uni.showModal({
          title: '提示',
          content: '需要获取位置权限才能使用WiFi功能',
          success: res => {
            if (res.confirm) {
              uni.openSetting()
            }
          }
        })
      }
    })
  })

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

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

  function bleComboConfigure({ token, wifiInfo, familyId = 'default', roomId, deviceAdapter }) {
    const onStepChange = progress => {
      step.value = progress
    }

    const onProgress = data => {
      console.info(data.code, data.detail)
      switch (data.code) {
        case WifiConfStepCode.PROTOCOL_START:
          onStepChange(1)
          break
        case WifiConfStepCode.PROTOCOL_SUCCESS:
          onStepChange(2)
          break
        case WifiConfStepCode.BUSINESS_QUERY_TOKEN_STATE_SUCCESS:
          onStepChange(3)
          break
        case WifiConfStepCode.WIFI_CONF_SUCCESS:
          onStepChange(4)
          break
        default:
          break
      }
    }

    const onComplete = ({ productId, deviceName }) => {
      console.log('配网成功', productId, deviceName)
    }

    const onError = async ({ code, detail }) => {
      const msg = WifiConfErrorMsg[code]
      console.log('配网错误(onError)', code, msg, detail)
    }

    $sdk.getSdk().plugins.wifiConfBleCombo.start({
      wifiConfToken: token,
      targetWifiInfo: wifiInfo,
      deviceAdapter,
      familyId,
      roomId,
      onProgress,
      onError,
      onComplete
    })
  }

  const connectDevice = async device => {
    try {
      const deviceAdapter = await bluetoothAdapter.connectDevice(device)
      console.log(1111, deviceAdapter)
      bleComboConfigure({
        token: '1234567890',
        wifiInfo: wifiInfo.value,
        familyId: 'default',
        roomId: 'default',
        deviceAdapter
      })
      current.value++
    } catch (err) {
      console.error('连接设备出错', err)
    }
  }

  const searchDevice = async () => {
    try {
      await bluetoothAdapter.startSearch({
        onError: error => {
          console.log('搜索设备出错', error)
          bluetoothAdapter.stopSearch()
        },
        onSearch: devices => {
          if (devices.length > 0) {
            console.log('搜索到设备', devices)
            deviceList.value = devices
          }
        },
        timeout: 1.4 * 15 * 1000
      })
    } catch (error) {
      console.log('搜索设备出错1', error)
    }
  }

  const handleNext = () => {
    current.value++
    searchDevice()
    if (wifiIndex.value === undefined) {
      uni.showToast({
        title: '请选择WiFi',
        icon: 'none'
      })
      return
    }
    if (password.value === '') {
      uni.showToast({
        title: '请输入密码',
        icon: 'none'
      })
      return
    }
    if (password.value.length < 8) {
      uni.showToast({
        title: '密码长度不能小于8位',
        icon: 'none'
      })
      return
    }

    wifiInfo.value = {
      SSID: wifiList.value[wifiIndex.value].SSID,
      password: password.value
    }

    uni.offGetWifiList()
    if (deviceInfo.platform === 'android') {
      uni.stopWifi()
    }
    current.value++

    searchDevice()
  }
</script>

<style lang="scss" scoped>
  .custom-steps {
    :deep(.u-text__value) {
      font-size: 28rpx !important;
    }
  }
</style>
