var _this = null;
var xBlufi = require("@/utils/blufi/xBlufi.js");
export default {	
	data(){
		return {
			sbList:[],
			wxList:[],
			blooth:null
		}
	},
	onLoad(){
		_this = this;
		this.Search();
		xBlufi.listenDeviceMsgEvent(true, this.funListenDeviceMsgEvent);
	},
	onUnload(){
		xBlufi.listenDeviceMsgEvent(false, this.funListenDeviceMsgEvent);
	},
	methods:{
		funListenDeviceMsgEvent: function(options) {
			let ssid_arry = this.wxList;
			switch (options.type) {
				case xBlufi.XBLUFI_TYPE.TYPE_GET_DEVICE_LISTS:
					if (options.result && options.data.length > 0) {
						_this.sbList = options.data;
						let ly = _this.sbList.find(d => d.name.indexOf('cx-') > -1);
						if (!ly) ly = _this.sbList.find(d => d.name.indexOf('BLUFI_DEVICE') > -1);
		
						if (ly) {
							xBlufi.notifyStartDiscoverBle({
								'isStart': false
							});
							_this.blooth = ly;
							_this.connectWiFi();
						}
					}
					break;
				case xBlufi.XBLUFI_TYPE.TYPE_CONNECTED:
					if (options.result) {
						xBlufi.listenDeviceMsgEvent(true, this.funListenDeviceMsgEvent);
						xBlufi.notifyInitBleEsp32({
							deviceId: _this.blooth.deviceId,
						})
					}
					break;
				case xBlufi.XBLUFI_TYPE.TYPE_GET_DEVICE_LISTS_START:
					if (!options.result) {
						console.log('蓝牙未开启')
					}
					break;
				case xBlufi.XBLUFI_TYPE.TYPE_CONNECT_NEAR_ROUTER_LISTS:
					if ('' === options.data.SSID) break;
					if(!ssid_arry.includes(options.data.SSID)) ssid_arry.push(options.data.SSID)
					_this.wxList = ssid_arry;
					let wifiSSID = _this.wxList[0];
					let wifiPWD = uni.getStorageSync(wifiSSID)||'';
					uni.setStorageSync('lanyaWiFiList',JSON.stringify(_this.wxList))
					uni.setStorageSync('lanyaWiFiSSID',wifiSSID)
					console.log(_this.wxList,'_this.wxList')
					console.log(wifiSSID,'wifiSSID')
					break;
				case xBlufi.XBLUFI_TYPE.TYPE_INIT_ESP32_RESULT:
					xBlufi.notifySendGetNearRouterSsid()
					break;
			}
		},
		// 开始或停止搜索设备
		Search: function() {
			xBlufi.notifyStartDiscoverBle({
				'isStart': true
			});
		},
		connectWiFi: function() {
			xBlufi.notifyConnectBle({
				isStart: true,
				deviceId: _this.blooth.deviceId,
				name: _this.blooth.name
			});
		}
	}
}