<template>
	<view class="page">
		<u-navbar title="店铺详情" :border-bottom="false" :background="bgc" title-color='#fff' back-icon-color="#fff"
			title-size='36' height='50'></u-navbar>
		<view class="box">
			<view class="shopname">
				{{listobj.name == null ? '' : listobj.name}}
			</view>
			<view class="shoplist">
				<view class="tit">
					基本信息
				</view>
				<view class="jiben">
					<text class="qian">绑定设备：</text> <text class="shen">{{listobj.deviceCount == undefined ? '--' : listobj.deviceCount}}</text>
				</view>
				<view class="jiben">
					<text class="qian">营业时间：</text> <text
						class="shen">{{listobj.businessTimeStart == null ? '' : listobj.businessTimeStart}}~{{listobj.businessTimeEnd == null ? '' : listobj.businessTimeEnd}}</text>
				</view>
				<view class="jiben">
					<text class="qian">详细地址：</text> <text class="shen">{{listobj.address == undefined ? '--' : listobj.address}}</text>
				</view>
				<view class="jiben">
					<text class="qian">创建时间：</text> <text class="shen">{{listobj.createTime == undefined ? '--' : listobj.createTime}}</text>
				</view>
			</view>
			<view class="editxg" @click="btnsh" v-if="listobj.status == 2">
				<view class="">
					审核中
				</view>
				<view class="">
					<u-icon name="arrow-right" color="#000" size="28"></u-icon>
				</view>
			</view>
			<view class="icons" style="border-radius: 24rpx;">
				<image v-if="listobj.operator.config" src="https://api.ccttiot.com/smartmeter/img/static/u9IYNLl7G83pOXtQbaYj" mode="aspectFit"
					@click="btnpag(4)"></image>
				<image v-if="listobj.operator.update" src="https://api.ccttiot.com/smartmeter/img/static/uoyO7psgUNmNuhPDoOmH" mode="aspectFit"
					@click="btnpag(2)"></image>
				<image v-if="listobj.operator.viewDevice" src="https://api.ccttiot.com/smartmeter/img/static/uCaV3mfjN1LUrW1gPPzQ" mode="aspectFit"
					@click="btnpag(1)"></image>
				<image v-if="listobj.operator.del" src="https://api.ccttiot.com/smartmeter/img/static/uu7AtppWYWNucDPLkcFu" mode="aspectFit"
					@click="btnpag(3)"></image>
			    <image @click="nav" v-if="listobj.operator.del" style="width: 120rpx;margin-top: 20rpx;" src="https://api.ccttiot.com/smartmeter/img/static/ulImlG4HEX1gU65tO00z" mode="aspectFit"></image>
			</view>
		</view>

		<u-select v-model="show" :list="list" title='添加方式' @confirm="confirm"></u-select>
          <view v-if="btnmsk" style="width: 100%;height: 100vh;position: fixed;top: 0;left: 0;background-color: #000;opacity: .1;z-index: 999;"></view>
	</view>
</template>

