<template>
	<view class="charts">
		<view v-if="chartType!='table'">
			<div class="moreTime">
				<div v-for="(item,index) in range" :key="index" @click="change(index)"
					:class="choiceTime===index?'bod':''">
					{{item}}
				</div>
			</div>
			<div class="childTime">
				<div v-for="(item,index) in childTime" v-show="choiceTime===index">
					<template>
						<template v-for="(o,i) in item">
							<div @click="getTime(i,o.value)" :class="choiceChildTime===i?'box':''">{{o.text}}</div>
						</template>
					</template>
				</div>
			</div>
			<view style="height:300px">
				<l-echart ref="chartRef" @finished="getServerData(true)"></l-echart>
			</view>
		</view>

		<scroll-view v-if="chartType=='table'" style="width: 100%;height: 350px;" scroll-y="true">
			<view>
				<text class="tabletitle">{{tableTitle}}</text>
			</view>
			<uni-table ref="table" border stripe emptyText="暂无更多数据">
				<uni-tr>
					<uni-th width="100" align="left">点位</uni-th>
					<uni-th width="100" align="left">最新值</uni-th>
				</uni-tr>
				<uni-tr v-for="(item, index) in tableData" :key="index">
					<uni-td>{{ item.itemName }}</uni-td>
					<uni-td>
						<view class="name">{{ item.itemValue }}</view>
					</uni-td>
				</uni-tr>
			</uni-table>
		</scroll-view>
	</view>
</template>

