<template>
	<view class="container">
		<view class="topSty flex justify-between align-center">
			<view class="text-bold" style="font-size: 34rpx;">历史数据</view>
			<view class="flex align-center " @click="openPicker">
				<view class="text-gray" @click="openPicker">{{ showTimeParams.selectBackDay }} ~
					{{ showTimeParams.selectDay }}
				</view>
				<u-icon name="calendar-fill" size="25" @click="openPicker"></u-icon>
			</view>
		</view>
		<view class="middleSty margin-top-lg">
			<view class="flex justify-around">
				<view class="flex flex-direction align-center justify-center w30" v-for="(item,index) of qpInfoList"
					:key="`${$assignKeys(item.name)}`" @click="goToOrderPage(item.name)">
					<view class="itemSty flex flex-direction"
						:style="{ backgroundImage: 'url('+ item.imgIcon +')', backgroundSize:'100% 100%', backgroundRepeat: 'no-repeat'}">
						<view class="text-sm margin-top-sm  margin-left-sm">
							{{ item.name }}
						</view>
						<view class="flex  margin-left-sm">
							<view class="text-bold numSty">{{item.value}}</view>
							<view class="margin-top-sm">(瓶)</view>
						</view>
					</view>
				</view>
			</view>
		</view>
		<view class="bottomSty margin-top-sm">
			<view class="circleSty flex">
				<view class="w50 circleLeftSty align-center">
					<view class="topSty">
						<view class="progressBox">
							<progress-circle :percent="circleInfoParams.allcount == 0? 0:100" :size="220"
								:strokeWidth="8" progressColor="#ea5504" id='a'>
								<view class="centerTxt">
									<view class="num text-gray">
										{{ circleInfoParams.allcount }}
									</view>
									<view class="txt text-gray">
										合计配送(单)
									</view>
								</view>
							</progress-circle>
						</view>
					</view>
				</view>
				<view class="w50 flex flex-direction margin-left-sm">
					<view class="circleItem margin-bottom-sm flex  justify-between align-center"
						v-for="(item,index) of circleDataList" :key="index">
						<view class="flex-direction flex margin-left-sm">
							<view style="color: #999DB0; font-size: 14px">{{item.name}}(单)</view>
							<view class="text-bold">{{ item.num }}</view>
						</view>
						<view class="progressBoxA">
							<progress-circle :percent="item.percent==0?0:item.percent" :size="120" :strokeWidth="8"
								progressColor="#ea5504" :id="item.id">
								<view class="centerTxt">
									<view class="num text-bold">
										{{ item.percent }}%
									</view>
								</view>
							</progress-circle>
						</view>
					</view>
				</view>
			</view>
			<view class="barchatSty margin-top-sm">
				<!--       <view id="myChart" :prop="options"  :change:prop="echarts.updateEcharts" style="width: 100%; height: 400px;"></view>-->
				<view style="width:100%; height:750rpx"><l-echart ref="myChart" @finished="drawLines"></l-echart></view>
				<!--        <canvas canvas-id="myChart" :style="{width: '100%', height: '500px'}"></canvas>-->
			</view>
		</view>
		<u-calendar :show="calendarShow" color="#ea5504" mode="range" :defaultDate="defaultDate" :maxDate="maxDate"
			:minDate="minDate" @confirm="calendarConfirm" @close="calendarShow = false"></u-calendar>
		<datetime-picker :show="showTimeParams.showStartDailog" :mode="'date'" :maxDate="showTimeParams.maxDate"
			:value="showTimeParams.timeValue" @cancel="handleTimeCancel" @confirm="hanleTimeConfirm"></datetime-picker>
	</view>