<script>
	var xBlufi = require("@/page_components/blufi/xBlufi.js");
	export default {
		data() {
			return {
				btnmsk:false,
				list: [{
						value: '1',
						label: '扫码添加'
					},
					{
						value: '2',
						label: '搜索附近设备添加'
					}
				],
				show: false,
				storeId: '',
				listobj: {},
				deviceId: '',
				name: '',
				mac: '',
				macs:''
			}
		},
		onLoad(option) {
			this.storeId = option.id
			this.getdetail()

			// xBlufi.initXBlufi(1);
			// console.log("xBlufi", xBlufi.XMQTT_SYSTEM);
			// xBlufi.listenDeviceMsgEvent(true, this.funListenDeviceMsgEvent);
			// xBlufi.notifyStartDiscoverBle({
			// 	'isStart': true
			// });

			// // 停止蓝牙搜索  
			// setTimeout(() => {
			// 	xBlufi.notifyStartDiscoverBle({
			// 		'isStart': false
			// 	});
			// 	xBlufi.notifyConnectBle({
			// 		isStart: true,
			// 		deviceId: this.deviceId,
			// 		name: this.name
			// 	});
			// }, 3000)

		},
		onUnload: function() {
			xBlufi.listenDeviceMsgEvent(false, this.funListenDeviceMsgEvent);
			xBlufi.notifyStartDiscoverBle({
				'isStart': false
			})
		},
		onHide() {
			xBlufi.listenDeviceMsgEvent(false, this.funListenDeviceMsgEvent);
			xBlufi.notifyStartDiscoverBle({
				'isStart': false
			});
		},
		onBeforeUnmount() {
			xBlufi.listenDeviceMsgEvent(false, this.funListenDeviceMsgEvent);
			xBlufi.notifyStartDiscoverBle({
				'isStart': false
			});
		},
		// 分享到好友（会话）
		  onShareAppMessage: function () {  
		    return {  
		      title: '创想物联',  
		      path: '/pages/shouye/index'  
		    }  
		  },  
		  
		  // 分享到朋友圈  
		  onShareTimeline: function () {  
		    return {  
		      title: '创想物联',  
		      query: '',  
		      path: '/pages/shouye/index'  
		    }  
		  },
		methods: {		
			nav(){
				uni.navigateTo({
					url:'/page_fenbao/hehuoren/index?storeId=' + this.storeId,
				})
			}, 
			btnsh(){
				uni.navigateTo({
					url:'/page_fenbao/editshenhe?storeId=' + this.storeId
				})
			},
			getdetail() {
				this.$u.get("/app/store/mch/" + this.storeId).then(res => {
					if (res.code == 200) {
						this.listobj = res.data
					}
				})
			},

			btnpag(num) {
				if (num == 1) {
					uni.navigateTo({
						url: '/page_fenbao/statulist/myshop/shebeilist/index?storeId=' + this.storeId
					})
				} else if (num == 2) {
					if(this.listobj.status == 2){
						uni.showToast({
							title: '已有未审核店铺信息',
							icon: 'none',
							duration: 1000
						})
					}else{
						uni.navigateTo({
							url: '/page_fenbao/statulist/myshop/editshop/index?obj=' + JSON.stringify(this.listobj)
						})
					}
				} else if (num == 3) {
					let vm = this
					uni.showModal({
						title: '提示',
						content: '你确定要注销这个店铺吗？',
						success: function(res) {
							if (res.confirm) {
								this.btnmsk = true
								vm.$u.delete("/app/store/" + vm.storeId).then(res => {
									if (res.code == 200) {
										uni.showToast({
											title: '删除成功',
											icon: 'success',
											duration: 1000
										})
										setTimeout(() => {
											this.btnmsk = false
											uni.navigateBack()
										}, 1500)
									} else if (res.code == 500) {
										uni.showToast({
											title: res.msg,
											icon: 'none',
											duration: 1000
										})
										this.btnmsk = false
									}
								})
							} else if (res.cancel) {
								console.log('用户点击了取消')
							}
						}
					})
				}else if(num == 4){
					uni.navigateTo({
						url:'/page_components/peizhi?obj=' + JSON.stringify(this.listobj)
					})
				}
			},

			confirm(e) {
				let type = e[0].value
				if (type == '1') {
					this.scanQRCode()
				} else if (type == '2') {
					uni.navigateTo({
						url: '/page_fenbao/device/index?storeId=' + this.storeId
					})
				}
			},
			scanQRCode() {
					  uni.scanCode({
					  	onlyFromCamera: true,
					  	scanType: ['qrCode'],
					  	success: res => {
					  		function getQueryParam(url, paramName) {
					  			let regex = new RegExp(`[?&]${paramName}=([^&]*)`)
					  			let results = regex.exec(url);
					  			return results ? decodeURIComponent(results[1].replace(/\+/g, ' ')) : null
					  		}
					  		let sceneValue = res.result
					  		let decodedValue = decodeURIComponent(sceneValue)
					  		let id = getQueryParam(decodedValue, 's')
					  		// console.log(res, id)
					  		let that = this
					  		let data = {
					  			deviceNo: id
					  		}
					  		that.$u.get(`/app/device/isBind?deviceNo=${id}`).then(res => {
					  			if (res.data == 2) {
					  				that.$u.get(`/app/device/${id}/withSuitList`).then((res) => {
					  					if (res.code == 200) {
					  						uni.navigateTo({
					  							url: '/page_components/fuwu/index?id=' + id
					  						})
					  					} 
					  				})
					  			} else if (res.data == 1) {
					  				uni.showModal({
					  					title: '提示',
					  					content: '该设备未绑定,你需进行绑定吗？',
					  					success: function(res) {
					  						if (res.confirm) {
					  							that.$u.put("/app/device/bind", data).then(res => {
					  								if(res.code == 200){
					  									that.$u.get(`/app/device/${id}/bySn`).then((res) => {
					  										if (res.code == 200) {
					  											uni.navigateTo({
					  												url: '/page_components/bindsz?id=' + res.data.deviceId
					  											})
					  										} 
					  									})
					  								}
					  							})
					  						}
					  					}
					  				})
					  			} else if (res.data == 0) {
					  				uni.showModal({
					  					title: '提示',
					  					content: '该设备未录入,你需进行录入吗？',
					  					success: function(res) {
					  						if (res.confirm) {
					  							uni.navigateTo({
					  								url: '/page_fenbao/zhuce?sn=' + id
					  							})
					  						} else if (res.cancel) {
													
											}
					  					}
					  				})
					  			}
					  		})
					  	},
					  	fail: err => {
					  		console.error('扫描失败：', err)
					  		uni.showToast({
					  			title: '扫描失败',
					  			icon: 'none'
					  		})
					  	}
					  })
			},

			funListenDeviceMsgEvent: function(options) {
				switch (options.type) {
					case xBlufi.XBLUFI_TYPE.TYPE_GET_DEVICE_LISTS:
						if (options.result) {
							let devicesarr = options.data
							console.log(devicesarr, 'devicesarrdevicesarr');
							devicesarr.forEach(device => {
								const mac = device.name.substring(5);
								if (device.name == this.qrResult) {
									this.deviceId = device.deviceId
									this.name = device.name
									this.mac = device.name.substring(5)
									this.devicesList = uniqueDevicesList;
								}
							})
						} else {
							uni.showToast({
								title: '没有发现设备',
								icon: 'none',
								duration:2000
							});
						}
						break;

					case xBlufi.XBLUFI_TYPE.TYPE_CONNECTED:
						console.log("连接回调：" + JSON.stringify(options));
						if (options.result) {
							uni.hideLoading();
							// uni.showToast({
							// 	title: '连接成功',
							// 	icon: 'none'
							// }); 
							{
								console.log("连接回调options.data.deviceId：" + options.data.deviceId,
									"连接回调options.data.name：" + options.data.name)
								let name = ''
								let index = this.name.indexOf('-')
								if (index !== -1) {
									name = this.name.slice(index + 1)
								}
								let data = {
									storeId: this.storeId,
									mac: this.macs
								}
								this.$u.put('/app/device/bind', data).then((res) => {
									if (res.code == 200) {
										uni.showToast({
											title: '绑定成功',
											icon: 'none',
											duration: 2000
										});
										uni.hideLoading()
										uni.removeStorageSync('mac');
										let vm = this
										uni.showModal({
											title: '提示',
											content: '你已绑定成功,需前去配网吗？',
											success: function(res) {
												if (res.confirm) {
													if(vm.mac == ''){
														uni.showToast({
															title: '请靠近设备，未找到设备',
															icon: 'none',
															duration: 2000
														});
													}else{
														let systemInfo = uni.getSystemInfoSync();
														if (systemInfo.platform === 'android') {
															// 当前设备是 Android  
															uni.navigateTo({
																url: '/page_components/wifilist/index?deviceId=' +options.data.deviceId + '&name=' +options.data.name
															})
														} else if (systemInfo.platform === 'ios') {
															// 当前设备是 iOS  
															uni.navigateTo({
																url: '/page_fenbao/device/wifivideo?deviceId=' +options.data.deviceId + '&name=' +options.data.name
															})
														}
													}
												} else if (res.cancel) {
													console.log('用户点击了取消')
												}
											}
										})

									} else if (res.code == 500) {
										uni.showToast({
											title: res.msg,
											icon: 'none',
											duration: 2000
										});
									} else {
										uni.showToast({
											title: '绑定失败',
											icon: 'none',
											duration: 2000
										});
										// uni.navigateBack()
									}
								})
							}
						}

						break

					case xBlufi.XBLUFI_TYPE.TYPE_GET_DEVICE_LISTS_START:
						if (!options.result) {
							console.log("蓝牙未开启", options)
							uni.showToast({
								title: '蓝牙未开启',
								icon: 'none',
								duration: 3000
							})
						} 

						break

					case xBlufi.XBLUFI_TYPE.TYPE_GET_DEVICE_LISTS_STOP:
						if (options.result) {
							let uniqueDevicesList = Array.from(new Set(this.devicesList));

							// 将去重后的数组重新赋值给 this.devicesList
							this.devicesList = uniqueDevicesList
							let list = []
							filteredDevices.forEach(device => {
								// 从设备名称中提取 MAC 地址（假设 MAC 地址是设备名称的后6个字符）
								let macFromName = device.name.substring(device.name.length - 12)
								// console.log(macFromName)
								// 与 this.mac 进行比较
								this.$u.get(`/app/device/${macFromName}/isBind`).then((res) => {
									if (res.data == false) {
										list.push(device)
									} else {

									}
								})

							})
							setTimeout(() => {
								this.devicesList = list
							}, 200)

							console.log('蓝牙停止搜索ok')
						} else {
							//蓝牙停止搜索失败
							console.log('蓝牙停止搜索失败')
						}
						this.searching = false
						// _this.setData({
						// 	searching: false
						// });

						break
				}
			},

		}
	}