<script>
	import {
		nowDate,
		timeToDate
	} from '../../utils/date.js'
	// nvue 不需要引入
	// #ifdef VUE2
	import * as echarts from '@/uni_modules/lime-echart/static/echarts.min';
	// #endif
	// #ifdef VUE3
	// #ifdef MP
	// 由于vue3 使用vite 不支持umd格式的包，小程序依然可以使用，但需要使用require
	const echarts = require('../../static/echarts.min');
	// #endif
	// #ifndef MP
	// 由于 vue3 使用vite 不支持umd格式的包，故引入npm的包
	import * as echarts from 'echarts/dist/echarts.esm';
	// #endif
	// #endif
	export default {
		components: {

		},
		props: {
			//图表类型 bar,line,pie,table
			chartType: {
				type: String,
				default: 'bar'
			},
			//图表高度
			height: {
				type: String,
				default: '300px'
			},
			//后台定义的图表id
			chartId: {
				type: Number,
				default: ''
			}
		},
		
		data() {
			return {
				seriesData: [],
				timeData:[],
				option: {},
				tableData: [],
				tableTitle:'数据表格',
				range: ["分", "时", "日", "周"],
				childTime: [
					[{
							value: 900000,
							text: "15分"
						},
						{
							value: 1800000,
							text: "30分"
						},
						{
							value: 2700000,
							text: "45分"
						}
					],
					[{
							value: 3600000,
							text: "1小时"
						},
						{
							value: 21600000,
							text: "6小时"
						},
						{
							value: 43200000,
							text: "12小时"
						},
						{
							value: 64800000,
							text: "18小时"
						}
					],
					[{
							value: 86400000,
							text: "1日"
						},
						{
							value: 259200000,
							text: "3日"
						},
						{
							value: 432000000,
							text: "5日"
						}
					],
					[{
							value: 604800000,
							text: "1周"
						},
						{
							value: 1209600000,
							text: "2周"
						},
						{
							value: 1814400000,
							text: "3周"
						},
						{
							value: 2419200000,
							text: "4周"
						}
					],
				],
				startTime: null,
				endTime:null,
				choiceTime: 0,
				choiceChildTime: 0,
				chartTime:null,
				chartInterval:3000,
			};
		},
		created() {
			this.startTime = timeToDate(new Date().getTime() - 900000)
			this.endTime = timeToDate(new Date().getTime())
		},
		mounted() {
			if(this.chartType=='table'){
				this.getServerData(true)
			}
		},
		methods: {
			async init() {
				// chart 图表实例不能存在data里
				const chart = await this.$refs.chartRef.init(echarts)
				chart.setOption(this.option)
				
				if(this.chartTime==null){
					this.chartTime = setInterval(()=>{
						this.getServerData(false)
					},this.chartInterval)
				}
			},
			//分时日周选择
			change(i) {
				this.choiceTime === i ? this.choiceTime = -1 : this.choiceTime = i
				this.choiceChildTime = -1
			},
			//二级时间选择
			getTime(i, val) {
				this.choiceChildTime = i
				this.startTime = timeToDate(new Date().getTime() - val)
				this.getServerData(true);
			},
			//获得图表数据
			getServerData(first) {
				let id = this.chartId
				let startTime = null
				let endTime = null
				if(first){
					startTime = this.startTime
					endTime = this.endTime
				}else{
					startTime = this.endTime
					endTime = timeToDate(new Date().getTime())
					this.endTime = endTime
				}
				//获取数据
				uni.$http.get(`/chart/getChartById?id=${id}&startTime=${startTime}&endTime=${endTime}`).then(res => {
					const data = res.data.data;
					const chartData = data.chartItemList
					//x轴数据，时间轴
					const timeData = chartData[0].valueTimeList
					const bucketType = data.bucketType
					const bucketValue = data.bucketValue
					this.chartInterval = this.getChartInterval(bucketType,bucketValue)
					let optionData = this.getChartOption(this.chartType)
					//y轴数据，数据轴
					if (this.chartType == 'bar' || this.chartType == 'line') {
						optionData.title.text = data.chartName
						const series = chartData.map(item => {
							return {
								name: item.describe ? item.describe : item.itemReadName,
								data: item.valueList,
								type: this.chartType
							}
						})
						if(first){
							this.seriesData = series
							this.timeData = timeData
						}else{
							//追加x轴数据
							this.timeData = this.timeData.concat(timeData);
							this.timeData.splice(0,timeData.length)
							//追加y轴数据
							series.forEach((item,index)=>{
								this.seriesData.forEach((sitem,sindex)=>{
									if(item.name==sitem.name){
										sitem.data = sitem.data.concat(item.data);
										sitem.data.splice(0,item.data.length)
									}
								})
							});
							
						}
						optionData.xAxis.data = this.timeData
						optionData.series = this.seriesData
					} else if (this.chartType == 'pie') {
						optionData.title.text = data.chartName
						const {
							valueList,
							valueTimeList
						} = chartData[0]
						let sdata = valueTimeList.map((item, i) => {
							return {
								name: item,
								value: valueList[i]
							}
						});
						if(first){
							this.seriesData = sdata
						}else{
							this.seriesData = this.seriesData.concat(sdata)
							this.seriesData.splice(0,sdata.length)
						}
						optionData.series = [{
							type: 'pie',
							radius: '55%',
							label: {
								show: false
							},
							data: this.seriesData,
							center: ['70%', '50%']
						}]
					} else if (this.chartType == 'table') {
						let dataList = [];
						for (let dataItem of chartData) {
							let data = {
								itemName: dataItem.describe != null ? dataItem.describe : dataItem
									.itemReadName,
								itemValue: dataItem.valueList[0],
								itemAlert: dataItem.valueTimeList[0],
							};
							dataList.push(data)
						}
						this.tableData = dataList
						this.tableTitle = data.chartName
						//定时刷新
						this.chartInterval = 3000
						if(this.chartTime==null){
							this.chartTime = setInterval(()=>{
								this.getServerData(false)
							},this.chartInterval)
						}
					}
					if(this.chartType!='table'){
						this.option = optionData
						if(first){
							this.init()
						}else{
							this.$refs.chartRef.setOption(this.option)
						}
					}
				});
			},
			getChartInterval(bucketType,bucketValue){
				let time = null
				switch (bucketType) {
					case 1:
						time = 86400000 * bucketValue
							
						break;
					case 2:
						time = 3600000 * bucketValue
							
						break;
					case 3:
						time = 60000 * bucketValue
							
						break;
					case 4:
						time = 1000 * bucketValue
						break;
				}
				return time
			},
			//获得图表option数据
			getChartOption(cType) {
				let option = {}
				if (cType == 'bar') {
					option = {
						title: {
							text: '',
							textStyle: {
								color: '#666666',
								fontWeight: 'normal',
								fontSize: '14'
							}
						},
						xAxis: {
							type: 'category',
							data: [],
							axisLabel: {
								formatter: function(value) {
									return value.substring(11, 19) + "\n" + value.substring(0, 10).split('-').join(
										'')
								}
							}
						},
						yAxis: {
							type: 'value'
						},
						legend: {
							type: 'scroll',
							top: 30
						},
						tooltip: {
							trigger: 'axis',
							axisPointer: {
								type: 'cross',
								lineStyle: {
									type: 'dashed'
								},
								label: {
									show: false
								}
							},
							textStyle: {
								color: '#ffffff'
							},
							confine: true,
							extraCssText: 'white-space: normal; word-break: break-all;',
							backgroundColor: 'rgba(108,106,120,0.9)',
							position: 'inside',
							// formatter: function(params) {
							// 	let result = ''
							// 	for (let i in params) {
							// 		let value = '--'
							// 		if (params[i].data !== null) {
							// 			value = params[i].data
							// 		}
							// 		result += params[i].seriesName + '：' + value
							// 	}
							// 	return result
							// }
						},
						dataZoom: [{
								type: 'slider',
								show: true,
								start: 90,
								end: 100
							},

						],
						series: []
					};
				} else if (cType == 'line') {
					option = {
						title: {
							text: '',
							textStyle: {
								color: '#666666',
								fontWeight: 'normal',
								fontSize: '14'
							}
						},
						xAxis: {
							type: 'category',
							data: [],
							axisLabel: {
								formatter: function(value) {
									return value.substring(11, 19) + "\n" + value.substring(0, 10).split('-').join(
										'')
								}
							}
						},
						yAxis: {
							type: 'value'
						},
						legend: {
							type: 'scroll',
							top: 30
						},
						tooltip: {
							trigger: 'axis',
							axisPointer: {
								type: 'cross',
								lineStyle: {
									type: 'dashed'
								},
								label: {
									show: false
								},
							},
							textStyle: {
								color: '#ffffff'
							},
							confine: true,
							extraCssText: 'white-space: normal; word-break: break-all;',
							backgroundColor: 'rgba(108,106,120,0.9)', //通过设置rgba调节背景颜色与透明度
							position: 'inside',
							// formatter: function(params) {
							// 	let result = ''
							// 	for (let i in params) {
							// 		let value = '--'
							// 		if (params[i].data !== null) {
							// 			value = params[i].data
							// 		}
							// 		result += params[i].seriesName + '：' + value + '<br/>'
							// 	}
							// 	return result
							// }
						},
						dataZoom: [
							{
								type: 'slider',
								show: true,
								start: 90,
								end: 100,
								bottom: 10
							}
						],
						series: []
					};
				} else if (cType == 'pie') {
					option = {
						title: {
							text: '',
							textStyle: {
								color: '#666666',
								fontWeight: 'normal',
								fontSize: '14'
							}
						},
						legend: {
							type: 'scroll',
							orient: 'vertical',
							left: 'left',
							top: 20
						},
						tooltip: {
							trigger: 'item',
							confine: true,
							extraCssText: 'white-space: normal; word-break: break-all;',
							backgroundColor: 'rgba(108,106,120,0.9)',
							textStyle: {
								color: '#ffffff'
							},
						},
						series: []
					};
				}
				return option
			}
		}
	};
