<template>
	<div class="pie-block">
		<div class="pie-data">
			<div v-for="(soft, index) in chartData.Soft" :class="['data-cell']" :data-soft="soft">
				<div class="light shadow-2" :style="'background: ' + chartData.Icon[index] + ';'"></div>
				<div class="desc" :data-desc="chartData.Desc[index]" :data-unit="chartData.Unit"><span :style="'color: ' + chartData.Icon[index]">{{softValues[soft].value}}</span></div>
				<div class="rate" :style="'color: ' + chartData.Icon[index] + ';'" v-if="SoftDataSum > 0" data-unit="%">{{((softValues[soft].value / SoftDataSum) * 100).toFixed(1)}}</div>
			</div>
		</div>
		<div class="pie-area">
			<echart :ref="'Pie_' + chartName" autoresize="true" :options="comObjOption" style="width: 100%; height: 100%;"></echart>
		</div>
	</div>
</template>

<script>
module.exports = {
	components: { 
		"echart" : VueECharts,
	},
	props: {
		"chartName": {
			required: true
		},
		"chartData": {
			required: true
		},
		"refreshRate": {
			default: 0,
			type: Number,
			required: true
		},
		"softValues": {
			default: {},
			required: true
		}
	},
	data: () => {
		return {
			comObjOption : {
				title: { show: false },
				legend: { show: false },
				tooltip: { show: false },
				animation: false,
				series: [{
					type: "pie",
					center: ["50%", "50%"],
					labelLine: { show: false },
					itemStyle: {
						shadowColor: "rgba(20%, 20%, 40%, 0.4)",
						shadowBlur: 2,
						shadowOffsetX: 1,
						shadowOffsetY: 1
					},
					data: []
				}]
			},
			comIntRefreshRate: 0,
			comObjTimer: null
		}
	},
	created () {
		this.$set(this.comObjOption, "color", this.chartData.Icon);
	},
	mounted () {
		this.comFnDrawing();
		this.comIntRefreshRate = this.refreshRate;
	},
	computed: {
		SoftDataSum () {
			return this.comObjOption.series[0].data.length > 0 ? this.comObjOption.series[0].data.reduce(function (a, b) { return a + b; }) : 0;
		}
	},
	watch: {
		"comIntRefreshRate": {
			handler (nv, ov) {
				if (nv == 0) {
					clearTimeout(this.comObjTimer);
				} else if (nv > 0) {
					this.comFnInfiniteDrawing();
				}
			}
		}
	},
	methods: {
		comFnInfiniteDrawing () {
			var self = this;
			self.comObjTimer = setTimeout(function(){
				self.comFnDrawing();
				self.comFnInfiniteDrawing();
			}, self.refreshRate * 1000);
		},
		comFnDrawing () {
			var self = this;
			var datas = [];
			self.chartData.Soft.forEach(function(_soft, _index){
				datas.push(Number(self.softValues[_soft].value));
			});
			self.$set(self.comObjOption.series[0], "data", datas);
		}
	}
}
</script>