<template>
	<view class="container">
		<!-- 头部背景图 -->
		<view class="headerImg">
			<image src="../../static/images/header.png" mode="aspectFit"></image>
		</view>
		<view class="bgmbox">
			<!-- 班级汇总选择切换 -->
			<picker class="classpicker" @change="bindPickerChange" :value="index" :range="array" range-key="Name">
				<view class="selectClass" @click="selectReport">
					<view>{{array[index].Name||"未知班级名"}}</view>
					<image src="../../static/images/Triangle.png" mode="aspectFit"></image>
				</view>
			</picker>
			<!-- 日期展示 -->
			<view class="huizong">
				<image src="../../static/images/message_1.png" mode="aspectFit"></image>
				<view class="huizongTime">{{week_desc}}</view>
			</view>

			<!-- 列表数据 -->
			<view class="dataBox">
				<view class="listitem" v-for="(item,index) in [1,2,3]" :key="index">
					<view class="labelbox">
						<image src="../../static/images/Group.png" mode="aspectFit"></image>
						<view class="labeltext">{{['每周要点','每周消费趋势','每周消费偏好区域'][index]}}</view>
						<image style="width: 32rpx;height: 32rpx;padding-left: 15rpx;" v-if="index==-1"
							src="../../static/images/wenhao.png" mode="aspectFit"></image>
					</view>
					<!-- 展示内容区 -->
					<view class="content">
						<view class="content1" v-if="index==0">
							<view v-for="(item,index) in summary" :key="index">
								{{item}}
							</view>
						</view>
						<view class="content2" v-if="index==1">
							<!-- 折线图 -->
							<view ref="zhexian" id="zhexian" style="width: 100%;height: 600rpx;">
							</view>
						</view>
						<view class="content3" v-if="index==2">
							<!-- 饼状图 -->
							<view ref="mychars" id="mychars" style="width: 100%;height: 500rpx;">
							</view>
						</view>
					</view>
				</view>
			</view>
		</view>
		<!-- 就餐情况表格 -->
		<view class="bgmbox2">
			<view class="labelbox">
				<image src="../../static/images/Group.png" mode="aspectFit"></image>
				<view class="labeltext">未就餐学生情况</view>
				<image @click="doubtTips" style="width: 32rpx;height: 32rpx;padding-left: 15rpx;"
					src="../../static/images/wenhao.png" mode="aspectFit"></image>
			</view>

			<!-- 表格数据 -->
			<view class="uni-table-box">
				<view class="table">
					<view class="table-head">
						<view>日期</view>
						<view>学生姓名</view>
						<view>次数</view>
					</view>
					<view v-for="(item,index) in unconsume_table.List" :key="index">
						<!--  -->
						<view class="table-body" v-for="(item2,index2) in item.List" :key="index2">
							<view>{{item2.date}}</view>
							<view>{{item2.student_name}}</view>
							<view>{{item2.cnt}}</view>
						</view>
						<!-- 总计 -->
						<view class="table-body total">
							<view>总计 {{index+1}}</view>
							<view>/</view>
							<view>{{item.total}}</view>
						</view>
					</view>
					<!-- 总计 -->
					<view class="table-body zongji">
						<view>总计</view>
						<view>/</view>
						<view>{{unconsume_table.total}}</view>
					</view>
				</view>
			</view>

		</view>

	</view>
</template>

