<template>
	<view class="uni-wrap">
		<uni-section class="mb-10" title="设备信息" type="line" titleFontSize="16">
			<template v-slot:right>
				<view @click="scanQR" :disabled="connected">
					<uni-icons type="scan" size="16"></uni-icons>
					<text style="padding-left: 5px;">扫码绑定</text>
				</view>
			</template>
			<uni-row>
				<uni-col :span="20">
					<text class="title">{{deviceId ? `已绑定设备：${deviceId}` : '未绑定设备'}}</text>
					<text class="title" v-if="power>0" style="padding-left: 5px;">电量:{{power}}</text>
				</uni-col>
				<uni-col :span="4">
					<button @click="toggleConnect()" type="primary" :plain="connected" :disabled="deviceId == ''"
						size="mini">
						{{connected ? '断开' : '连接'}}
					</button>
				</uni-col>
			</uni-row>
		</uni-section>
		<uni-section class="mb-10" title="数据测量" type="line" titleFontSize="16">
			<!-- <uni-data-select
				label="选择设备"
				v-model="r.device_name"
				:localdata="devices"
				:clear="false"
			>
			</uni-data-select>
			<uni-data-select
				label="选择测点"
				v-model="r.check_point"
				:localdata="checkPoints"
				:clear="false"
			>
			</uni-data-select> -->
			<uni-row>
				<uni-col :span="12">
					<button @click="collectVib()" type="primary" :disabled="!connected || processing">测振</button>
				</uni-col>
				<uni-col :span="12">
					<view class="padding">
						<button @click="collectTemp()" type="primary" :disabled="!connected || processing">测温</button>
					</view>
				</uni-col>
			</uni-row>
			<uni-row class="text">
				<uni-col>
					<text class="title">速度：{{r.velocity}} mm/s</text>
				</uni-col>
			</uni-row>
			<uni-row class="text">
				<uni-col>
					<text class="title">加速度：{{r.acceleration}} m/s<sup>2</sup></text>
				</uni-col>
			</uni-row>
			<uni-row class="text">
				<uni-col>
					<text class="title">位移：{{r.displacement}} &micro;m</text>
				</uni-col>
			</uni-row>
			<uni-row class="text">
				<uni-col>
					<text class="title">温度：{{r.temperature}} &deg;C</text>
				</uni-col>
			</uni-row>
			<uni-row>
				<uni-col>
					<view class="padding">
						<button @click="save()" type="primary" :disabled="saved">保存</button>
					</view>
				</uni-col>
			</uni-row>
		</uni-section>
		<uni-section class="mb-10" title="数据查看" type="line" titleFontSize="16">
			<uni-row>
				<uni-col :span="12">
					<view class="padding">
						<button @click="toPage('/pages/records/records')" type="primary">查看历史数据</button>
					</view>
				</uni-col>
				<uni-col :span="12">
					<view class="padding">
						<button @click="toPage('/pages/records/chart')" type="primary">查看趋势图</button>
					</view>
				</uni-col>
			</uni-row>
		</uni-section>
		<view class="content">
			<text>{{msg}}</text>
		</view>
		<uni-popup ref="popup" :is-mask-click="false">
			<view class="chart-pop">
				<uni-card>
					<uni-row>
						<uni-col>
							<l-echart ref="wChart" @finished="initChart" custom-style="width:100%;"></l-echart>
						</uni-col>
					</uni-row>
					<uni-row>
						<uni-col :span="8">
							<view class="center">
								<button @click="closePop()" size="mini">取消</button>
							</view>
						</uni-col>
						<uni-col :span="8">
							<view class="center">
								<button @click="collectVib()" size="mini">重测</button>
							</view>
						</uni-col>
						<uni-col :span="8">
							<view class="center">
								<button @click="saveCheck()" size="mini" type="primary">保存</button>
							</view>
						</uni-col>
					</uni-row>
				</uni-card>
			</view>
		</uni-popup>
	</view>
</template>

