<template>
	<view class="weightPages">
		<view class="table" v-if="isConnection == 0">称重中，请将食物放到秤上</view>
		<view class="table" v-if="isConnection == 1" @click="openBluetoothAdapter">连接失败，点击重新连接</view>
		<view class="image" v-if="isConnection != 3">
			<image src="../static/cheng.png"></image>
		</view>
		<view v-if="isConnection == 3">
			<view class="weight">
				<view>重量<text>{{weight}}</text>{{dw}}</view>
				<view>热量<text>{{kcal}}</text>千卡</view>
			</view>
			<view class="tips">
				注：重新称重可更新当前数据
			</view>
			<view class="groupbtn" v-if="weightType!=2">
				<view class="btn" @click="handleDetailSub">完成</view>
				<view class="btn" @click="handleDetailNext" v-if="!stopblue">下一位</view>
			</view>
			<view class="btn" @click="handlesub" v-if="weightType==2">确认添加</view>
		</view>


		<view class="tips" v-if="isConnection == 1">
			<uni-icons type="info-filled" color="#dd524d" size="20"></uni-icons>
			请确定设备是开机状态、手机蓝牙权限已打开！
		</view>
	</view>
</template>

<script>
	import {
		mapState
	} from "vuex";
	let myTime
	let nextCnt = 0
	const plugin = requirePlugin("sdkPlugin").AiLink;
	export default {
		data() {
			return {
				dw: "g",
				kcal: "",
				weight: "",
				weightALL: "",
				weight0: 0,
				stopblue: false,
				isConnection: 0, //是否连接成功
			}
		},
		props: {
			weightType: {
				type: Number,
				default: -1 //0分类称重,1累计称重,2购物车称重
			},
			isLast: {
				type: Boolean,
				default: false
			}
		},
		computed: {
			...mapState(["user", 'isConnected', "isBluetoothTyle"]),
		},
		mounted() {
			let that = this
			console.log("mounted", that.weightType)
			that.openBluetoothAdapter()
			that.onBLEConnectionStateChange()
			uni.onBluetoothAdapterStateChange(function(res) {
				that.$store.commit("changeBluetooth", res.available);
			})
		},
		watch: {
			weightType: function() {
				let that = this
				that.openBluetoothAdapter()
			},
			isBluetoothTyle: function() {
				let that = this
				if (!that.isBluetoothTyle) {
					that.handleBack()
				}
			},
			isLast: function() {
				let that = this
				that.stopblue = that.isLast
				console.log("最后", this.isLast)

			}
		},
		methods: {
			// 初始化蓝牙
			openBluetoothAdapter() {
				let that = this
				that.weight = ""
				that.kcal = ""
				uni.openBluetoothAdapter({
					success: e => {
						that.isConnection = 0
						that.startBluetoothDeviceDiscovery()
					},
					fail: e => {
						that.isConnection = 1
						console.log('openBluetoothAdapter', e)
						that.$tools.msg("请确定设备是开机状态、手机蓝牙权限已打开！")
					}
				});
			},
			// 开始搜寻附近的蓝牙外围设备
			startBluetoothDeviceDiscovery() {
				let that = this
				uni.startBluetoothDevicesDiscovery({
					allowDuplicatesKey: true,
					services: [
						"F0A0",
					],
					success: res => {
						that.isConnection = 0
						that.onBluetoothDeviceFound();
					},
					fail: res => {
						that.isConnection = 1
						console.log('startBluetoothDeviceDiscovery', res)
						that.$tools.msg("请确定设备是开机状态、手机蓝牙权限已打开！")
					}
				});
			},
			// 监听蓝牙连接状态
			onBLEConnectionStateChange() {
				let that = this
				uni.onBLEConnectionStateChange(function(res) {
					console.log("监听蓝牙连接状态", res.connected)
					if (!res.connected) {
						that.isConnection = 1
						that.closeBLEConnection()
						that.closeBluetoothAdapter()
					}
					that.$store.commit("changeConnected", res.connected);
				})
			},
			/**
			 * 停止搜索蓝牙设备
			 */
			stopBluetoothDevicesDiscovery() {
				uni.stopBluetoothDevicesDiscovery({
					success: e => {
						console.log("停止搜索蓝牙设备", e)
					},
				});
			},
			/**
			 * 发现外围设备
			 */
			onBluetoothDeviceFound() {
				var that = this;
				that.isConnection = 0
				uni.onBluetoothDeviceFound(res => {
					res.devices.forEach(device => {
						device.advertisData = device.advertisData ? device.advertisData : ''
						device.advertisServiceUUIDs = device.advertisServiceUUIDs ? device
							.advertisServiceUUIDs : ""
						if (!device.name && !device.localName) {
							return
						}
						if (device.name.indexOf("EL") !== -1 && device.advertisServiceUUIDs != '') {
							clearTimeout(myTime);
							that.isConnection = 3
							let value = that.$tools.ab2hex(device.advertisData)
							let parseDataRes = plugin.parseBroadcastData(device.advertisData)
							let analyzeData = plugin.analyzeBroadcastScaleData(parseDataRes)
							let analyzeDataText = analyzeData.text
							let data = analyzeData.data
							if (parseDataRes.status == 1) {
								let data0 = parseDataRes.payload
								let data = parseInt(data0[3]).toString(16)
								let data1 = parseInt(data0[4]).toString(16)
								let data2 = parseInt((data + data1), 16) //重量
								// 
								let unit0 = parseInt(data0[5]).toString(16) //单位小数点
								let unit = unit0.length > 1 ? unit0.substring(1, 2) : unit0 //单位
								let num = parseInt(unit0.substring(0, 1), 16).toString(8)
								let dot = num.toString().substring(0, 1) //小数点
								let zfz = 0 //正负值
								if (num.toString().length > 1) {
									dot = num.toString().substring(1, 2)
									zfz = num.toString().substring(0, 1)
								}
								if (unit == "7") {
									that.dw = "ml"
								}
								if (unit == "3") {
									that.dw = "oz"
								}
								if (unit == "2") {
									that.dw = "lb'oz"
								}

								if (dot == "1") {
									data2 = data2 / 10
								}
								if (dot == "2") {
									data2 = data2 / 100
								}
								if (zfz == "0") {
									data2 = data2
								}
								if (zfz == "1") {
									data2 = "-" + data2
								}
								that.weight = data2
								console.log("analyzeData", data.weight, data2)
							}
						}
					})
				});
			},
			// 保存测量结果 
			handlesub() {
				let that = this
				console.log("weight", that.weight)
				if (Number(that.weight) > 0) {
					that.$emit("handleBle", that.weight, that.dw, that.kcal)
					that.stopBluetoothDevicesDiscovery() //取消蓝牙搜索
					that.closeBLEConnection()
					that.closeBluetoothAdapter()
				} else {
					that.$tools.msg("数据异常，请清零后重新称重!")
				}

			},
			// 备料完成
			handleDetailSub() {
				let that = this
				if (that.weightType == 1) {
					that.weight0 = Number(that.weight) - Number(that.weightALL)
					that.weightALL = that.weight
				} else {
					that.weight0 = that.weight
				}
				if (Number(that.weight0) > 0) {
					that.$emit("handleDetailSub", that.weight0, that.dw, that.kcal)
					that.stopBluetoothDevicesDiscovery() //取消蓝牙搜索
					that.closeBLEConnection()
					that.closeBluetoothAdapter()
					that.weight = 0
					that.weight0 = 0
				} else {
					that.$tools.msg("数据异常，请清零后重新称重!")
				}
			},
			//备料下一个
			handleDetailNext() {
				let that = this
				if (that.weightType == 1) {
					that.weight0 = Number(that.weight) - Number(that.weightALL)
					that.weightALL = that.weight
				} else {
					that.weight0 = that.weight
				}
				if (Number(that.weight0) > 0) {
					that.$emit("handleDetailNext", that.weight0, that.dw, that.kcal)
					that.weight = 0
					that.weight0 = 0
				} else {
					that.$tools.msg("数据异常，请清零后重新称重!")
				}
			},

			handleBack() {
				let that = this
				that.isConnection = 1
				that.stopBluetoothDevicesDiscovery() //取消蓝牙搜索
				that.closeBLEConnection()
				that.closeBluetoothAdapter()
			},
			/**
			 * 断开蓝牙模块
			 */
			closeBluetoothAdapter() {
				let that = this;
				uni.closeBluetoothAdapter({
					success: res => {
						console.log('蓝牙模块关闭成功');
					}
				})
			},
			/**
			 * 断开蓝牙连接
			 */
			closeBLEConnection() {
				var that = this;
				uni.closeBLEConnection({
					deviceId: that.deviceId,
					success: res => {
						console.log('断开蓝牙连接成功');
					}
				});
			},
		},
	}