<script>
	var option;
	let myChartzhexian, myChart;

	var gHost = "https://" + window.location.host;
	if (window.location.protocol != "https:") {
		gHost = "https://fpdev.xiaopay.net";
	}
	//获取参数
	function getQueryParams(params) {
		let href = window.location.href
		let query = href.substring(href.indexOf('?') + 1);
		let vars = query.split("&");
		for (var i = 0; i < vars.length; i++) {
			let pair = vars[i].split("=");
			if (pair[0] == params) {
				return pair[1];
			}
		}
		return (false);
	}
	let icon = {
		'0': 'image://data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAgAAAAICAYAAADED76LAAAAh0lEQVQoU2NkYGBg0Njaq8bwl7GdgZHBBcRn+M+wh4H5f+UN7+JbjCBJxn8MJxgYGAXBknDw//1/JgYLRo1NfWsZGRmCGBj+b/jxjzkDJM/B9HcGAwNjwP//DOsYNTb3fWRkYOD78Y9J4r5/wUuQAsWNE8Q5mP69+M/A8IkIBQStIORIQt4EAOTOTgf3b2UWAAAAAElFTkSuQmCC',
		'1': 'image://data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAgAAAAICAYAAADED76LAAAAhUlEQVQoU2NkYGBgCHz9RI35P0M7A+N/FxCf4T/jnr+MDJXrRWVuMYIlGRhOMDAwCIIlEeD9XwYGC8aQV0/WMjAyBP1nZNzw+y9LBkielfnPDMb//wMY/jOsYwx5/fgjAwMj369/rBKbxMVfghT4vXwpzsb0+wUDw/9PRCggZAVBRxLyJgBtFlJZuXamlAAAAABJRU5ErkJggg==',
		'2': 'image://data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAgAAAAICAYAAADED76LAAAAe0lEQVQoU4WPvQnCUACEv3u1BKy0VnAGB3AAcYqs4ARZIUskOEAGcAbBpNVK8rB+Fx42du+64477EcDT8RCgMZwyFwwJrntVD2VRcAfWWfzDx3DU5NgZLoKbCfUvIbWGs6DX6DgDFYTtTqt3Noz+biC9gFg2FCuKI0s3F9F1Rmtx2vOzAAAAAElFTkSuQmCC',
	}
	export default {
		name: "ClsWeekReport",
		data() {
			return {
				title: 'picker',
				array: [{
					DepId: '',
					Name: ""
				}],
				index: 0,
				time: '12:01',
				token: "",
				weekid: -1,
				consume_prefs: [],
				consume_trend: [],
				summary: [],
				unconsume_table: {},
				week_desc: ''
			}
		},
		onLoad() {

		},
		created: function() {
			// console.log(this.$echarts);
		},
		methods: {
			// 点击问好提示
			async doubtTips() {
				uni.showModal({
					title: "系统提示",
					showCancel: false,
					content: "统计周期为上周一至上周五",
				})
			},
			async bindPickerChange(e) {
				try {
					uni.showLoading({
						title: "加载中....."
					})
					console.log('picker发送选择改变，携带值为', e.target.value)
					this.index = e.target.value
					// 切换班级获取报告
					await this.QueryClsReport(this.array[e.target.value].DepId)
					uni.setNavigationBarTitle({
						title: (this.array[e.target.value].Name || "未知名班级") + "周消费报告"
					})
					uni.hideLoading()
				} catch (e) {
					//TODO handle the exception
					uni.hideLoading()
					uni.showModal({
						title: "系统提示",
						showCancel: false,
						content: e.message,
					})
				}

			},
			// 切换班级选择汇总
			async selectReport() {
				console.log(111);
			},
			// 微信JS-SDK鉴权
			async js_sdk_init() {
				wx.config({
					debug: true, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
					appId: '', // 必填，公众号的唯一标识
					timestamp: '', // 必填，生成签名的时间戳
					nonceStr: '', // 必填，生成签名的随机串
					signature: '', // 必填，签名
					jsApiList: [] // 必填，需要使用的JS接口列表
				});
				wx.ready(function() {
					// config信息验证后会执行ready方法，所有接口调用都必须在config接口获得结果之后，config是一个客户端的异步操作，所以如果需要在页面加载时就调用相关接口，则须把相关接口放在ready函数中调用来确保正确执行。对于用户触发时才调用的接口，则可以直接调用，不需要放在ready函数中。
				});
				wx.error(function(res) {
					// config信息验证失败会执行error函数，如签名过期导致验证失败，具体错误信息可以打开config的debug模式查看，也可以在返回的res参数中查看，对于SPA可以在这里更新签名。
					uni.showToast({
						icon: "none",
						title: JSON.stringify(res)
					})
				});
			},
			// 二维码加密内容转tokenqrcode2Token
			async tokenqrcode2Token() {
				let this_ = this
				return new Promise((resolve, reject) => {
					// 二维码加密内容获取token
					$.ajax({
						url: gHost + '/qyxp/qyapp/qrcode2Token',
						type: "get",
						timeout: 8000,
						contentType: "application/x-www-form-urlencoded",
						data: {
							hex: getQueryParams('hex')
						},
						success: function(res) {
							if (res.code == 10000) {
								this_.schoolName = res.results.schoolName
								this_.teacherName = res.results.teacherName
								this_.token = res.results.token
								resolve(res)
							} else {
								reject(res)
							}
						},
						error: function(error) {
							reject(error)
						}
					})
				})
			},
			// 埋点接口，用户点击班级周消费报告推送消息后调用此接口
			async CaptureEvent() {
				return new Promise((resolve, reject) => {
					// 二维码加密内容获取token
					$.ajax({
						url: gHost + '/qyxp/qyapp/CaptureEvent',
						type: "post",
						dataType: 'json',
						contentType: 'application/json; charset=UTF-8',
						cache: false,
						data: JSON.stringify({
							"event": "view_week_report",
							"hex": getQueryParams('hex'),
							"qyToken": this.token,
							"weekId": 0
						}),
						success: function(res) {
							if (res.code == 10000) {
								resolve(res)
							} else {
								resolve(res)
								uni.showToast({
									icon: "none",
									title: res.message
								})
							}
						},
						error: function(error) {
							reject(error)
						}
					})
				})
			},
			// 获取管理的班级列表
			async QueryAdminCls() {
				return new Promise((resolve, reject) => {
					// 二维码加密内容获取token
					$.ajax({
						url: gHost + '/qyxp/qyapp/QueryAdminCls',
						type: "post",
						dataType: 'json',
						contentType: 'application/json; charset=UTF-8',
						cache: false,
						data: JSON.stringify({
							qyToken: this.token
						}),
						success: function(res) {
							if (res.code == 10000) {
								resolve(res)
							} else {
								reject(res)
							}
						},
						error: function(error) {
							reject(error)
						}
					})
				})
			},
			// 获取班级周消费报告
			async QueryClsReport(clsId) {
				let this_ = this;
				return new Promise((resolve, reject) => {
					// 二维码加密内容获取token
					$.ajax({
						url: gHost + '/qyxp/qyapp/QueryClsReport',
						type: "post",
						dataType: 'json',
						contentType: 'application/json; charset=UTF-8',
						cache: false,
						data: JSON.stringify({
							"clsId": clsId + '',
							"qyToken": this_.token,
							"weekId": getQueryParams('weekid') ? parseInt(getQueryParams(
								'weekid')) : -1
						}),
						success: function(res) {
							if (res.code == 10000) {
								let {
									consume_prefs,
									consume_trend,
									summary,
									unconsume_table,
									week_desc
								} = res.results
								this_.consume_prefs = consume_prefs
								this_.consume_trend = consume_trend
								this_.summary = summary
								this_.unconsume_table = unconsume_table
								this_.week_desc = week_desc
								// 折线图重新渲染
								this_.Linechart()
								// 饼图渲染
								this_.piechart()
								resolve(res)
							} else {
								reject(res)
							}
						},
						error: function(error) {
							reject(error)
						}
					})
				})
			},
			// 折线图渲染
			async Linechart() {
				let this_ = this;
				this.$nextTick(function() {
					let zhexianchartDom = document.getElementById('zhexian');
					console.log(zhexianchartDom);
					myChartzhexian = echarts.init(zhexianchartDom);
					myChartzhexian.setOption({
						grid: {
							left: '3%',
							right: '4%',
							bottom: '3%',
							containLabel: true
						},
						legend: {

						},
						// 高亮样式。
						emphasis: {
							itemStyle: {},
							label: {
								show: false,
								// 高亮时标签的文字
								formatter: ''
							}
						},
						tooltip: {
							trigger: 'axis',
							extraCssText: 'width: 35%;text-align: center;border-radius: 0px 100px 100px 200px;', // 额外附加到浮层的 css 样式
							borderWidth: 0,
							backgroundColor: '#729487', // 提示框浮层的背景颜色。
							formatter: function(name) {
								// console.log(name[0].data);
								return name[0].data.name + '   ' + name[0].value + '次';
							},
							textStyle: {
								fontWeight: 'bold',
								color: "#F1F4F3"
							},
							axisPointer: { //坐标轴指示器，坐标轴触发有效，
								type: 'shadow', //默认为line，line直线，cross十字准星，shadow阴影
								shadowStyle: {
									color: {
										type: 'linear',
										x: 0,
										y: 0,
										x2: 0,
										y2: 1,
										colorStops: [{
											offset: 0,
											color: '#E4F6EF' // 0% 处的颜色
										}, {
											offset: 1,
											color: '#34e7b5' // 100% 处的颜色
										}],
										global: false // 缺省为 false
									},
									opacity: 0.5
								}
							}
						},
						xAxis: {
							type: 'category',
							data: this_.consume_trend.map(v => {
								return v.Date
							})
						},
						yAxis: {
							type: 'value'
						},
						series: [{
							itemStyle: {
								normal: {
									lineStyle: {
										color: '#29B38E'
									}
								}
							},
							data: this_.consume_trend.map(v => {
								return {
									name: v.Date,
									value: v.Amount,
									itemStyle: {
										normal: {
											color: "#29B38E"
										}
									}
								}
							}),
							type: 'line',
							smooth: true,
							areaStyle: {
								color: {
									type: 'linear',
									x: 0,
									y: 0,
									x2: 0,
									y2: 1,
									colorStops: [{
										offset: 1,
										color: '#E4F6EF' // 0% 处的颜色
									}, {
										offset: 0,
										color: '#34e7b5' // 100% 处的颜色
									}],
									global: false // 缺省为 false
								},
								opacity: 0.3
							}
						}],
						media: {
							minHeight: 200
						}
					});
				})
			},
			// 饼图渲染
			async piechart() {
				let this_ = this;
				let pieChartData = [{
						value: 1,
						name: '系统工具'
					},
					{
						value: 3,
						name: '课程表'
					},
					{
						value: 0,
						name: '意见反馈'
					},
					{
						value: 43,
						name: '其他'
					}
				]
				this.$nextTick(function() {
					let chartDom = document.getElementById('mychars');
					myChart = echarts.init(chartDom);
					let sum = 0,
						obj = {};
					this_.consume_prefs.forEach(ele => {
						obj[ele.scene] = parseFloat(ele.amount)
						sum += parseFloat(ele.amount);
					})

					myChart.setOption({
						//设置主副标题
						title: {
							show: false,
							text: sum.toFixed(2), //主标题
							left: "23%",
							top: "40%",
							z: 0,
							zlevel: 100,
							textStyle: { //设置主标题的 样式
								textAlign: "center",
								color: '#29B38E',
								fontSize: 14
							}
						},
						grid: {
							show: false,
							containLabel: false,
						},
						tooltip: {
							show: false,
							triggerOn: 'none',
							trigger: 'item',
							appendToBody: true
						},
						legend: {
							top: '35%',
							right: '0',
							orient: 'vertical',
							selector: false,
							formatter: function(name) {
								console.log(name);
								return `{a|${name}}:  {x|共花费${obj[name]}元}`;
							},
							textStyle: {
								fontWeight: 'normal',
								rich: {
									a: {
										fontWeight: 'bold',
										padding: [0, 0, 0, 15]
									},
									b: {

									},
									x: {

									}
								}
							},
							itemWidth: 10, // 图例图形宽度
							itemHeight: 10, // 图例图形高度
							data: this_.consume_prefs.map((v, index) => {
								return {
									name: v.scene,
									// 强制设置图形为圆。
									icon: icon[index + '0'],
									// 设置文本为红色
									textStyle: {
										itemStyle: {
											// color: "#aa0000"
										}
									}
								}
							})
						},
						series: [{
							name: '访问来源',
							type: 'pie',
							// 设置成相对的百分比
							center: ['30%', '45%'],
							radius: ['40%', '55%'],
							avoidLabelOverlap: false,
							legendHoverLink: false, //移入leged不显示在中间
							textAlign: "center",
							label: {
								show: true,
								fontSize: '15',
								fontWeight: 'bold',
								formatter: '{@name}元',
								position: 'center',
								color: '#29B38E',
								itemStyle: {

								}
							},
							emphasis: {
								itemStyle: {},
								label: {
									show: true,
									fontSize: '15',
									fontWeight: 'bold'
								}
							},
							select: {
								label: {
									show: true
								},
								labelLine: {},
								itemStyle: {
									color: '#29B38E'
								}
							},
							labelLine: {
								show: false
							},
							data: this_.consume_prefs.map((v, index) => {
								console.log(this_.consume_prefs);
								return {
									value: parseFloat(v.amount),
									name: v.scene,
									itemStyle: {
										normal: {
											color: ["#29B38E", "#54EBE4", "#DEFFF2"][
												index
											]
										}
									}
								}
							})
						}]
					});
				})
			},
			// 初始化
			async init_() {
				uni.showLoading({
					title: "加载中....."
				})
				try {
					await this.tokenqrcode2Token();
					let AdminCls = await this.QueryAdminCls();
					if (AdminCls.results) {
						this.array = AdminCls.results
						// this.array = [{
						// 	DepId: 39,
						// 	Name: "未知班级姓名"
						// }, {
						// 	DepId: 40,
						// 	Name: "101班周消费报告 "
						// }, {
						// 	DepId: 41,
						// 	Name: "102班周消费报告 "
						// }]
					}
					await this.QueryClsReport(AdminCls.results[0].DepId);
					uni.setNavigationBarTitle({
						title: (this.array[0].Name || "未知名班级") + "周消费报告"
					})
					await this.CaptureEvent()
					uni.hideLoading()
				} catch (e) {
					//TODO handle the exception
					uni.hideLoading()
					uni.showModal({
						title: "系统提示",
						showCancel: false,
						content: e.message,
					})
				}
			}
		},
		mounted: function() {
			let this_ = this;
			if (!getQueryParams('hex')) {
				return uni.showModal({
					title: "系统提示",
					showCancel: false,
					content: "hex参数错误",
				})
			}
			this_.init_()
			window.addEventListener('resize', () => {
				this.$nextTick(function() {
					myChartzhexian.resize()
					myChart.resize()
				})
			})
			// setTimeout(function() {
			// 	this_.js_sdk_init()
			// }, 2000)
		}
	}