<script>
	import Vue from 'vue';
	import db from '@/service/db';
	import {
		devices,
		checkPoints
	} from '@/service/common';
	import * as echarts from '@/uni_modules/lime-echart/static/echarts.min';

	const Ewg = uni.requireNativePlugin('UniCollectionUtils');
	let vibData = {
		velocity: null,
		acceleration: null,
		displacement: null,
		wave: [],
		power: -1,
	};

	function now() {
		const _now = formatTime(new Date());
		return _now;
	}

	function formatTime(d, fmt = 'yyyy-MM-dd hh:mm:ss') {
		const opt = {
			'y+': d.getFullYear().toString(), // 年
			'M+': (d.getMonth() + 1).toString(), // 月
			'd+': d.getDate().toString(), // 日
			'h+': d.getHours().toString(), // 时
			'm+': d.getMinutes().toString(), // 分
			's+': d.getSeconds().toString() // 秒
		}
		let dateString = fmt;
		for (const k in opt) {
			const ret = new RegExp('(' + k + ')').exec(dateString);
			if (ret) {
				if (/(y+)/.test(k)) {
					dateString = dateString.replace(ret[1], opt[k].substring(4 - ret[1].length))
				} else {
					dateString = dateString.replace(ret[1], (ret[1].length === 1) ? (opt[k]) : (opt[k].padStart(ret[1]
						.length, '0')))
				}
			}
		}
		return dateString;
	}

	export default Vue.extend({
		data() {
			const r = {
				temperature: null,
				velocity: null,
				acceleration: null,
				displacement: null,
				create_time: null,
				operate_time: null,
				wave: null,
			};
			return {
				buttonTitle: '连接设备',
				msg: '.',
				deviceId: '',
				power: -1,
				connected: false,
				processing: false,
				saved: true,
				r,
				extraIcon: {
					size: '22',
					type: 'list'
				},
				devices,
				checkPoints
			};
		},
		onLoad() {
			uni.setNavigationBarTitle({
				title: '蓝牙测振Demo V' + uni.getAppBaseInfo().appVersion
			});
			uni.getStorage({
				key: 'deviceId',
				success: (res) => {
					console.log(`get deivceId: ${res.data}`);
					this.deviceId = res.data;
				}
			});
			plus.android.requestPermissions(["android.permission.ACCESS_FINE_LOCATION"], (i) => {
				console.log(i);
			}, (e) => {
				console.error(e);
			});
			plus.android.requestPermissions(["android.permission.BLUETOOTH_CONNECT"], (i) => {
				console.log(i);
			}, (e) => {
				console.error(e);
			});
			plus.android.requestPermissions(["android.permission.BLUETOOTH_CONNECT"]);
			plus.android.requestPermissions(["android.permission.BLUETOOTH_SCAN"]);
			// initBL();
		},
		onUnload() {},
		methods: {
			toggleConnect() {
				uni.showLoading({
					title: '加载中'
				});
				if (this.connected) {
					Ewg.disConnect(this.deviceId, (res) => {
						console.log("断开设备", JSON.stringify((res)));
						this.msg = '设备已断开';
						this.connected = false;
						uni.hideLoading();
					});
				} else {
					Ewg.connect(this.deviceId, (res) => {
						console.log("连接设备", JSON.stringify((res)))
						this.msg = '设备已连接';
						this.connected = true;
						uni.hideLoading();
					});
				}
			},
			collectTemp() {
				this.msg = '正在测温';
				uni.showLoading({
					title: this.msg
				});
				this.processing = true;
				this.r.temperature = null;
				Ewg.collectTemp("0.95", (res) => {
					console.log("测温", JSON.stringify((res)));
					this.stop();
					if (res.result == 0) {
						this.r.temperature = res.temperature;
						this.r.operate_time = now();
						this.power = res.battery;
						this.msg = `温度结果：${JSON.stringify((res))}`;
						this.saved = false;
					} else {
						this.r.temperature = null;
						this.power = -1;
						this.msg = `测温异常：${JSON.stringify((res))}`;
					}
					uni.hideLoading();
				});
			},
			collectVib() {
				this.msg = '正在测振';
				this.openPop();
				uni.showLoading({
					title: this.msg
				});
				// TODO: 调整清除数据的内容
				this.processing = true;
				this.r.velocity = null;
				this.r.acceleration = null;
				this.r.displacement = null;
				this.r.wave = null;
				console.log('开始测振');
				// 0 --加速度  1--速度  2--位移
				Ewg.collectVib(1, "5120", "2048", true, (res) => { // 注意：只有带波形时才会把在个值都返回
					this.stop();
					if (res.result == 0) {
						vibData.velocity = res.speedValue;
						vibData.acceleration = res.accValue;
						vibData.displacement = res.disValue;
						vibData.wave = res.waveData;
						vibData.power = res.battery;
						this.waveChart();
						// this.r.velocity = res.speedValue;
						// this.r.acceleration = res.accValue;
						// this.r.displacement = res.disValue;
						// this.r.wave = res.waveData!.join(',');
						// this.r.operate_time = now();
						// this.power = res.battery;
						// this.msg = `温振完成`;
						// this.saved = false;
					} else {
						this.r.velocity = null;
						this.r.acceleration = null;
						this.r.displacement = null;
						this.r.wave = null;
						this.power = -1;
						this.msg = `测振异常：${JSON.stringify((res))}`;
					}
					uni.hideLoading();
				});
			},
			stop() {
				Ewg.stopCollect();
				this.msg = '停止测量';
				this.processing = false;
			},
			scanQR() {
				uni.scanCode({
					onlyFromCamera: true,
					scanType: ['qrCode'],
					success: (res) => {
						const did = res.result;
						console.log(`条码内容：${did}`);
						if (did?.startsWith('expert-')) {
							this.deviceId = did.substring('expert-'.length);
							uni.setStorageSync('deviceId', this.deviceId);
						} else {
							this.msg = `error device: ${did}`;
						}
					}
				});
			},
			save() {
				console.log(JSON.stringify(this.r));
				// if (!this.r.check_point || !this.r.device_name) {
				// 	uni.showModal({
				// 		title: '提醒',
				// 		showCancel: false,
				// 		content: `请选择'设备'及'测点'`
				// 	});
				// 	return;
				// }
				db.insertTableData('records', this.r).then(
					() => {
						this.saved = true;
						this.msg = '测量数据已保存';
						uni.showToast({
							title: '保存成功',
							icon: 'success',
							mask: true
						});
					},
					(e) => {
						this.saved = false;
						console.log(`保存失败：${JSON.stringify(e)}`);
						this.msg = '测量数据保存失败';
						uni.showModal({
							title: '保存失败',
							showCancel: false,
							content: JSON.stringify(e)
						});
					}
				);
			},
			toPage(path) {
				uni.navigateTo({
					url: path
				});
			},
			openPop() {
				this.$refs.popup.open();
			},
			async initChart() {
				this.$refs.wChart.init(echarts,
					chart => chart.setOption({
						// grid: {
						// 	left: 40,
						// 	right: 110
						// },
						// tooltip: {
						// },
						xAxis: {
							type: 'category',
							name: '时间(ms)',
							splitLine: {
								show: true
							},
							axisLabel: {
								formatter: function(value, index) {
									return Math.round(value * 10) / 10;
								},
								// showMaxLabel: true,
							},
						},
						yAxis: [
							// {
							// type: 'value',
							// boundaryGap: [0, '100%'],
							// splitLine: {
							// 	show: false
							// }
							{
								position: 'left',
								type: 'value',
								name: '速度(mm/s)',
								axisLine: {
									show: true
								},
								splitLine: {
									show: true
								}
							}
						],
						series: [{
							type: 'line',
							smooth: true,
							name: '速度',
							yAxisIndex: 0,
						}]
					}), {
						locale: "ZH"
					},
				);
				uni.onWindowResize(res => {
					this.$refs.wChart?.resize();
				});
			},
			closePop() {
				this.$refs.popup.close();
			},
			saveCheck() {
				this.r.acceleration = vibData.acceleration;
				this.r.displacement = vibData.displacement;
				this.r.velocity = vibData.velocity;
				this.r.wave = vibData.wave.join(',');
				this.r.operate_time = now();
				this.power = vibData.power;
				this.msg = `温振完成`;
				this.saved = false;
				this.closePop();
			},
			waveChart() {
				const wave = vibData.wave;
				const point = wave.length;
				const samplingRate = 5120;
				const times = [];
				const duration = (1000 * point) / samplingRate;
				console.log(`duration: ${duration}`);
				const timespace = duration / (point - 1);
				for (let i = 0; i < point; i++) {
					times.push(i * timespace);
				}
				this.$refs.wChart.setOption({
					xAxis: {
						data: times
					},
					series: [{
						data: wave
					}]
				});
			}
		}
	});
</script>

<style>
	.uni-wrap {
		background-color: #efeff4;
	}

	.uni-row {
		padding: 10px;
	}

	.uni-row.text {
		padding-top: 2px;
		padding-bottom: 2px;
	}

	.padding {
		padding: 0 5px;
	}

	.mb-10 {
		margin-bottom: 10px;
	}

	.content {
		padding: 20px;
		background-color: #fff;
	}

	.title {
		font-size: 16px;
	}

	.chart-pop {
		width: 100vw;
	}

	.center {
		display: flex;
		justify-content: center;
	}
</style>