</template>
<script>
	import progressCircle from "@/components/progressCircle"
	import datetimePicker from "@/components/date-time-picker/date-time-picker.vue";
	// import * as echarts from 'echarts';
	import * as echarts from '@/uni_modules/lime-echart/static/echarts.min'
	export default {
		name: "index",
		components: {
			progressCircle,
			datetimePicker
		},
		data() {
			return {
				calendarShow: false,
				myChart: null,
				showTimeParams: {
					showStartDailog: false,
					timeValue: Date.now(),
					selectDay: '',
					selectBackDay: '',
					maxDate: Date.parse(new Date()),
				},
				minDate: this.$dayjs().subtract(15, 'day').format('YYYY-MM-DD'),
				maxDate: this.$dayjs().add(0, 'day').format('YYYY-MM-DD'),
				defaultDate: [],
				qpInfoList: [{
						name: '满瓶配送',
						value: '0',
						key: 'mpps',
						imgIcon: '/static/images/gas-background/historyBg1.png',
					},
					{
						name: '空瓶回收',
						value: '0',
						key: 'kphs',
						imgIcon: '/static/images/gas-background/historyBg2.png',
					},
					{
						name: '满瓶回收',
						value: '0',
						key: 'mphs',
						imgIcon: '/static/images/gas-background/historyBg3.png'
					}
				],
				circleDataList: [{
						name: '订单配送',
						id: 'circleA',
						num: '0',
						percent: 80,
						progress: 0.5, // 进度条的百分比，0.5代表50%
						percent:0
					},
					{
						name: '无单安装',
						id: 'circleB',
						num: '0',
						percent: 0
					},
					// {
					//   name:'帮助下单',
					//   id:'circleC',
					//   num:'1221',
					//   percent:0
					// }
				],
				circleInfoParams: {
					allcount: 0
				},
				options: {
					color: ['#EA0E0E', '#52BFA8'],
					// color: ['#EA0E0E', '#52BFA8', '#AE303A'],
					tooltip: {
						trigger: 'axis',
						axisPointer: {
							type: 'shadow'
						}
					},
					legend: {
						orient: 'horizontal',
						itemWidth: '14',
						itemHeight: '3',
						right: '0%',
						align: 'right',
						textStyle: {
							fontSize: '10px'
						},
						data: ['订单配送', '无单安装']
						// data:['订单配送', '无单安装','帮助下单']
					},
					grid: {
						left: '0%',
						right: '0%',
						bottom: '10%',
						top: '10%',
						containLabel: true
					},
					calculable: true,
					xAxis: [{
						type: 'category',
						axisTick: {
							show: false
						},
						data: []
					}],
					yAxis: [{
						name: '订单数',
						type: 'value',
						nameTextStyle: {
							fontSize: '8px'
						}
					}],
					series: [{
							name: '订单配送',
							type: 'bar',
							barGap: 0,
							data: []
						},
						{
							name: '无单安装',
							type: 'bar',
							data: []
						},
						// {
						//   name: '帮助下单',
						//   type: 'bar',
						//   data:[]
						// },
					]
				},
				chart: null,
			}
		},
		onLoad(options) {
			// let that = this;
			// // 通过nextTick异步画图
			// this.$nextTick(() => {
			// 	this.drawLines();
			// });
		},
		onReady() {
			// 初始化图表
			// this.$nextTick(() => {
			// 	this.drawLines();
			// });
		},
		mounted() {
			console.log("mounted");
			// this.rate.canvas ='cpbg'
			// this.Progressbar(this.rate);
			// this.$nextTick(() => {
				// this.drawLines();
				this.getTimeSelect();
			// })
		},
		methods: {
			getTimeSelect() {
				// 获取当前日期
				const today = new Date();
				// 将小时、分钟、秒、毫秒设为0
				today.setHours(0, 0, 0, 0);
				// 获取今天零时的时间戳
				const timestamp = today.getTime();
				const currentDate = Date.parse(new Date());
				this.showTimeParams.maxDate = timestamp;
				this.getCurrentDate(today);
				// console.log('打印timestamp', timestamp);
				// console.log('打印timestamp', currentDate);
			},
			async drawLines() {
				// var chartDom = document.getElementById('myChart');
				// var myChart = echarts.init(chartDom);
				try {
					console.log('打印this.params', this.showTimeParams.selectDay, this.showTimeParams.selectBackDay);
					let selectStartDate = this.formatDate(this.showTimeParams.selectBackDay);
					let selectEndDate = this.formatDate(this.showTimeParams.selectDay);
					let params = {
						startDate: selectStartDate,
						endDate: selectEndDate
					}
					let res = await this.$api.employeeApi.getUserCenterData(params);
					// console.log('daadada', res);
					let {
						code,
						value
					} = res;
					if (code == 200) {
						let {
							mpps,
							kphs,
							mphs,
							ddps,
							wdaz,
							bzxd,
							count,
							wdps,
							xsxd
						} = value;
						let qpInfoParams = {
							mpps: mpps,
							kphs: kphs,
							mphs: mphs,
						}
						this.qpInfoList = this.$assignValues(qpInfoParams, this.qpInfoList);
						// console.log('打印wdps', wdps);
						let xAxisData = wdps.length > 0 ? wdps.map((item) => item.rq) : [];

						// console.log('打印xAxisData', xAxisData);
						this.options.xAxis[0].data = xAxisData;
						let ddpsData = wdps.length > 0 ? wdps.map((item) => item.num) : [];
						this.options.series[1].data = ddpsData;
						let xsxdData = wdps.length > 0 ? xsxd.map((item) => item.num) : [];
						this.options.series[0].data = xsxdData;
						// console.log('打印options', this.options);

						this.circleInfoParams.allcount = count;
						this.circleDataList[0].num = ddps;
						this.circleDataList[1].num = wdaz;
						// this.circleDataList[2].num = bzxd;
						if (count !== 0) {
							if (ddps == 0) {
								this.circleDataList[0].percent = 0;
							} else {
								this.circleDataList[0].percent = parseFloat(((ddps / count) * 100).toFixed(0));
								// console.log('打印this.circleDataList[0].percent', this.circleDataList[0].percent)
								if (wdaz == 0) {
									this.circleDataList[1].percent = 0;
								} else {
									this.circleDataList[1].percent = parseFloat(((wdaz / count) * 100).toFixed(0));
									if (bzxd == 0) {
										this.circleDataList[2].percent = 0;
									} else {
										// this.circleDataList[2].percent = parseFloat(((wdaz / count) * 100).toFixed(0));
									}
								}
							}
						} else {
							this.circleDataList[0].percent = 0;
							this.circleDataList[1].percent = 0;
							// this.circleDataList[2].percent = 0;
						}

					}
				} catch (e) {
					console.log(e);
				}
				const chart = await this.$refs.myChart.init(echarts);
				this.options && chart.setOption(this.options)
				window.addEventListener('resize', function() {
					chart.resize()
				})

				// 这里是用于窗口变化时的自适应，利用的是echarts自带的resize方法
				// 如果你打印出来这个echarts实例，可以在函数里面找到这个方法
				// window.addEventListener('resize', () => {
				//   this.myChart.resize()
				// });
			},
			//打开时间弹窗
			openPicker() {
				// this.showTimeParams.showStartDailog = true;
				this.calendarShow = true;
				this.defaultDate = [this.showTimeParams.selectBackDay,this.showTimeParams.selectDay];
			},
			//关闭时间弹窗
			handleTimeCancel() {
				this.showTimeParams.showStartDailog = false;
			},
			formatDate(dateString) {
				return dateString.replace(/\//g, '-');
			},
			//点击时间弹窗完成按钮
			async hanleTimeConfirm(time) {
				// 创建一个新的Date对象并设置其时间戳属性
				var dateObj = new Date(time.value);
				// console.log('打印dateObj=====', dateObj);
				await this.getCurrentDate(dateObj);
				// 提取年份、月份和日期信息

			},
			async calendarConfirm(e) {
				console.log("选择日期范围", e);
				this.showTimeParams.selectBackDay = e[0];
				this.showTimeParams.selectDay = e[e.length - 1];
				this.calendarShow = false;
				this.defaultDate = [this.showTimeParams.selectBackDay,this.showTimeParams.selectDay];
				await this.drawLines();
			},
			async getCurrentDate(dateObj) {
				// console.log('打印getCurrentDate=====dateObj', dateObj);
				var year = dateObj.getFullYear();
				var month = dateObj.getMonth(); // 注意月份从0开始计数，所以需要加1
				var day = dateObj.getDate();
				month = this.doHandMonth(month + 1);
				day = this.doHandMonth(day);
				let currentDay = year + "/" + month + "/" + day
				this.showTimeParams.showStartDailog = false;
				let gobackDay = this.getData(dateObj, -6);
				// console.log('打印dateObj', gobackDay, currentDay);
				this.showTimeParams.selectBackDay = gobackDay;
				this.showTimeParams.selectDay = currentDay;
				await this.drawLines();
			},
			getData(currentToday, day) {
				var today = currentToday;
				// console.log('打印today', today);
				var targetday = today.getTime() + 1000 * 60 * 60 * 24 * day
				today.setTime(targetday)
				var tYear = today.getFullYear()
				var tMonth = today.getMonth()
				var tDate = today.getDate()
				tMonth = this.doHandMonth(tMonth + 1)
				tDate = this.doHandMonth(tDate)
				return tYear + "/" + tMonth + "/" + tDate
			},
			doHandMonth(month) {
				var m = month
				if (month.toString().length == 1) {
					m = "0" + month
				}
				return m
			},
			goToOrderPage(val) {
				console.log('打印val', val)
			},

		}


	}
</script>

<style lang="scss" scoped>
	.container {
		background-color: #ffffff !important;
		border-radius: 10px;
		padding: 15px 12px;
		width: 100%;

		.middleSty {
			.itemSty {
				//width: calc(100% / 3);
				border-radius: 15px;
				height: 120rpx;
				width: 100%;
				background-size: cover;
				background-position: center;

				//background-image: url("https://cdn.uviewui.com/uview/album/1.jpg");
				.numSty {
					font-size: 50rpx;
				}
			}
		}

		.bottomSty {
			.circleSty {
				display: flex;

				//#myEcharts {
				//  width: 100%;
				//  height: 600rpx;
				//}
				.progress_box {
					/* position: relative; */
					/* width: 100%; */
					height: 200rem;
					/* background-color: red; */
					display: inline-block;
					align-items: center;
					justify-content: center;
					text-align: center;

				}

				.circleLeftSty {
					position: relative;
					height: 420rpx;
					background-color: #f9fafd;

					.topSty {
						position: absolute;
						background-color: #ffffff;
						width: 280rpx;
						height: 280rpx;
						position: relative;
						margin: auto;
						top: 50%;
						left: 50%;
						box-shadow: 1px 1px 10px 0 rgba(0, 0, 0, 0.5);
						transform: translate(-57%, -50%);
						border-radius: 50%;
					}

					.progressBox {
						position: absolute;
						//width: 90%;
						//height: 90%;
						top: 50%;
						left: 50%;
						margin: 0 auto;
						//background-color: #ffffff;
						transform: translate(-50%, -66%);
						margin-top: 33rpx;
					}

					.centerTxt {
						position: absolute;
						top: 50%;
						left: 50%;
						width: 80px;
						transform: translate(-50%, -50%);

						.num {
							font-size: 60rpx;
							text-align: center;
							font-family: Arial;
							font-weight: bold;
							color: #38393A;
						}

						.txt {
							font-size: 26rpx;
							font-family: PingFang SC;
							font-weight: 400;
							color: #8A8B8B;
							margin-top: 10rpx;
						}
					}
				}

				.circleItem {
					height: 200rpx;
					background-color: #f9fafd;

					.progressBoxA {
						position: relative;
						margin: 10px;

						.centerTxt {
							position: absolute;
							top: 50%;
							left: 50%;
							//width: 80px;
							transform: translate(-50%, -50%);

							.num {
								font-size: 32rpx !important;
								text-align: center;
								font-family: Arial;
								font-weight: bold;
								color: #38393A;
							}

							.txt {
								font-size: 26rpx;
								font-family: PingFang SC;
								font-weight: 400;
								color: #8A8B8B;
								margin-top: 10rpx;
							}
						}
					}
				}
			}
		}
	}
</style>