</script>

<style scoped lang="scss">
	.weightPages {
		display: flex;
		flex-wrap: wrap;
		flex-direction: column;
		position: absolute;
		justify-content: space-around;
		left: 0;
		right: 0;
		bottom: 20px;
		top: 60px;

		.weight {
			background: #fff;
			color: #666;
			font-size: 16px;
			flex-wrap: wrap;
			text-align: center;

			view {
				width: 60%;
				height: 50px;
				display: flex;
				margin-left: 25%;
				align-items: flex-end;
				margin-bottom: 15px;

				text {
					width: 80px;
					display: inline-block;
					border-bottom: 1px solid #dfdfdf;
					margin: 0 10px;
					font-size: 18px;
					font-weight: bold;
					color: #f0ae43;
				}
			}
		}

		.tips {
			font-size: 12px;
			text-align: center;
		}

		.btn {
			color: #fff;
			width: 80%;
			margin-left: 10%
		}

		.groupbtn {
			.btn {
				color: #000 !important;
			}
		}

		.table {
			width: 100%;
			font-size: 16px;
			font-weight: bold;
			text-align: center;
			margin: 15px 0;
		}

		.image {
			width: 160px;
			height: 160px;
			margin: auto;

			image {
				width: 100%;
				height: 100%;
			}
		}

		.tips {
			margin-bottom: 15px;
			margin-left: 15px;
			display: flex;
			color: #999;
		}
	}
</style>
