<template>
	<view>
		<canvas canvas-id="chartBox2" id="chartBox2" style="width: 570rpx;height: 280rpx;"></canvas>
	</view>
</template>
 
<script>
	export default {
		data() {
			return {
				cbox1: null,       //画布实例对象
				arrayList: [
					{
						percent: 0,
						lineColor: '#FFE3D2',
						linePercentColor: "#FD741D",
						name: "活动热量"
					},
					{
						percent: 0,
						lineColor: '#FFF4D3',
						linePercentColor: "#FDC925",
						name: "今日步数"
					},
					{
						percent: 0,
						lineColor: '#DAF1FE',
						linePercentColor: "#49B9FC",
						name: "锻炼时长"
					},
					{
						percent: 0,
						lineColor: '#E2F2E1',
						linePercentColor: "#6DBF68",
						name: "活动小时数"
					}
				],
				dataList:[],
				radius: 0,
				padding: 0,
				lineWidth: 0,
			}
		},
		mounted() {
			this.initCircle()
		},
		methods: {
			calcNum(a,b) {
				const num = Number(b||0) > 0 ? (Number(a||0) / Number(b||0)).toFixed(2) : 0
				return num > 1 ? 1 : num
			},
			initCircle(data){
				if(data) {
					this.arrayList[0].percent = this.calcNum(data.calorie,data.targetCalorie)
					this.arrayList[1].percent = this.calcNum(data.step,data.targetStep)
					this.arrayList[2].percent = this.calcNum(data.sport,data.targetSport)
					this.arrayList[3].percent = this.calcNum(data.activity,data.targetActivity)
				}
				//数据值
				this.dataList = Array.isArray(this.arrayList) ? this.arrayList : [];
				//直径
				this.radius = uni.upx2px(540);
				//四周内填充
				this.padding = uni.upx2px(6);
				//线宽度
				this.lineWidth = uni.upx2px(48);
				this.ctx = uni.createCanvasContext('chartBox2')
				this.drawStart()
			},
			//开始绘制
			drawStart(){
				//清空画面
					this.ctx.clearRect(0, 0, this.radius, this.radius);
					//循环绘制出每个圆环
					for(var i in this.dataList){
						//绘制圆环
						this.drawCircle(this.dataList[i], parseInt(i));
					}
					//绘制图形
					this.ctx.draw();
			},
			
			/**
			 * 绘制圆环
			 */
			drawCircle(_param, _i){
				//计算实际半径
					let _radius = this.radius/2-((this.padding+this.lineWidth)*(_i+1));
					
					//开始绘制圆环
					this.ctx.beginPath();
					this.ctx.arc(this.radius/2,this.radius/2, _radius,Math.PI,0, false);
					this.ctx.lineWidth = this.lineWidth;
					this.ctx.strokeStyle = _param.lineColor;
					this.ctx.lineCap = 'round';
					this.ctx.stroke();
					
					//绘制高亮进度条
					this.ctx.beginPath();
					this.ctx.lineCap = 'round';
					const endAngle = _param.percent > 0 ? (Math.PI * _param.percent)-Math.PI : Math.PI;
					this.ctx.arc(
				        this.radius/2,this.radius/2, 
				        _radius,Math.PI, endAngle,false
				    );
					this.ctx.strokeStyle = _param.linePercentColor;
					this.ctx.stroke();
					//恢复之前保存的绘图上下文
					this.ctx.restore();
			}
		}
	}
</script>
 
<style lang="scss" scoped>
</style>