<template>
	<view>
		<uni-section class="section" title="振动波形图" type="line" titleFontSize="16">
			<l-echart ref="chart"></l-echart>
		</uni-section>
		<uni-section class="section" title="频谱图" type="line" titleFontSize="16">
			<l-echart ref="chartt" @finished="initChart"></l-echart>
		</uni-section>
	</view>
</template>

<script>
	import * as echarts from '@/uni_modules/lime-echart/static/echarts.min';
	import db from '@/service/db';
	import {devices, checkPoints} from '@/service/common';
	import {fft} from '@/js/fft/fft';
	import * as util from "@/js/fft/fftutil";

	const chartData = {
		wave: [],
		vs: [],
	}
	const options = {
		// 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;
			  },
			},
		},
		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,
		}]
	};
	const options_t = {
		xAxis: {
			type: 'category',
			name: '频率(Hz)',
			axisLabel: {
			  formatter: function (value, index) {
				return Math.round(value * 10) / 10;
			  },
			  // showMaxLabel: true,
			  // interval:1
			},
			// splitLine: {
			// 	show: true
			// }
		},
		yAxis: {
			type: 'value',
			name: '振幅',
			// splitLine: {
			// 	show: false
			// }
		},
		series: [{
			name: '振幅',
			type: 'line',
			// smooth: true,
			// yAxisIndex: 0,
		}],
		dataZoom: [{
			type: "inside",
		}],
	};

	export default {
		data() {
			return {
				id: null,
			};
		},
		onLoad(option) {
			this.id = option.id;
			chartData.wave = [];
		},
		methods: {
			async loadChartData() {
				const sql = `select wave from records where id = ${this.id}`;
				const records = await db.select(sql);
				if (records.length < 1) {
					alert("no record found");
					return;
				}
				const wave = records[0].wave.split(',');
				const point = 2048;
				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++) {
					chartData.wave.push(parseFloat(wave[i]));
					times.push(i * timespace);
				}
				// console.log(`times.length: ${times.length}, wave.length: ${chartData.wave.length}`);
				this.$refs.chart.setOption({xAxis: {data: times}, series: [{data: chartData.wave}]});

				const phasors = fft(chartData.wave);

				const resultSize = phasors.length / 8;
				let frequencies = util.fftFreq(phasors, samplingRate);
				frequencies = frequencies.slice(0, resultSize);
				
				let magnitudes = util.fftMag(phasors);
				const magnitudeSize = magnitudes.length;
				magnitudes = magnitudes.slice(0, resultSize);
				magnitudes = magnitudes.map(function (v, ix) {
				  return v / magnitudeSize;
				});
				magnitudes[0] = 0; // 清除 0Hz 的直流分量
				// console.log(`frequencies:[${frequencies[0]},${frequencies[frequencies.length-1]}], magnitudes[0]:[${magnitudes[0]}]`);
				// console.log(`magnitudes: ${magnitudes[0]}, ${magnitudes[1]}, ${magnitudes[2]}, ${magnitudes[3]}, ${magnitudes[4]}, ${magnitudes[5]}, ${magnitudes[6]}, ${magnitudes[7]}, ${magnitudes[8]}, ${magnitudes[9]}`);
				// console.log("magnitudes: ", magnitudes);

				this.$refs.chartt.setOption({xAxis: {data: frequencies}, series: [{data: magnitudes}]});
			},
			async initChart() {
				await this.$refs.chart.init(echarts, chart => chart.setOption(options), { locale: "ZH" });
				await this.$refs.chartt.init(echarts, chart => chart.setOption(options_t), { locale: "ZH" });

				this.loadChartData().catch(reason => console.error(reason));

				uni.onWindowResize(res => {
					this.$refs.chart?.resize();
					this.$refs.chartt?.resize();
				})
			}
		}
	}
</script>

<style lang="scss">
	.section {
		margin: 10px 0;
	}
</style>