<template>
	<view style="position: relative;">
		<canvas :style="{width: width + 'px',height:height + 'px'}" class="sleepcanvas" canvas-id="sleepCanvas" @click="handleSleepcharts"></canvas>
		<view class="timebox">
			<view class="timebox-start">
				<view>{{startSleepTime.substring(5,10)}}</view>
				<view>{{startSleepTime.substring(11,16)}}入睡</view>
			</view>
			<view class="timebox-end">
				<view>{{endSleepTime.substring(5,10)}}</view>
				<view>{{endSleepTime.substring(11,16)}}醒来</view>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		name: "sleepCharts",
		props: {
			sleepValue: {
				type: Array,
				default: []
			},
			// 1:默认样式，每个数据柱从最底部出发 ,2:悬浮样式，各个数据类型的起始高度不同
			type: {
				type: Number,
				default: 1
			},
			sleepData: {
				type: Object,
				default: {}
			},
		},
		data() {
			return {
				showLoading: false,
				width: uni.getSystemInfoSync().windowWidth - uni.upx2px(96),
				height: uni.upx2px(382),
				touchValue: {},
				startSleepTime: "",
				endSleepTime: "",
				style: "",
				ctx: null,
				dataList: []
			}
		},
		methods: {
			initData() {
				this.dataList = []
				if(this.sleepValue && this.sleepValue.length > 0) {
					let result = [];
					let previousObj = null;
					
					for (let i = 0; i < this.sleepValue.length; i++) {
					  let currentObj = this.sleepValue[i];
					  
					  if (previousObj && currentObj.start !== previousObj.end) {
					    let newObject = {
					      end: currentObj.start,
					      start: previousObj.end,
					      type: -1 
					    };
					    result.push(newObject);
					  }
					  
					  result.push(currentObj);
					  previousObj = currentObj;
					}
					this.dataList = result
					this.calculateSNTime();
					this.drawCharts();
				}
			},
			
			// 获睡眠的总秒数
			getAllTime() {
				const first = new Date(this.dataList[0].start).getTime();
				const last = new Date(this.dataList[this.dataList.length - 1].end).getTime();
				let allTime = Math.floor((last - first) / 1000);
				return allTime;
			},

			// 计算开始结束时间
			calculateSNTime() {
				this.startSleepTime = this.dataList[0].start;
				this.endSleepTime = this.dataList[this.dataList.length - 1].end;
			},

			// 绘制睡眠图
			drawCharts() {
				let ALLTIME = this.getAllTime();
				let {
					width, // x
					height // y
				} = this;
				let context = uni.createCanvasContext('sleepCanvas', this);
				this.ctx = context;
				context.setLineWidth(1);
				let xValue = 0;
				this.showLoading = true
				this.dataList.map((item, index) => {
					// ============== 计算矩形的颜色 ============== //
					// 3 深睡,4 浅睡,6 清醒,7 快速眼动
					switch (item.type) {
						case 3: // 深睡
							context.setFillStyle("#8C37E6");
							item.sleepStateText = "深睡";
							break;
						case 4: // 浅睡
							context.setFillStyle("#D138CF");
							item.sleepStateText = "浅睡";
							break;
						case 6: // 清醒
							context.setFillStyle("#FDBD27");
							item.sleepStateText = "清醒";
							break;
						case 7: // 快速眼动
							context.setFillStyle("#F88082");
							item.sleepStateText = "快速眼动";
							break;
						default:
							context.setFillStyle("#FFFFFF");
							item.sleepStateText = "其他";
					}
					// ========================================= //

					// ============== 计算矩形的高度 ============== //
					let yValue = uni.upx2px(80);
					if (item.type == 3) {
						yValue = yValue * 1;
					} else if (item.type == 4) {
						yValue = yValue * 2;
					} else if (item.type == 6) {
						yValue = yValue * 4;
					} else if (item.type == 7) {
						yValue = yValue * 3;
					} else {
						yValue = yValue * 5;
					}
					// ========================================= //
					
					// ============== 计算矩形的宽 =============== //
					let value = Math.floor((new Date(item.end).getTime() - new Date(item.start).getTime()) / 1000);
					// ========================================= //
					value = value / ALLTIME * width;

					// =============== 绘制数据柱 ================ //
					let spacingH = uni.upx2px(80)
					
					if (this.type === 1) {
						context.fillRect(xValue, height, value, -yValue);
					} else if (this.type === 2) {
						// 根据数据类型 更改这类柱子y轴起始位置
						if (item.type == 3) {
							context.fillRect(xValue, height- spacingH, value, spacingH);
						} else if (item.type == 4){
							context.fillRect(xValue, height - yValue, value, spacingH);
						} else if (item.type == 6){
							context.fillRect(xValue, height - yValue, value, spacingH);
						} else if (item.type == 7){
							context.fillRect(xValue, height - yValue, value, spacingH);
						} else {
							context.fillRect(xValue, height, value, -yValue);
						}
					}
					// ========================================= //

					xValue = xValue + value; // 计算下一次x轴开始画的位置
					context.stroke()
				})
				this.showLoading = false
				context.draw()
				this.touchValue = {
					startTime: this.dataList[0].start + ":00",
					endTime: this.dataList[this.dataList.length-1].end + ":00",
					type: '',
					sleepStateText: '总睡眠',
					hours: "",
					minutes: ""
				}
				const all = this.sleepData.deepSleep + this.sleepData.lightSleep + this.sleepData.weakSleep + this.sleepData.eyemoveSleep
				this.touchValue.hours = Math.floor(all / 60)
				this.touchValue.minutes = all % 60
				this.$emit("handleItem", this.touchValue,'init');
			},

			// 点击睡眠图表
			handleSleepcharts(e) {
				// 这段睡眠的总秒数
				const ALLTIME = this.getAllTime();
				// 点击的坐标
				const touchX = e.detail.x - e.currentTarget.offsetLeft-uni.upx2px(48);
				// 图表的总宽度
				const chartsWidth = this.width;
				// 获取点击位置在睡眠中从开始到点击这一刻的秒数
				const second =  touchX / chartsWidth * ALLTIME;
				// 获取点击位置的时间戳
				const timeStamp = (new Date(this.dataList[0].start).getTime() / 1000) + second;
				let touchStartTime = null,
					touchEndTime = null;
				// 获取点击位置对应的数组项
				this.dataList.forEach((item,index) => {
					if (timeStamp > (new Date(item.start).getTime() / 1000) && timeStamp < (new Date(item.end).getTime() / 1000)) {
						this.touchValue = {
							startTime: item.start + ":00",
							endTime: item.end + ":00",
							type: item.type,
							sleepStateText: item.sleepStateText
						}
					}
				})
				this.$emit("handleItem", this.touchValue);
			},
		}
	}
</script>

<style scoped lang="scss">
	.timebox-touch {
		color: #fff;
		text-align:center;
		min-width:300rpx;
		padding: 6rpx 10rpx;
		box-sizing: border-box;
		// height:48rpx;
		border-radius:28rpx;
		font-size: 20rpx;
		// line-height:48rpx;
	}

	.type3 {
		background-color: rgba(140, 55, 230, 0.3);
	}
	.type4 {
		background-color: rgba(209, 56, 207, 0.3);
	}
	.type6 {
		background-color: rgba(248, 128, 130, 0.3);
	}
	.type7 {
		background-color: rgba(253, 189, 39, 0.3);
	}
	.sleepcanvas {
		border-bottom: 1rpx dashed #ECECEC;
	}
	.timebox {
		display: flex;
		align-items: center;
		justify-content: space-between;
		font-family: PingFang SC, PingFang SC;
		font-weight: 400;
		font-size: 20rpx;
		color: #999999;
		text-align: center;
		padding: 10rpx 0;
	}
	.timebox-start {
		
	}
	.timebox-end {
		
	}
</style>