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

<script>
import * as echarts from 'echarts';
require('echarts/theme/macarons'); // echarts theme
import resize from '../mixins/resize';

const animationDuration = 1000;

export default {
	mixins: [resize],
	props: {
		className: {
			type: String,
			default: 'chart',
		},
		title: {
			type: String,
			default: 'chart',
		},
		width: {
			type: String,
			default: '100%',
		},
		height: {
			type: String,
			default: '300px',
		},
		allData: {
			type: Object,
			default: () => ({}),
		},
		histogram: {
			type: Array,
			default: () => [],
		},
	},
	data() {
		return {
			chart: null,
		};
	},
	beforeDestroy() {
		if (!this.chart) {
			return;
		}
		this.chart.dispose();
		this.chart = null;
	},
	methods: {
		initChart() {
			var nameArr = [];
			var valueArr = [];
			if (this.histogram.length > 0) {
				this.histogram.forEach((item) => {
					nameArr.push(item.time);
					valueArr.push(item.number);
				});
			} else {
				for (let i in this.allData) {
					nameArr.push(i);
					valueArr.push(this.allData[i]);
				}
			}
			this.chart = echarts.init(this.$el, 'macarons');

			this.chart.setOption({
				title: {
					text: '{space|}{tip|}{space|}{value|' + this.title + '}',
					left: '0%',
					top: '0%',
					textStyle: {
						rich: {
							tip: {
								width: 4,
								height: 16,
								backgroundColor: '#1FC495',
								marginRight: 6,
							},
							space: {
								width: 8,
							},
							value: {
								fontSize: 16,
								fontWeight: 'bold',
							},
						},
					},
				},
				tooltip: {
					trigger: 'axis',
					axisPointer: {
						// 坐标轴指示器，坐标轴触发有效
						type: 'shadow', // 默认为直线，可选为：'line' | 'shadow'
					},
				},
				grid: {
					top: 40,
					left: '2%',
					right: '2%',
					bottom: '3%',
					containLabel: true,
				},
				xAxis: [
					{
						type: 'category',
						data: nameArr,
						axisTick: {
							alignWithLabel: true,
						},
					},
				],
				yAxis: [
					{
						type: 'value',
						axisTick: {
							show: false,
						},
					},
				],
				series: [
					{
						name: 'pageA',
						type: 'bar',
						stack: 'vistors',
						barWidth: '60%',
						data: valueArr,
						animationDuration,
					},
				],
			});
		},
	},
};
</script>