</script>

<style lang="scss">
	/deep/ .u-title {
		padding-bottom: 22rpx;
	}

	/deep/ .u-icon__icon {
		padding-bottom: 22rpx;
	}


	page {
		background: linear-gradient(180deg, #8883F0 0%, rgba(255, 255, 255, 0) 100%);
	}

	.page {
		width: 750rpx;
		position: fixed;
		top: 0;
		left: 0;
         .editxg{
			 width: 100%;
			 height: 90rpx;
			 line-height: 90rpx;
			 display: flex;
			 justify-content: space-between;
			 padding: 0 30rpx;
			 box-sizing: border-box;
			 background-color: #fff;
			 border-radius: 20rpx;
			 margin-top: 20rpx;
		 }
		.box {
			width: 750rpx;
			height: 1440rpx;
			background: #F4F5F7;
			border-radius: 0rpx 0rpx 0rpx 0rpx;
			padding: 22rpx 36rpx;
			box-sizing: border-box;

			.shopname {
				width: 680rpx;
				height: 102rpx;
				background: #FFFFFF;
				border-radius: 24rpx 24rpx 24rpx 24rpx;
				margin: auto;
				padding-left: 30rpx;
				padding-top: 30rpx;
				font-weight: 600;
				font-size: 32rpx;
				color: #3D3D3D;
			}

			.shoplist {
				padding: 30rpx;
				box-sizing: border-box;
				width: 680rpx;
				height: 320rpx;
				background: #FFFFFF;
				border-radius: 24rpx 24rpx 24rpx 24rpx;
				margin-top: 24rpx;

				.tit {
					font-weight: 600;
					font-size: 28rpx;
					color: #3D3D3D;
				}

				.jiben {
					margin-top: 16rpx;
					display: flex;
					justify-content: space-between;

					.qian {
						font-size: 26rpx;
						color: #808080;
						width: 40%;
					}

					.shen {
						font-size: 26rpx;
						color: #3D3D3D;
					}
				}
			}

			.icons {
				// padding-top: 30rpx;
				padding-left: 50rpx;
				padding-right: 50rpx;
				box-sizing: border-box;
				width: 680rpx;
				max-height: 360rpx;
				background: #FFFFFF;
				border-radius: 24rpx 24rpx 24rpx 24rpx;
				margin: auto;
				display: flex;
				justify-content: space-between;
				flex-wrap: wrap;	
				margin-top: 26rpx;

				image {
					width: 96rpx;
					height: 96rpx;
					margin-top: 40rpx;
					margin-bottom: 40rpx;
					margin-right: 20rpx;
				}
			}
		}
	}
</style>