<template>
	<view class="content">
		<!-- <view class="first-line">
			<button class="first-btn">一层</button>
			<button class="second-btn">二层</button>
		</view> -->
		<view class="second-content">
			<view class="sec-first">
				<!-- <view class="sec-first-one">配送中心</view>
				<view class="sec-first-two">盥洗室</view> -->
				一层档口监测图
			</view>
			
			<view class="sec-second">
				<view class="first-col">
					<view class="shop-text" v-for="(name,i) in shopName">
						{{shopNum[i]}} {{name}}
					</view>
				</view>
				<view class="second-col">
					<view class="second-col-line">
						<view class="shop-btn" :class="{'color1':rank[i] == 1,'color2':rank[i] == 2}"
							v-for="(shop,i) in shopNum1">
							<!-- <view class="shop-btn" :class="{'color1':rank[i] == 1,'color2':rank[i] == 2}"
							v-for="(shop,i) in shopNum1" @click="getInfo(i)"> -->
							<view class="">
								{{shop}}
							</view>
							<view class="">
								{{peopleNum[i]}}人
							</view>
							 
							</view>
					</view>
					<view class="second-col-item">
						<view class="col-item" v-for="(shop,i) in shopNum1"></view>
					</view>
					<view class="second-col-line">
						<view class="shop-btn" :class="{'color1':rank[19-i] == 1,'color2':rank[19-i] == 2}"
							v-for="(shop,i) in shopNum2">
							<!-- <view class="shop-btn" :class="{'color1':rank[19-i] == 1,'color2':rank[19-i] == 2}"
							v-for="(shop,i) in shopNum2" @click="getInfo(19-i)"> -->
							<view class="">
								{{shop}}
							</view>
							<view class="">
								{{peopleNum[19-i]}}人
							</view>
							</view>
					</view>
				</view>
			</view>
			<!-- <view class="sec-third">
				<view class="sec-third-one">黄焖鸡米饭</view>
				<view class="sec-third-two">包子铺</view>
			</view> -->
		</view>
		<view class="third-note">
			<view class="third-first">
				<span style="color: #FF0000;">*</span>
				注：点击对应食堂窗口查看实时人数
			</view>
			<view class="third-second">
				<view class="one-line">
					<view class="one-block"></view>
					<view class="third-text">
						窗口人数低于{{minNum}}人
					</view>
				</view>
				<view class="tow-line">
					<view class="two-block"></view>
					<view class="third-text">
						窗口人数高于{{minNum}}人且小于{{maxNum}}人
					</view>
				</view>
				<view class="three-line">
					<view class="three-block"></view>
					<view class="third-text">
						窗口人数高于{{maxNum}}人
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import sha256 from "../../static/index.js"
	import demo from '../../static/demo.js'
	export default {
		data() {
			return {
				rank: [],
				minNum: 0,
				maxNum: 12,
				shopNum1: [],
				shopNum2: [],
				shopNum: ['①', '②', '③', '④', '⑤', '⑥', '⑦', '⑧', '⑨', '⑩', '⑪', '⑫', '⑬', '⑭', '⑮', '⑯', '⑰', '⑱', '⑲',
					'⑳'
				],
				// peopleNum: [6, 12, 6, 14, 5, 4, 17, 6, 9, 13, 6, 1, 4, 9, 5, 14, 5, 3, 0, -10],
				peopleNum: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
				shopName: ['奶茶店', '晏阿婆米线', '犀米家', '港式套餐饭', '小东北麻辣烫', '小芸家食速快餐', '后来的粥', '思艳鲜包', '荷叶蒸饭', '老南昌米粉', '食尚快餐',
					'五谷渔粉', '柚米套餐饭', '北方饼店', '宴阿婆自选水饺', '贵州花溪牛肉', '小木屋', '麻辣香锅', '土耳其烤肉饭', '兰州拉面'
				],

				status_code: '',
				response: '',
				nonce: '290208a68afdc9aca4b454da8fc22acd3f88a178c32e4128c0a00e7ff13fbdc7',
				opaque: 'null',
				uri: '/API/Web/Login',
				algorithm: 'SHA-256',
				username: 'admin',
				password: 'Chuanghai-2021',
				realm: 'device',
				qop: 'auth',
				nc: '00000001',
				cnonce: '247fe9fd623c1c42',
				token: '',
				lap_number: '',
				reader_id: '',
				sequence: '',
				heat_alarm: '',
				heartResult: '',
				flag: 1,
				chan: '',
				store: [7, 3, 18, 5, 15, 14, 8, 19, 11, 20, 9, 13, 10, 1, 4, 6, 17, 12, 2, 16],
			}
		},
		watch: {
			// status_code: { //深度监听，可监听到对象、数组的变化
			// 	handler(val, oldVal) {
			// 		if (val != 200) {
			// 			clearInterval(this.timer)
			// 			this.flag = 0
			// 		} else if (val == 200) {
			// 			this.flag = 1
			// 			this.timer = setInterval(() => {
			// 				this.heartBeat()
			// 			}, 25000)
			// 			this.checkInfoFirst()
			// 		}
			// 	},
			// 	deep: true
			// },
			// heartResult: {
			// 	handler(val, oldVal) {
			// 		if (val != 'success') {
			// 			clearInterval(this.timer)
			// 			this.flag = 0
			// 		}
			// 	},
			// 	deep: true
			// },
			peopleNum: {
				handler(val, oldVal) {
					this.getShopNum()
					this.getRank()
				},
				deep: true
			}
		},
		onLoad() {
			this.getShopNum()
			this.getRank()

			this.getNumInfo()
			this.timer = setInterval(() => {
				this.getNumInfo()
			}, 8000)


			// this.getSha256()
			// this.login()


			// this.loginRange()
		},
		onUnload() {
			clearInterval(this.timer)
		},
		methods: {

			loginRange() {
				uni.request({
					url: '/camera/Login/Range',
					method: 'POST',
					header: {
						"Content-Type": "application/json; charset=UTF-8",
					},
					success: res => {
						console.log(res)
					},
				});
			},

			async login() {
				// console.log(this.nonce)
				const res = await uni.request({
					url: '/camera/Web/Login',
					method: 'POST',
					header: {
						"Content-Type": "application/json",
						'Authorization': 'Digest username="' + this.username + '",realm="' + this
							.realm + '",nonce=' + this.nonce + ',uri="' + this.uri + '",algorithm="' +
							this.algorithm + '",qop=auth,nc=' + this.nc + ',cnonce="' + this.cnonce +
							'",response="' + this.response + '"',
					},
				});

				this.result = res[1]
				this.status_code = this.result.statusCode
				this.headers = this.result.header['www-authenticate']
				if (this.status_code == 401) {
					let headers = this.result.header['www-authenticate']
					let pattern = new RegExp('".*?"', "g"); // 正则匹配URL
					let matcher = headers.match(pattern);
					// this.realm = matcher[0]
					this.nonce = matcher[1].substring(1, matcher[1].length - 1)
					// console.log(this.headers)
					// console.log(this.nonce)
					this.getSha256()
					this.login()
				} else if (this.status_code == 200) {
					// console.log(res[1].header['x-csrftoken'])
					this.token = res[1].header['x-csrftoken']
					console.log('登录成功')
					uni.showToast({
						icon: 'success',
						title: '登录成功',
						duration: 2000
					});
				} else {
					console.log('登录失败!!!!!!')
					this.showLoding()
					clearInterval(this.timer)
					setTimeout(() => {
						location.reload();
					}, 5000);
				}
			},

			showLoding() {
				uni.showLoading({
					title: '重新加载中'
				});

				setTimeout(function() {
					uni.hideLoading();
				}, 3000);
			},

			async heartBeat() {
				// console.log(this.flag)
				const res = await uni.request({
					url: '/camera/Login/Heartbeat',
					method: 'POST',
					header: {
						"Content-Type": "application/json",
						"X-csrftoken": this.token
					},
				});
				// console.log(res)
				// console.log(res[1].data.error_code)
				this.heartResult = res[1].data.result
				if (this.heartResult == 'success') {
					console.log('保活成功')
					uni.showToast({
						icon: 'success',
						title: '保活成功',
						duration: 2000
					});
				} else {
					console.log('保活失败!!!!!!')
					clearInterval(this.timer)
				}
			},

			checkInfoFirst() {
				uni.request({
					url: '/camera/Event/Check',
					method: 'POST',
					header: {
						"X-csrftoken": this.token,
						"Content-Type": "application/json",
					},
					success: res => {
						// console.log(res.data.data)
						console.log('首次推送成功')
						this.lap_number = res.data.data.lap_number
						this.reader_id = res.data.data.reader_id
						this.sequence = res.data.data.sequence

						if (this.reader_id != '') {
							this.checkInfo()
						}

					},
					fail: (err) => {
						console.log('首次推送失败!!!!!!', err)
					},
				});
			},

			checkInfo() {
				// console.log(this.flag)
				this.heat_alarm = ''
				uni.request({
					url: '/camera/Event/Check',
					method: 'POST',
					header: {
						"X-csrftoken": this.token,
						"Content-Type": "application/json",
					},
					data: {
						"data": {
							"lap_number": this.lap_number,
							"reader_id": this.reader_id,
							"sequence": this.sequence,
							"subscribe_ai_metadata": true,
							"subscribe_intelligence": true,
						}
					},
					success: res => {
						// console.log(res.data.data)
						// console.log(res.data.result)
						if (res.data.result == 'success') {

							this.lap_number = res.data.data.lap_number
							this.reader_id = res.data.data.reader_id
							this.sequence = res.data.data.sequence
							this.heat_alarm = res.data.data.heat_alarm

							if (this.heat_alarm != 'HeatAlarm') {
								// console.log(res.data.data)
								for (let j = 0; j < res.data.data.alarm_list.length; j++) {
									if ('realtime_data_report' in res.data.data.alarm_list[j]) {
										// console.log(res.data.data.alarm_list[j].realtime_data_report)
										var objs = res.data.data.alarm_list[j].realtime_data_report
										for (let i = 0; i < objs.length; i++) {
											if ('realtime_data_type' in objs[i]) {
												if (objs[i].realtime_data_type == 'queue_length') {
													var chanNum = objs[i].channel.substring(2) - 1
													var storeNum = this.store[chanNum] - 1
													console.log('当前通道为：', objs[i].channel, ',当前档口为：', this
														.store[chanNum], ',当前档口人数为：', objs[i]
														.shoulder_count)
													this.peopleNum.splice(storeNum, 1, objs[i].shoulder_count)
												}
											} else {
												console.log('realtime_data_type不存在!!!!!!')
											}
										}
									} else {
										// console.log('realtime_data_report 不存在!!!!!!')
									}
								}
							}

							if (this.flag == 1) {
								setTimeout(() => {
									console.log('推送请求成功')
									uni.showToast({
										icon: 'success',
										title: '推送成功',
										duration: 2000
									});
									this.checkInfo()
								}, 5000);
							} else {
								console.log('推送请求失败!!!!!!')
							}

						} else {
							console.log('返回参数不存在，正在重新推送请求')
							setTimeout(() => {
								location.reload();
							}, 3000);
						}
					},
					fail: (err) => {
						this.checkInfoFirst()
						console.log('推送失败!!!!!!', err)
					},
				});
			},

			getSha256() {
				let A1 = mycrypto.sha256.create()
				let A2 = mycrypto.sha256.create()
				let Response = mycrypto.sha256.create()

				let sha1 = this.username + ':' + this.realm + ':' + this.password
				let sha2 = 'POST' + ':' + this.uri

				A1.update(sha1)
				var HA1 = A1.digest().toHex()

				A2.update(sha2)
				var HA2 = A2.digest().toHex()

				var ResponseText = HA1 + ':' + this.nonce + ':' + this.nc + ':' + this.cnonce + ':' + this.qop + ':' + HA2
				Response.update(ResponseText)

				this.response = Response.digest().toHex()
				// console.log('response:', this.response)

				// console.log('Authorization:Digest username="', this.username, '",realm="', this
				// 	.realm, '",nonce="', this.nonce, '",uri="', this.uri, '",algorithm="',
				// 	this.algorithm, '",qop=auth,nc=', this.nc, ',cnonce="', this.cnonce, '",response="', this.response,
				// 	'"')
			},

			getNumInfo() {
				uni.request({
					url: 'camera/loginquery.action',
					method: 'POST',
					header: {
						"Content-Type": "application/json; charset=UTF-8",
					},
					success: res => {
						// console.log(res)
						this.info = JSON.parse(res.data.message)
						console.log(this.info)
						if ('error_code' in this.info) {
							this.showLoding()
						} else {
							if (this.info.result = 'success') {
								if (this.info.data.heat_alarm != 'HeatAlarm') {
									for (let j = 0; j < this.info.data.alarm_list.length; j++) {
										if ('realtime_data_report' in this.info.data.alarm_list[j]) {
											// console.log(this.info.data.alarm_list[j].realtime_data_report)
											var objs = this.info.data.alarm_list[j].realtime_data_report
											for (let i = 0; i < objs.length; i++) {
												if ('realtime_data_type' in objs[i]) {
													if (objs[i].realtime_data_type == 'queue_length') {
														var chanNum = objs[i].channel.substring(2) - 1
														var storeNum = this.store[chanNum] - 1

														// if (objs[i].shoulder_count != 0) {
															console.log('当前通道为：', objs[i].channel, ',当前档口为：',
																this
																.store[chanNum], ',当前档口人数为：', objs[i]
																.shoulder_count)
															this.peopleNum.splice(storeNum, 1, objs[i]
																.shoulder_count)
														// }

													}
												} else {
													console.log('realtime_data_type不存在!!!!!!')
												}
											}
										} else {
											// console.log('realtime_data_report 不存在!!!!!!')
										}
									}
								} else {
									this.peopleNum = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
									console.log('等待中……')
									
								}
							}

						}

					},
					fail: (err) => {
						console.log('推送失败!!!!!!', err)
						// this.checkFirst()
					},
				});
			},

			// checkFirst() {
			// 	uni.request({
			// 		url: '/camera/loginfirst.action',
			// 		method: 'POST',
			// 		header: {
			// 			"Content-Type": "application/json; charset=UTF-8",
			// 		},
			// 		success: res => {
			// 			console.log('重新激活成功')
			// 		},
			// 	});
			// },

			getShopNum() {
				this.shopNum1 = this.shopNum.slice(0, 10)
				this.shopNum2 = this.shopNum.slice(10, 20).reverse()
				// var i = 1
				// while (i <= 20) {
				// 	var name = '窗口名称' + i
				// 	// console.log(name)
				// 	i = i + 1
				// 	this.shopName.push(name)
				// }
				// console.log(this.shopName)
			},

			getRank() {
				const self = this
				var i = 0
				self.rank = []
				var tmp = []
				while (i < self.peopleNum.length) {
					// console.log(this.peopleNum[i])
					if (self.peopleNum[i] > self.minNum && self.peopleNum[i] <= self.maxNum) {
						tmp.push(1)
					} else if (self.peopleNum[i] > self.maxNum) {
						tmp.push(2)
					} else if (self.peopleNum[i] <= self.minNum && self.peopleNum[i] >= 0) {
						tmp.push(0)
					} else {
						console.log('num is error')
					}
					setTimeout(() => {
						self.rank = tmp
						self.$forceUpdate()
					}, 300);
					i += 1
				}
				// console.log(this.rank)
			},

			getInfo(e) {
				// console.log(e)
				if (this.peopleNum[e] >= 0) {
					uni.showToast({
						icon: 'none',
						title: e + 1 + '号窗口实时人数：' + this.peopleNum[e],
						duration: 2000
					});
				} else if (this.peopleNum[e] == undefined) {
					uni.showToast({
						icon: 'none',
						title: 'empty',
						duration: 2000
					});
				} else {
					uni.showToast({
						icon: 'none',
						title: 'error',
						duration: 2000
					});
				}

			},
			//跳转
			navigatorToSec() {
				uni.navigateTo({
					url: '/pages/second/second',
				});
			},

			getTime() {
				var date = new Date(),
					year = date.getFullYear(),
					month = date.getMonth() + 1,
					day = date.getDate(),
					hour = date.getHours() < 10 ? "0" + date.getHours() : date.getHours(),
					minute = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes(),
					second = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
				month >= 1 && month <= 9 ? (month = "0" + month) : "";
				day >= 0 && day <= 9 ? (day = "0" + day) : "";
				var timer = year + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + second;
				return timer;
			},
		}
	}
</script>

<style>
	@import url("index.css");
</style>
