<template>
	<nav class="site-navbar" :class="'site-navbar--' + navbarLayoutType">
		<div class="site-navbar__header">
			<h1 class="site-navbar__brand">
				<a class="site-navbar__brand-lg" href="javascript:;">盛安到家1.0系统</a>
				<a class="site-navbar__brand-mini" href="javascript:;">
					<img src="~@/assets/img/avatar.png" style="width: 30px;height: 30px; border-radius: 50%;">
				</a>
			</h1>
		</div>
		<div class="site-navbar__body clearfix">
			<el-menu class="site-navbar__menu" mode="horizontal">
				<el-menu-item class="site-navbar__switch" index="0" @click="sidebarFold = !sidebarFold">
					<icon-svg name="zhedie"></icon-svg>
				</el-menu-item>
				<!-- <el-menu-item index="1" style="position: relative;" @click="$router.push({ name: 'missionSm' })" v-if="show">
				  <template slot="title">
				    <span class="left-number" v-if="chatNum">{{chatNum}}</span>
				    <icon-svg name="xiaoxi" class="el-icon-setting" style="font-size: 28px;"></icon-svg>
				    
				  </template>
</el-menu-item> -->
				<!-- <el-menu-item index="1" style="position: relative;" @click="$router.push({ name: 'vueMchat' })">
				  <template slot="title">
				    <span class="left-number" v-if="chatNum2">{{chatNum2}}</span>
				    <icon-svg name="xiaoxi" class="el-icon-setting" style="font-size: 28px;"></icon-svg>
				    
				  </template>
				</el-menu-item> -->





			</el-menu>
			<el-menu class="site-navbar__menu site-navbar__menu--right" mode="horizontal">
				<!-- <el-menu-item index="1" style="position: relative;" @click="$router.push({ name: 'vueMchat' })">
          <template slot="title">
            <span class="left-number" v-if="chatNum">{{chatNum}}</span>
            <icon-svg name="tixing" class="el-icon-setting" style="font-size: 28px;"></icon-svg>
            <audio autoplay="autoplay" src="" ref='audio' controls hidden></audio>
          </template>
        </el-menu-item> -->
				<el-menu-item class="site-navbar__avatar" index="3">
					<!-- <audio id="audio" autoplay="autoplay"  v-if="chatNum>0" 
					  src="https://pw.xianmxkj.com/file/uploadPath/2022/01/19/0753211f78d718d44ee6372e33eae9ee.mp3" ref='audio'
					  controls hidden></audio> -->
					<audio id="audio1" src="../../static/img/01beb0bc15549b9aa4d18027a7751bae.mp3" ref='audio' controls
						hidden></audio>
					<el-dropdown :show-timeout="0" placement="bottom">
						<span class="el-dropdown-link">
							<span style="margin-right: 10px;">{{ username ? username : '' }} <span
									v-if="username">,欢迎您登录</span></span>
							<img src="~@/assets/img/avatar.png" :alt="userName">
						</span>
						<el-dropdown-menu slot="dropdown">
							<!-- <el-dropdown-item @click.native="updatePasswordHandle()">修改密码</el-dropdown-item> -->
							<el-dropdown-item @click.native="logoutHandle()">退出</el-dropdown-item>
						</el-dropdown-menu>
					</el-dropdown>
				</el-menu-item>
			</el-menu>
		</div>

		<!-- 弹窗, 修改密码 -->
		<update-password v-if="updatePassowrdVisible" ref="updatePassowrd"></update-password>
	</nav>
</template>

