<template>
	<view :id="'mybox'+cid" class="u-echart" v-if="cid">
		<canvas :canvas-id="'uEchart'+cid" :id="'uEchart'+cid" class="u-echart" type="2d" @tap="tap">
		</canvas>
	</view>
</template>

<script>
	import uCharts from '@/uni_modules/qiun-data-charts/js_sdk/u-charts/u-charts.js';
	var uChartsInstance = {};
	export default {
		data() {
			return {
				cWidth: '',
				cHeight: '',
				pixelRatio: '',
				cid: '',
				scrollTop: 0
			};
		},
		created() {
			this.cid = this._uid;
		},
		mounted() {
			let _self = this
			uni.$on('onPageScroll', function(data) {
				_self.scrollTop = Number(data);
			})
		},
		methods: {
			initCharts(option) {
				const query = uni.createSelectorQuery().in(this);
				query.select('#mybox' + this._uid).boundingClientRect(data => {
					this.cWidth = data.width;
					this.cHeight = data.height;
					this.pixelRatio = uni.getSystemInfoSync().pixelRatio;
					this.drawCharts('uEchart' + this._uid, option);
				}).exec();
			},
			drawCharts(id, option) {
				const query = uni.createSelectorQuery().in(this);
				query.select('#' + id).fields({
					node: true,
					size: true
				}).exec(res => {
					if (res[0]) {
						const canvas = res[0].node;
						const ctx = canvas.getContext('2d');
						canvas.width = res[0].width * this.pixelRatio;
						canvas.height = res[0].height * this.pixelRatio;
						const commonOption = {
							context: ctx,
							width: this.cWidth * this.pixelRatio,
							height: this.cHeight * this.pixelRatio,
							pixelRatio: this.pixelRatio
						}
						const chartsOption = Object.assign(commonOption, option);
						uChartsInstance[id] = new uCharts(chartsOption);
					} else {
						console.error("[uCharts]: 未获取到 context");
					}
				});
			},
			tap(e) {
				const query = uni.createSelectorQuery().in(this);
				query.select('#mybox' + this._uid).boundingClientRect(data => {
					let rchartdom = data,
						tmpe = {};
					if (e.detail.x) { //tap或者click的事件
						tmpe = {
							x: e.detail.x - rchartdom.left,
							y: e.detail.y - rchartdom.top - this.scrollTop
						}
					} else { //mouse的事件
						tmpe = {
							x: e.clientX - rchartdom.left,
							y: e.clientY - rchartdom.top - this.scrollTop
						}
					}
					e.changedTouches = [];
					e.changedTouches.unshift(tmpe);
					uChartsInstance[e.target.id].showToolTip(e);
				}).exec();
			}
		}
	};
</script>

<style scoped>
	.u-echart {
		width: 100%;
		height: 100%;
	}
</style>