<template>
	<view class="page" :style="{'min-height':h+'px', 'padding-top':mt+'px'}">
		<cus-header title='无线局域网' bgColor="transparent"></cus-header>
		<view class="content">
		    <button @click="initWifi">初始化WiFi模块</button>
		    <button @click="getConnectedWifi">获取已连接WiFi</button>
		    <button @click="getWifiList">扫描WiFi列表</button>
		    
		    <view v-if="connectedWifi">
		      <text>已连接: {{ connectedWifi.SSID }}</text>
		      <text>信号强度: {{ connectedWifi.level }} dBm</text>
		    </view>
		
		    <view v-for="(wifi, index) in wifiList" :key="index">
		      <text>{{ wifi.SSID }}</text>
		      <text>信号: {{ wifi.level }} dBm</text>
		      <button @click="connectWifi(wifi)">连接</button>
		    </view>
		  </view>
	</view>
</template>

<script>
	export default {
		data() {
		    return {
		      wifiList: [],
		      connectedWifi: null
		    }
		  },
		  methods: {
		    // 初始化WiFi模块
		    initWifi() {
		      uni.startWifi({
		        success: () => {
		          uni.showToast({ title: 'WiFi模块初始化成功' });
		          this.startWifiListener();
		        },
		        fail: (err) => {
		          console.error('初始化失败:', err);
		        }
		      });
		    },
		
		    // 获取已连接WiFi
		    getConnectedWifi() {
		      uni.getConnectedWifi({
		        success: (res) => {
		          this.connectedWifi = res.wifi;
		        },
		        fail: (err) => {
		          console.error('获取失败:', err);
		        }
		      });
		    },
		
		    // 扫描WiFi列表
		    getWifiList() {
		      uni.startWifi({
		        success: () => {
		          uni.getWifiList({
		            success: (res) => {
		              console.log('获取列表成功');
		            },
		            fail: (err) => {
		              console.error('获取列表失败:', err);
		            }
		          });
		        }
		      });
		    },
		
		    // 监听WiFi变化
		    startWifiListener() {
		      uni.onWifiConnected((res) => {
		        this.connectedWifi = res.wifi;
		      });
		
		      uni.onGetWifiList((res) => {
		        this.wifiList = res.wifiList.sort((a, b) => b.level - a.level);
		      });
		    },
		
		    // 连接指定WiFi
		    connectWifi(wifi) {
		      uni.connectWifi({
		        SSID: wifi.SSID,
		        password: 'your_password', // 需要实际密码
		        success: () => {
		          uni.showToast({ title: '连接成功' });
		        },
		        fail: (err) => {
		          console.error('连接失败:', err);
		        }
		      });
		    }
		  }
	}
</script>

<style scoped lang="less">
	.page{
		background: #F1F3F5;
		box-sizing: border-box;
		
		.content {
		  padding: 20px;
		}
		
		button {
		  margin: 10px 0;
		  padding: 8px;
		  background-color: #007AFF;
		  color: white;
		  border-radius: 5px;
		}
	}
</style>