<script>
import UpdatePassword from './main-navbar-update-password'
import {
	clearLoginInfo
} from '@/utils'
export default {
	data() {
		return {
			updatePassowrdVisible: false,
			username: '',
			intervalId: 0,
			storeId: 0,
			isshow: false,
			chatNum: 0,
			chatNumJl: 0,
			chatNumQy: 0,
			chatNumJjqz: 0,
			chatNumYh: 0,
			chatNumJg: 0,
			chatNumCs: 0,

			errCount: 0,
			errCount1: 0,
			chatNum1: 0,

			errCount2: 0,
			chatNum2: 0,
			chatNumXdd: 0,
			ringOrderId: null,
			userId: null,

		}
	},
	components: {
		UpdatePassword
	},
	computed: {
		navbarLayoutType: {
			get() {
				return this.$store.state.common.navbarLayoutType
			}
		},
		sidebarFold: {
			get() {
				return this.$store.state.common.sidebarFold
			},
			set(val) {
				this.$store.commit('common/updateSidebarFold', val)
			}
		},
		mainTabs: {
			get() {
				return this.$store.state.common.mainTabs
			},
			set(val) {
				this.$store.commit('common/updateMainTabs', val)
			}
		},
		userName: {
			get() {
				return this.$store.state.user.name
			}
		},
	},
	methods: {
		// 修改密码
		updatePasswordHandle() {
			this.updatePassowrdVisible = true
			this.$nextTick(() => {
				this.$refs.updatePassowrd.init()
			})
		},
		// 退出
		logoutHandle() {
			this.$confirm(`确定进行[退出]操作?`, '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			}).then(() => {
				this.$cookie.set('token', '')
				this.$cookie.set('userId', '')
				this.$cookie.set('numberDts', '')
				this.$cookie.set('numberJjqz', '')
				this.$cookie.set('numberDsh', '')
				this.$cookie.set('numberDrz', '')
				this.$cookie.set('numberCs', '')
				this.$cookie.set('numberJg', '')
				sessionStorage.clear()
				//router.options.isAddDynamicMenuRoutes = false;
				this.$router.push({
					name: 'login'
				})

			}).catch(() => { })
		},

		// 获取用户信息
		userSelect() {
			let userId = this.$cookie.get('userId')
			this.$http({
				url: this.$http.adornUrl(`sys/user/info`),
				method: 'get',
				params: this.$http.adornParams({})
			}).then(({
				data
			}) => {
				let returnData = data.user;
				// if (returnData == null) {
				//   this.$cookie.set('token', '')
				//   this.$cookie.set('userId', '')
				//   sessionStorage.clear()
				//   this.$notify({
				//     title: '提示',
				//     duration: 1800,
				//     message: '用户信息失效，退出登录',
				//     type: 'warning'
				//   });
				//   this.$router.push({
				//     path: '/login'
				//   });
				// } else {
				this.username = returnData.username
				// }
			})
		},
		// 获取聊天消息
		chatSelect() {
			this.$http({
				url: this.$http.adornUrl('chats/count'),
				method: 'get',
				params: this.$http.adornParams({
					'storeId': this.storeId
				})
			}).then(({
				data
			}) => {
				let returnData = data.data;
				this.chatNum = returnData
				if (this.chatNum == 0) {
					this.isshow = false
				} else {
					// this.chatAudio();
					// let audio = new Audio()
					// audio.src = require('../assets/img/notify.mp3')
					// audio.play();
					//如果不是当前页面，标题栏闪动+消息提示
					if (document.hidden) {
						var options = {
							body: '您有新的未读消息，请及时处理',
							silent: true
						}
						var notification = new Notification('消息通知', options);
						notification.onclick = function () {
							window.open(window.location.href, '_blank');
						}
						//标题栏闪动
						var defaultTitle = document.title;
						if (that.isReceive) {
							return;
						} else {
							that.isReceive = true;
						}
						that.timer = setInterval(function () {
							var title = document.title;
							if (document.hidden && that.isReceive) {
								if (/你有新消息/.test(title) == false) {
									document.title = '【你有新消息】';
								} else {
									document.title = defaultTitle;
								}
							} else {
								that.isReceive = false;
								document.title = defaultTitle;
							}
						}, 500);
					}
					this.isshow = true
				}
			})
		},
		//申请浏览器通知权限，具体参见上面文档链接
		notification() {
			let that = this;
			if (!("Notification" in window)) {
				console.log("浏览器不支持消息通知");
				return;
			}
			Notification.requestPermission(function (permission) { });
		},
		// 获取聊天消息
		chatSelect2() {
			this.$http({
				url: this.$http.adornUrl('chats/count'),
				method: 'get',
				params: this.$http.adornParams({
					'storeId': this.storeId
				})
			}).then(({
				data
			}) => {
				let returnData = data.data;
				if (data.data > 0) {
					this.$notify.info({
						title: '消息',
						dangerouslyUseHTMLString: true,
						message: '您有' + data.data + '条未读消息。',
						offset: 80,
						duration: 2500,
						type: "warning"
					});
					this.aplayAudio1()
				}
			})
		},
		// 获取实名认证待审核数据
		dataSelect() {
			this.$http({
				url: this.$http.adornUrl('admin/realname/selectRealNameCount'),
				method: 'get',
				params: this.$http.adornParams({})
			}).then(({
				data
			}) => {
				if (data.data >= 0) {
					this.$cookie.set('numberDrz', data.data)
				}

			})
		},
		// 获取投诉待审核数据
		dataSelectPy() {
			this.$http({
				url: this.$http.adornUrl('message/selectMessageCount'),
				method: 'get',
				params: this.$http.adornParams({
					'state': 7,
				})
			}).then(({
				data
			}) => {
				if (data.data >= 0) {
					this.$cookie.set('numberDts', data.data)
				}
			})
		},
		// 获取紧急求助待审核数据
		dataSelectJjqz() {
			this.$http({
				url: this.$http.adornUrl('message/selectMessageCount'),
				method: 'get',
				params: this.$http.adornParams({
					'state': 9,
				})
			}).then(({
				data
			}) => {
				if (data.data >= 0) {
					this.$cookie.set('numberJjqz', data.data)
				}
			})
		},
		// 获取代理待审核数据
		dataSelectYh() {
			this.$http({
				url: this.$http.adornUrl('apply/selectApplyCount'),
				method: 'get',
				params: this.$http.adornParams({})
			}).then(({
				data
			}) => {
				if (data.data >= 0) {
					this.$cookie.set('numberDsh', data.data)
				}
			})
		},
		// 获取警告订单数据
		dataSelectJg() {
			let _this = this
			this.$http({
				url: this.$http.adornUrl('artificer/selectWarningOrdersCount'),
				method: 'get',
				params: this.$http.adornParams({})
			}).then(({
				data
			}) => {
				if (data.data >= 0) {
					this.$cookie.set('numberJg', data.data)
					if (data.data > 0) {
						if (this.errCount1 != data.data) {
							if (data.data > this.errCount1) {
								this.$notify.info({
									title: '消息',
									dangerouslyUseHTMLString: true,
									message: '有' + data.data + '条警告订单，请前往服务中订单查看。',
									offset: 80,
									duration: 0,
									type: "warning",
									onClose() {
										_this.updatesD5(1);
									}
								});
								this.errCount1 = data.data
								this.chatNum1 = data.data
								this.aplayAudio()
							}

						}
					} else {
						this.errCount1 = 0
						this.chatNum1 = 0
					}
				}
			})
		},
		// 获取超时订单数据
		dataSelectCs() {
			let _this = this
			this.$http({
				url: this.$http.adornUrl('artificer/selectOverTimeOrdersCount'),
				method: 'get',
				params: this.$http.adornParams({})
			}).then(({
				data
			}) => {
				if (data.data >= 0) {
					this.$cookie.set('numberCs', data.data)

					if (data.data > 0) {
						if (this.errCount != data.data) {
							if (data.data > this.errCount) {
								this.$notify.info({
									title: '消息',
									dangerouslyUseHTMLString: true,
									message: '有' + data.data + '条超时订单，请前往服务中订单查看。',
									offset: 80,
									duration: 0,
									type: "warning",
									onClose() {
										_this.updatesD5(2);
									}
								});
							}
							this.errCount = data.data
							this.chatNum = data.data
							this.aplayAudio()

						}
					} else {
						this.errCount = 0
						this.chatNum = 0
					}
				}
			})
		},
		updatesD5(index) {
			this.$router.push({
				path: '/orderInservice',
				query: {
					types: index
				}
			})
		},
		dataSelectXdd() {
			let _this = this
			this.$http({
				url: this.$http.adornUrl('message/selectOrdersCount'),
				method: 'get',
				params: this.$http.adornParams({
				})
			}).then(({
				data
			}) => {
				if (data.data >= 0) {
					if (data.data > 0) {
						if (this.errCount2 != data.data) {
							if (data.data > this.errCount2) {
								this.$notify.info({
									title: '消息',
									dangerouslyUseHTMLString: true,
									message: '有' + data.data + '条新订单，请前往订单中心查看。',
									offset: 80,
									duration: 0,
									type: "warning",
									onClose() {
										_this.updatesDX();
									}
								});
							}
							this.errCount2 = data.data
							this.chatNum2 = data.data
							this.aplayAudio()

						}
					} else {
						this.errCount2 = 0
						this.chatNum2 = 0
					}
				}
			})
		},
		updatesDX() {
			this.$router.push({
				path: '/orderCenter',
				query: {
				}
			})
		},
		aplayAudio() {
			const audio = document.getElementById('audio1');
			audio.play();
			console.log('订单语音提示');
		},
		// aplayAudio1() {
		//   const audio = document.getElementById('audio')
		//   audio.play()
		//   console.log('消息语音提示')
		// },
		getRingId() {
			this.$http({
				url: this.$http.adornUrl(`common/type/condition/xitong`),
				method: 'get',
				params: this.$http.adornParams({})
			}).then(({
				data
			}) => {
				if (data && data.code === 0) {
					let returnData = data.data;
					//将【开关配置】中id为394"是否开启打车费扣提成"隐藏
					let hasItemStaus = returnData.some((item) => item.id == 433);
					if (hasItemStaus) {
						let ringOrderArr = returnData.filter((item) => item.id == 433);
						if (ringOrderArr) window.localStorage.setItem("ringOrderId", ringOrderArr[0].value);
					}
					console.log(returnData);
				}
			})
		}
	},
	mounted() {
		this.getRingId();
		this.userSelect()
		// this.chatSelect()
		// this.chatSelect2()
		this.notification();

		this.dataSelect()
		this.dataSelectPy()
		this.dataSelectJjqz()
		this.dataSelectYh()
		if ((this.userId && this.ringOrderId) && (this.userId == this.ringOrderId)) {
			this.dataSelectJg()
			this.dataSelectCs()
		}
	},
	created() {
		// this.chatNum = setInterval(() => {
		//   this.chatSelect()
		// }, 6000)
		this.userId = window.localStorage.getItem('userId');
		this.ringOrderId = window.localStorage.getItem('ringOrderId');

		// this.chatNumJl = setInterval(() => {
		// 	this.dataSelect()
		// }, 6000)
		// this.chatNumQy = setInterval(() => {
		// 	this.dataSelectPy()
		// }, 6000)
		// this.chatNumJjqz = setInterval(() => {
		// 	this.dataSelectJjqz()
		// }, 6000)
		// this.chatNumYh = setInterval(() => {
		// 	this.dataSelectYh()
		// }, 6000)
		// 目前的逻辑是只有客服账号才有订单相关（新订单、警告订单、超时订单）的提示
		// if ((this.userId && this.ringOrderId) && (this.userId == this.ringOrderId)) {
		// 	this.chatNumJg = setInterval(() => {
		// 		this.dataSelectJg()
		// 	}, 6000)
		// 	this.chatNumCs = setInterval(() => {
		// 		this.dataSelectCs()
		// 	}, 6000)
		// 	this.chatNumXdd = setInterval(() => {
		// 		this.dataSelectXdd()
		// 	}, 3000)
		// }
	},
	beforeDestroy() {
		// clearInterval(this.chatNum)

		// clearInterval(this.chatNumJl);
		// clearInterval(this.chatNumQy);
		// clearInterval(this.chatNumJjqz);
		// clearInterval(this.chatNumYh);
		// clearInterval(this.chatNumJg);
		// clearInterval(this.chatNumCs);
		// clearInterval(this.chatNumXdd);
	}
}
</script>
<style scoped="scoped">
.site-navbar__avatar .el-dropdown-link>img {
	height: 36px;
}

.left-number {
	position: absolute;
	top: 0;
	right: 20px;
	width: 18px;
	height: 18px;
	line-height: 18px;
	border-radius: 50%;
	background: #ff4949;
	color: #ffffff;
	text-align: center;
	font-size: 10px;
	font-family: PingFang SC, PingFang SC-Regular;
	font-weight: 400;
	margin-top: 5px;
}
</style>
