<template>
	<view class="page">
		<view class="page">
			<view class="weui-form">
				<view class="weui-form__text-area">
					<view class="weui-form__title">xBlufi蓝牙配网{{version}}</view>
					<view class="weui-form__desc">设计理念：简单/快速上手</view>
				</view>
				<view class="weui-form__control-area">
					<view class="weui-cells__group weui-cells__group_form">
						<view class="weui-cells__title">需配置入网当前路由器SSID：{{ssid}}</view>
						<view class="weui-cells weui-cells_form">
							<view class="weui-cell">
								<picker @change="bindPickerChange" :value="index" :range="array">
									<view class="picker">
										Wi-Fi列表：{{array[index]}}
									</view>
								</picker>
							</view>
							<view class="weui-cell">
								<view class="weui-cell__hd"><label class="weui-label">密码：</label></view>
								<view class="weui-cell__bd">
									<input class="weui-input" :value="password" @input="bindPasswordInput" type="text"
										placeholder="在此输入路由器密码" />
								</view>
							</view>
							<view class="weui-cell">
								<view class="weui-cell__hd"><label class="weui-label">数据：</label></view>
								<view class="weui-cell__bd">
									<input class="weui-input" @input="bindCustomDataInput" type="text"
										placeholder="在此输入自定义数据" />
								</view>
							</view>
						</view>
					</view>
				</view>
				<view class="weui-form__tips-area">
					<label for="weuiAgree" class="weui-agree">
						<input id="weuiAgree" type="checkbox" class="weui-agree__checkbox" /><span
							class="weui-agree__text">{{connected?"蓝牙已连接":"蓝牙已断开"}}
						</span>
					</label>
				</view>
				<view class="weui-form__opr-area">
					<button @tap="OnClickStart" :disabled="!isInitOK" type="primary">{{isInitOK?"开始配网并发送自定义数据":"设备初始化失败或非2.4G网络"}}</button>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	var xBlufi = require("@/utils/blufi/xBlufi.js");
	export default {
		data() {
			return {
				version: '2.2',
				name: '',
				index: 0,
				array: [],
				connectedDeviceId: '',
				connected: true,
				deviceInfo: null,
				isInitOK: false,
				ssid:'',
				password: '',
				customData: ''
			}
		},
		onShow: function(options) {
			this.initWifi()
		},
		onLoad: function(options) {
			var that = this
			this.initWifi()
			this.name = options.name;
			this.connectedDeviceId = options.deviceId;
			xBlufi.listenDeviceMsgEvent(true, this.funListenDeviceMsgEvent);
			xBlufi.notifyInitBleEsp32({
				deviceId: options.deviceId,
			})
			wx.showLoading({
				title: '设备初始化中',
			})
		},
		onUnload: function() {
			let that = this
			xBlufi.notifyConnectBle({
				isStart: false,
				deviceId: that.connectedDeviceId,
				name: that.name,
			});
			xBlufi.listenDeviceMsgEvent(false, this.funListenDeviceMsgEvent);
		},
		methods: {
			funListenDeviceMsgEvent: function(options) {
				let that = this
				let ssid_arry = this.array;
				switch (options.type) {
					case xBlufi.XBLUFI_TYPE.TYPE_STATUS_CONNECTED:
						that.connected = options.result
						if (!options.result) {
							wx.showModal({
								title: '很抱歉提醒你！',
								content: '小程序与设备异常断开',
								showCancel: false, //是否显示取消按钮
								// success: function(res) {
								// 	wx.navigateBack({
								// 		url: '../search/search'
								// 	})
								// },
							})
						}
						break;
					case xBlufi.XBLUFI_TYPE.TYPE_CONNECT_ROUTER_RESULT:
						wx.hideLoading();
						if (!options.result)
							wx.showModal({
								title: '温馨提示',
								content: '配网失败，请重试',
								showCancel: false, //是否显示取消按钮
							})
						else {

							if (options.data.progress == 100) {
								let ssid = options.data.ssid;
								wx.showModal({
									title: '温馨提示',
									// content: `成功连接路由器【${options.data.ssid}】`,
									content: `成功连接路由器【${that.ssid}】`,
									showCancel: false, //是否显示取消按钮
									success: function(res) {
										wx.setStorage({
											key: ssid,
											data: that.password
										})
										//判断是否为空
										if (that.customData)
											//开始发送自定义数据，此方法可以在蓝牙连接esp设备之后，随时随地调用！
											xBlufi.notifySendCustomData({
												customData: that.customData,
											})
									},
								})
							}
						}
						break;
					case xBlufi.XBLUFI_TYPE.TYPE_RECIEVE_CUSTON_DATA:
						wx.showModal({
							title: '收到自定义设备数据',
							content: `【${options.data}】`,
							showCancel: false, //是否显示取消按钮
						})
						break;
					case xBlufi.XBLUFI_TYPE.TYPE_CONNECT_NEAR_ROUTER_LISTS:
						wx.hideLoading();
						if ('' === options.data.SSID) break;
						if(!ssid_arry.includes(options.data.SSID)) ssid_arry.push(options.data.SSID)
						that.array = ssid_arry;
						that.ssid = that.array[0];
						that.isInitOK = true
						break;
					case xBlufi.XBLUFI_TYPE.TYPE_INIT_ESP32_RESULT:
						wx.hideLoading();
						if (options.result) {
							xBlufi.notifySendGetNearRouterSsid()
							wx.showLoading({
								title: '模组获取周围WiFi列表...',
							})
						} else {
							that.connected = false
							wx.showModal({
								title: '温馨提示',
								content: `设备初始化失败`,
								showCancel: false, //是否显示取消按钮
							})
						}
						break;
				}
			},
			OnClickStart: function() {
				if (!this.ssid) {
					wx.showToast({
						title: 'SSID不能为空',
						icon: 'none'
					})
					return
				}
				if (!this.password) {
					wx.showToast({
						title: '密码不能为空',
						icon: 'none'
					})
					return;
				}

				wx.showLoading({
					title: '正在配网',
					mask: true
				})
				
				xBlufi.notifySendRouterSsidAndPassword({
					ssid: this.ssid,
					password: this.password,
					success: res => {
						console.log(res, 'res');
					},
					fail:err=>{
						console.log(err, 'err');
					}
				})
			},
			stringToUtf8Bytes: function(str) {
				// 编码为百分比转义字符串（如 "%E6%88%91" => "我"）
				const encoded = encodeURIComponent(str);
				const bytes = [];
				let i = 0;
				while (i < encoded.length) {
					if (encoded[i] === '%') {
						// 提取 % 后的两个字符作为十六进制字节（如 "%E6" => 0xE6）
						bytes.push(parseInt(encoded.substr(i + 1, 2), 16));
						i += 3; // 跳过 %XX 三个字符
					} else {
						// 普通 ASCII 字符直接转为字节（如 "A" => 0x41）
						bytes.push(encoded.charCodeAt(i));
						i++;
					}
				}
				return bytes;
			},
			bytesToBase64: function(bytes) {
				return wx.arrayBufferToBase64(new Uint8Array(bytes).buffer);
			},
			bindPasswordInput: function(e) {
				this.password = e.detail.value
			},
			bindCustomDataInput: function(e) {
				this.customData = e.detail.value
			},
			initWifi() {

			},
			bindPickerChange: function(e) {
				this.index = e.detail.value
				let password = wx.getStorageSync(this.array[e.detail.value])
				this.ssid = this.array[e.detail.value]
				this.isInitOK = true
				this.password = password == undefined ? "" : password
			},
		}
	}
</script>

<style scoped lang="scss">
	@import url(@/utils/blufi/weui.scss);

	page,
	.page {
		height: 100%;
	}

	button {
		width: 75%;
	}
</style>