</script>

<style scoped>
	page {
		background: #FFFFFF;
		height: 100%;
	}

	canvas {
		display: block;
		margin: 0 auto;
		border: 1px solid red;
	}


	.container {
		padding-top: 26rpx;
		padding-bottom: 26rpx;
	}

	.container image {
		position: relative;
	}

	.headerImg {
		width: 670rpx;
		height: 130rpx;
		margin: 0 auto;
	}

	.headerImg image {
		width: 100%;
		height: 100%;
		position: relative;
	}

	.selectClass {
		width: 60%;
		height: 50rpx;
		font-size: 36rpx;
		font-family: PingFangSC-Medium, PingFang SC;
		font-weight: 500;
		color: #FFFFFF;
		line-height: 50rpx;
		text-shadow: 0rpx 4rpx 8rpx rgba(0, 0, 0, 0.5);


		margin: 0 auto;
		display: flex;
		justify-content: center;
	}

	.classpicker {
		position: relative;
		top: -90rpx;
	}

	.selectClass image {
		width: 40rpx;
		height: 30rpx;
		position: relative;
		top: 12rpx;
	}

	.bgmbox {
		width: 670rpx;
		/* height: 1352rpx; */
		background-image: url(../../static/images/Slice.png);
		background-repeat: no-repeat;
		background-size: 100% 100%;
		background-attachment: fixed;
		box-shadow: 0rpx 6rpx 7rpx 0rpx rgba(0, 171, 207, 0.58);
		margin: 0 auto;
		padding-bottom: 50rpx;
	}

	.bgmbox2 {
		width: 670rpx;
		/* height: 718rpx; */
		box-shadow: 0rpx 6rpx 7rpx 0rpx rgba(0, 171, 207, 0.58);
		margin: 0 auto;

		padding-bottom: 50rpx;
	}

	.bgmbox2>.labelbox {
		padding-top: 40rpx;
	}

	.huizong {
		display: flex;
		justify-content: flex-end;
		align-items: center;
		padding-right: 20rpx;
		margin-top: -30rpx;
	}

	.huizongTime {
		/* width: 204rpx; */
		height: 42rpx;
		font-size: 30rpx;
		font-family: PingFang-SC-Regular, PingFang-SC;
		font-weight: 400;
		color: #6F747A;
		line-height: 42rpx;
	}

	.listitem {
		margin-top: 56rpx;
	}

	.huizong image {
		width: 32rpx;
		height: 32rpx;
		padding-right: 10rpx;
		top: -5rpx;
	}

	.labelbox {
		display: flex;
		align-items: center;
		justify-content: flex-start;
		margin-left: 24rpx;
	}

	.labelbox .labeltext {
		height: 44rpx;
		font-size: 32rpx;
		font-family: PingFangSC-Medium, PingFang SC;
		font-weight: 600;
		color: #3D3D3D;
		line-height: 44rpx;
		margin-left: 10rpx;
	}

	.labelbox image {
		width: 36rpx;
		height: 20rpx;
	}

	.content1 {
		/* height: 280rpx; */
	}

	.content1,
	.content2,
	.content3 {
		width: 626rpx;
		margin: 0 auto;
	}

	.content1 {
		font-size: 28rpx;
		font-family: PingFang-SC-Regular, PingFang-SC;
		font-weight: 400;
		color: #3D3D3D;
		line-height: 50rpx;

	}

	.content1 view:first-child {
		margin-top: 20rpx;
	}

	.content1 view:not(:first-child) {
		margin-top: 40rpx;
	}


	.table-head,
	.table-body {
		width: 616rpx;
		height: 62rpx;
		line-height: 62rpx;
		margin: 0 auto;
		display: flex;
		justify-content: space-between;
	}

	.table-body {
		height: 80rpx;
		font-size: 28rpx;
		font-family: PingFangSC-Regular, PingFang SC;
		font-weight: 400;
		color: #3D3D3D;
		line-height: 80rpx;

	}

	.table-body view {
		width: 120rpx;
		text-align: center;
	}

	.table-head {
		background-color: #F3F3F3;
		color: #3D3D3D;
		margin-top: 44rpx;
		font-size: 30rpx;
		font-family: PingFangSC-Medium, PingFang SC;
		font-weight: 500;
	}

	.table-head view {
		padding-left: 34rpx;
		padding-right: 36rpx;
	}

	.total {
		height: 72rpx;
		font-size: 28rpx;
		font-family: PingFangSC-Medium, PingFang SC;
		font-weight: 500;
		color: #3D3D3D;
		line-height: 72rpx;
		background-color: #D7F6F4;
	}

	.zongji {
		font-size: 28rpx;
		font-family: PingFangSC-Medium, PingFang SC;
		font-weight: 500;
		color: #29B38E;
	}

	.zongji view {
		width: 130rpx;
		text-align: center;
	}

	.table-head,
	.total {
		border-radius: 10rpx;
	}
</style>