</script>

<style scoped>
	.charts {
		height: 400px;
	}

	.moreTime {
		display: flex;
		justify-content: space-between;
		align-items: center;
		width: 80vw;
		margin: auto
	}

	.bod {
		border-bottom: 3px solid #007AFF;
	}

	.box {
		border: 1px solid #007AFF !important;
	}

	.childTime {

		margin: 16rpx 60rpx 0 60rpx;
	}

	.childTime>div {
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.childTime>div>div {
		width: 140rpx;
		padding: 10rpx;
		border: 1px solid #e6e6e6;
		border-radius: 16rpx;
		color: #7e7e7e;
		font-size: 28rpx;
		text-align: center;
	}
	.tabletitle{
		font-size: 14px;
		padding: 8px 10px;
		font-weight: bold;
		color: #606266;
	}
	
	.uni-table-td {
	    display: table-cell;
	    padding: 8px 10px;
	    font-size: 14px;
	    border-bottom: 1px #0a48d9 solid;
		border-right: 1px #0a48d9 solid;
	    font-weight: 400;
	    color: #606266;
	    line-height: 23px;
	    box-sizing: border-box;
	}
	.uni-table-th {
	    padding: 12px 10px;
	    display: table-cell;
	    box-sizing: border-box;
	    font-size: 14px;
	    font-weight: bold;
	    color: #909399;
		border-top: 1px #0a48d9 solid;
		border-right: 1px #0a48d9 solid;
	    border-bottom: 1px #0a48d9 solid;
	}
</style>