<template>
	<div :class="className" :style="{ height: height, width: width }" />
</template>

<script>
import echarts from 'echarts'
require('echarts/theme/macarons') // echarts theme
import { debounce } from '@/utils'
import { getOnOffCount } from '@/api/sDevice'

export default {
	props: {
		className: {
			type: String,
			default: 'chart',
		},
		width: {
			type: String,
			default: '100%',
		},
		height: {
			type: String,
			default: '27vh',
		},
		warnSum: {
			type: Number,
			default: 65
		}
	},
	data() {
		return {
			relayon: 0,
			relayoff: 0,
			devon: 0,
			devoff: 0,
			chart: null,
		}
	},
	mounted() {
		this.getOnOffCount()
		this.__resizeHandler = debounce(() => {
			if (this.chart) {
				this.chart.resize()
			}
		}, 100)
		window.addEventListener('resize', this.__resizeHandler)
	},
	beforeDestroy() {
		if (!this.chart) {
			return
		}
		window.removeEventListener('resize', this.__resizeHandler)
		this.chart.dispose()
		this.chart = null
	},
	methods: {
		getOnOffCount() {
			getOnOffCount().then(res => {
				if (res.relayon != null) {
					this.relayon = res.relayon
				}
				if (res.relayoff != null) {
					this.relayoff = res.relayoff
				}
				if (res.devon != null) {
					this.devon = res.devon
				}
				if (res.devoff != null) {
					this.devoff = res.devoff
				}
				// console.log(this.relayon, this.relayoff, this.devon, this.devoff)
				this.initChart()
			})
		},
		initChart() {
			this.chart = echarts.init(this.$el, 'macarons')
			let option = {
				title: [
					{
						text: '报警统计',
						textStyle: {
							color: '#000',	
							fontSize: 16,
							fontWeight: 800,
						},
						top: 10,
						left: 10,
					},

					{
						text: this.warnSum + '%',
						x: 'center',
						y: 'center',
						textStyle: {
							fontSize: '24',
							fontWeight: '600',
							color: '#000',
							textAlign: 'center',
						},
					},

					{
						text: '报警信息处理率：' + this.warnSum + '%',
						x: 'center',
						y: '89%',
						textStyle: {
							fontSize: '14',
							fontWeight: '600',
							color: '#000',
							textAlign: 'center',
						},
					},
				],
				polar: {
					radius: ['55%', '71%'],
					center: ['center', 'center'],
				},
				angleAxis: {
					max: 100,
					show: false,
				},
				radiusAxis: {
					type: 'category',
					show: true,
				},
				series: [
					{
						name: '在线监测系统/湿度',
						type: 'bar',
						roundCap: true,
						barWidth: 60,
						showBackground: true,
						backgroundStyle: {
							color: '#E0E0EC',
						},
						data: [this.warnSum],
						coordinateSystem: 'polar',
						itemStyle: {
							normal: {
								color: new echarts.graphic.LinearGradient(0, 1, 0, 0, [
									{
										offset: 0,
										color: '#0CF4FD',
									},
									{
										offset: 1,
										color: '#0954FD',
									},
								]),
							},
						},
					},
				],
			}

			this.chart.setOption(option)
		},
	},
}
</script>
