<!-- 使用 type="home" 属性设置首页，其他页面不需要设置，默认为page；推荐使用json5，更强大，且允许注释 -->
<route lang="json5" type="page">
{
  style: {
    navigationBarTitleText: '配网向导',
  },
}
</route>

<template>
  <view class="page-form">
    <view class="form-title">
      <view>配网步骤</view>
    </view>
    <view class="tips-box">
      <wd-img :src="deviceImg" width="100" mode="widthFix"></wd-img>
      <view class="check-box">
        <view class="check-result">{{ checkResult }}</view>
        <view v-if="currentWifi" class="check-result">{{ `设备当前连接WiFi: ${currentWifi}` }}</view>
        <wd-button @click="getConnectedWifi()">重新检查</wd-button>
      </view>
      <view v-if="!checkWiFiFlag">{{ `请先连接以 "${targetWifi}" 开头的WiFi` }}</view>
    </view>

    <view class="form-title">
      <view>家庭路由器信息</view>
      <view class="opt-item" @click="getWifiList()">
        <wd-icon name="refresh" size="30rpx"></wd-icon>
        <text>刷新无线列表</text>
      </view>
    </view>
    <wd-form ref="form" :model="formData">
      <wd-cell-group custom-class="form-group" border>
        <wd-select-picker
          v-model="formData.ssid"
          label="无线名称"
          label-width="100px"
          prop="ssid"
          type="radio"
          filterable
          placeholder="请选择家里的无线名称"
          :columns="wifiList"
          value-key="ssid"
          label-key="ssid"
          :loading="loading"
          :max="1"
          :show-confirm="false"
          :rules="[{ required: true, message: '请选择家里的无线名称' }]"
        />
        <wd-input
          v-model="formData.pwd"
          label="无线密码"
          label-width="100px"
          prop="pwd"
          placeholder="请输入家里的无线密码"
          clearable
          show-password
          :rules="[{ required: true, pattern: /^.{8,}$/, message: '请输入不少于8位无线密码' }]"
        />
      </wd-cell-group>

      <view class="form-footer">
        <wd-button type="primary" size="large" :disabled="loading" @click="handleSubmit()" block>提交</wd-button>
      </view>
    </wd-form>
  </view>
</template>

<script lang="ts" setup>
import { testConnect, getWifiStatus, getWifis, connectWifi } from '@/service/api/index'
import { useToast } from 'wot-design-uni'

const loading = ref(false)
const deviceImg = ref('/static/images/device.png')
const toast = useToast()
const targetWifi = "maoer-hub"
const checkWiFiFlag = ref(false)
const checkIPFlag = ref(false)
// 设备当前连接的wifi
const currentWifi = ref("")
// 手机已连接的wifi信息
const wifiInfo: any = ref({})
// 表单信息
const form = ref()
const formData: any = ref({
  ssid: "",
  pwd: "",
})
const wifiList: any = ref([])
// 检查结果
const checkResult = computed(() => {
  return checkWiFiFlag.value ? (checkIPFlag.value ? "已检测到设备" : "未检测到设备") : "未连接指定WiFi"
})

// 检查手机wifi连接是否正确, 匹配前缀
function checkWifi() {
  if (wifiInfo.value.SSID.startsWith(targetWifi)) {
    checkWiFiFlag.value = true
    toast.success('您已连接指定WiFi！')
  }
}

// 获取已连接中的 Wi-Fi 信息。
function getConnectedWifi(isFirst = false) {
  uni.startWifi().then(() => {
    setTimeout(() => {
      uni.getConnectedWifi({
        success: (res) => {
          // 当前手机连接的wifi信息
          wifiInfo.value = res.wifi || {}
          checkWifi()
          if (checkWiFiFlag.value) checkIP(isFirst)
        },
        fail: (err) => {
          toast.error('获取WiFi信息失败')
        }
      })
    }, 1000)
  }).catch((err)=> {})
}

// 局域网通信: 检查IP地址是否请求成功
function checkIP(isFirst: boolean = false) {
  testConnect().then((res: any) => {
    checkIPFlag.value = true
    getDeviceWifiStatus()
    if (isFirst) getWifiList()
  }).catch((err)=> {})
}

// 局域网通信: 获取设备当前连接wifi
function getDeviceWifiStatus() {
  getWifiStatus().then((res: any) => {
    console.log('当前连接WiFi: ', res);
    currentWifi.value = res.body || ""
  }).catch((err)=> {})
}

// 局域网通信: 获取可连接wifi列表
function getWifiList() {
  toast.loading('加载无线列表中...')
  loading.value = true
  getWifis().then((res: any) => {
    console.log('wifi列表: ', res.body);
    wifiList.value = (res.body || []).filter((i: any) => i.ssid)
    toast.success('已刷新无线列表')
  }).catch((err)=> {})
  .finally(() => {
    loading.value = false
    toast.close()
  })
}

// 局域网通信: 设置打印助手的WiFi连接信息
function handleSubmit() {
  form.value.validate().then(({ valid, errors }) => {
    if (valid) {
      loading.value = true
      uni.showLoading({
        title: '正在提交...'
      });
      connectWifi(formData.value).then((res: any) => {
        console.log('res: ', res);
        toast.success('连接成功')
        currentWifi.value = res.body || ""
      }).catch((err) => {
        console.log('err: ', err);
        toast.error('连接失败')
        getDeviceWifiStatus()
      })
      .finally(() => {
        loading.value = false
        uni.hideLoading()
      })
    }
  })
}

onLoad(() => {
  getConnectedWifi(true)
})
</script>

<style lang="scss" scoped>
.tips-box {
  width: calc(100% - 60rpx);
  padding: 40rpx 30rpx;
  text-align: center;
  background-color: #fff;
  border-radius: 16rpx;
}
.check-box {
  margin: 40rpx 0;
  .check-result {
    margin-bottom: 30rpx;
  }
}
</style>

