<template>
	<view class="msg-box">
		<!-- 顶部导航栏 -->
		<view class="nav-header">
			<view class="nav-left" @click="goSearch">
				<u-icon name="search" color="rgba(56, 58, 63, 1)" size="32"></u-icon>
			</view>
			<view class="nav-center">
				<text class="nav-title">消息</text>
			</view>
			<view class="nav-right">
				<u-icon name="bell" color="rgba(56, 58, 63, 1)" size="32" style="margin-right: 20rpx;"></u-icon>
				<u-icon name="setting" color="rgba(56, 58, 63, 1)" size="32" @click="showSettingsModal"></u-icon>
			</view>
		</view>
		
		<view class="chat-title">聊天</view>
		
		<view v-if="msgList.length" class="margin-topW">
			<view class="flex padding-tb radius padding-lr-sm bg" @click="goMsg" v-for="(item,index) in msgList"
				:key='index'>
				<view>
					<image style="width: 80rpx;height: 80rpx;border-radius: 80rpx;"
						src="../../static/images/msg/msg.png"></image>
				</view>
				<view class="flex-sub margin-left-sm">
					<view class="flex justify-between">
						<view class="text-white">{{item.title?item.title: '系统消息'}}</view>
						<view v-if="messageCount>0"
							style="height: 32rpx;width: 32rpx;border-radius: 100rpx;background-color: red;color: #FFF;text-align: center;">
							{{messageCount}}
						</view>
					</view>
					<view>
						<view class="text-grey">{{item.content}}</view>
					</view>
				</view>
			</view>
		</view>
		<view class="margin-topW">
			<view class="flex padding-tb radius padding-lr-sm bg" @click="goChat">
				<view>
					<image style="width: 80rpx;height: 80rpx;border-radius: 80rpx;"
						src="../../static/images/msg/msgs.png"></image>
				</view>
				<view class="flex-sub margin-left-sm">
					<view class="flex justify-between">
						<view class="text-white">在线客服</view>
						<view v-if="userCount>0"
							style="height: 32rpx;width: 32rpx;border-radius: 100rpx;background-color: red;color: #FFF;text-align: center;">
							{{userCount}}
						</view>
					</view>
					<view>
						<view class="text-grey">联系在线客服</view>
					</view>
				</view>
			</view>
		</view>

		<view v-if="chatList.length" class="margin-top-sm  content ">
			<view class="radius padding-lr-sm bg" style="margin-top: 4rpx;" @click="goIM(item)"
				v-for="(item,index) in chatList" :key='index'>
				<view class="flex padding-tb ">
					<view class="avatar-container">
						<u-image shape="circle" width='80rpx' height="80rpx" :src="item.avatar"></u-image>
						<view class="online-dot"></view>
					</view>
					<view class="flex-sub margin-left-sm">
						<view class="flex justify-between align-center">
							<view class="text-white flex align-center userNameleng">
								<view class="text-white" style="font-size: 28rpx;">
									{{item.userName}}
								</view>
								<text class="text-grey"
									style="font-size: 22rpx;margin-left: 10rpx;"><text v-if="item.companyName">{{item.companyName}} |</text> {{item.stationName}}
								</text>
							</view>
							<view class="text-grey">{{item.messageTime?getMonthOrDay(item.messageTime):''}}</view>
						</view>
						<view class="flex justify-between" style="margin-top: 10rpx;">
							<view class="text-grey" v-if="item.messageType == 1">{{item.content}}</view>
							<view class="text-grey" v-else-if="item.messageType == 18">位置</view>
							<view class="text-grey" v-else-if="item.messageType == 9">简历请求</view>
							<view class="text-grey" v-else-if="item.messageType == 6">微信请求</view>
							<view class="text-grey" v-else-if="item.messageType == 5">手机号请求</view>
							<view class="text-grey" v-else-if="item.messageType == 2">[图片]</view>
							<view class="text-grey" v-else-if="item.messageType == 4"><image class="chat-listitem-text"
							v-if="item.content && item.messageType === 4"
							:src="ossUrl +item.content"
							style="height: 40rpx;width: 40rpx;"></image></view>
							<view class="text-grey" v-else-if="item.messageType == 20">[视频通话]</view>
							<view class="text-grey" v-else-if="item.messageType == 21">[语音通话]</view>
							<view v-if="item.contentCount"
								style="height: 32rpx;width: 32rpx;border-radius: 100rpx;background-color: red;color: #FFF;text-align: center;">
								{{item.contentCount}}
							</view>

						</view>
					</view>
				</view>
				<!-- <view class="flex padding-tb" v-else>
					<view>
						<u-image shape="circle" width='80rpx' height="80rpx" :src="item.avatar"></u-image>
					</view>
					<view class="flex-sub margin-left-sm">
						<view class="flex justify-between">
							<view class="text-white">{{item.userName}}</view>
							<view class="text-grey">{{item.messageTime?item.messageTime:''}}</view>
						</view>
						<view class="flex justify-between">
							<view class="text-grey" v-if="item.messageType == 1">{{item.content}}</view>
							<view class="text-grey" v-else-if="item.messageType == 18">位置</view>
							<view class="text-grey" v-else-if="item.messageType == 9">简历请求</view>
							<view class="text-grey" v-else-if="item.messageType == 6">微信请求</view>
							<view class="text-grey" v-else-if="item.messageType == 5">手机号请求</view>
							<view class="text-grey" v-else>[图片]</view>
							<view v-if="item.contentCount"
								style="height: 32rpx;width: 32rpx;border-radius: 100rpx;background-color: red;color: #FFF;text-align: center;">
								{{item.contentCount}}
							</view>
						</view>
					</view>
				</view> -->
			</view>
		</view>

		<empty v-if="!chatList.length" content='暂无消息'></empty>
		
		<!-- 消息设置弹窗 -->
		<u-popup v-model="showSettings" mode="bottom" :mask-close-able="true" border-radius="20">
			<view class="settings-modal">
				<view class="modal-drag-bar"></view>
				<view class="modal-title">消息设置</view>
				
				<!-- 消息通知开关 -->
				<view class="setting-item setting-item-first">
					<view class="setting-left">
						<view class="setting-title-row">
							<view class="setting-label">消息通知开关</view>
							<view class="setting-desc">关闭后将不再向你推送消息通知</view>
						</view>
						<view class="switch-status" :class="{ 'status-on': notificationEnabled, 'status-off': !notificationEnabled }">
							{{ notificationEnabled ? 'On' : 'Off' }}
						</view>
					</view>
					<view class="setting-right">
						<u-switch v-model="notificationEnabled" active-color="#007AFF" @change="toggleNotification"></u-switch>
					</view>
				</view>
				
				<!-- 招呼语设置 -->
				<view class="setting-item" @click="goGreetingSettings">
					<view class="setting-left">
						<view class="setting-label">招呼语设置</view>
					</view>
					<view class="setting-right">
						<view class="setting-desc">设置后,沟通时可自动发送设置的招呼语</view>
						<u-icon name="arrow-right" color="rgba(29, 33, 41, 1)" size="24"></u-icon>
					</view>
				</view>
				
				<!-- 常用语设置 -->
				<view class="setting-item" @click="goCommonPhrases">
					<view class="setting-left">
						<view class="setting-label">常用语设置</view>
					</view>
					<view class="setting-right">
						<u-icon name="arrow-right" color="rgba(29, 33, 41, 1)" size="24"></u-icon>
					</view>
				</view>
			</view>
		</u-popup>
	</view>
</template>

<script>
	import empty from '../../components/empty.vue'
	import configData from '../../common/config.js'
	export default {
		components: {
			empty
		},
		data() {
			return {
				page: 1,
				limit: 100,
				chatList: [],
				userId: '',
				msgList: [],
				time: '',
				messageCount: 0,
				userCount: 0,
				arr: [],
				showModal: true,
				showSettings: false, // 控制设置弹窗显示
				notificationEnabled: true, // 消息通知开关状态
				ossUrl:configData.ossUrl
			}
		},
		onLoad() {
			if (uni.getStorageSync('userId')) {
				this.getChatList()
			}

		},
		//下拉刷新
		onPullDownRefresh() {
			let that = this
			if (uni.getStorageSync('token')) {
				that.getweiduMsg();
				that.getChatList()
				that.getMsgList()
				that.$nextTick(function() {
					that.messageCount = uni.getStorageSync('messageCount')
				})
			}
		},
		onShow() {
			let that = this
			that.userId = uni.getStorageSync('userId')
			if (that.userId) {
				that.time = setInterval(function() {
					that.getweiduMsg();
					that.getChatList()
					that.getMsgList()
					that.$nextTick(function() {
						that.messageCount = uni.getStorageSync('messageCount')
					})

				}, 3000)
				this.$Request.getT('/app/common/type/310').then(res => { //消息未读提醒
					if (res.code == 0) {
						if (res.data && res.data.value) {
							this.arr.push(res.data.value)
						}
					}
				})
				this.$Request.getT('/app/common/type/337').then(res => { //预约成功通知(通用)
					if (res.code == 0) {
						if (res.data && res.data.value) {
							this.arr.push(res.data.value)
						}
					}
				})
				this.$Request.getT('/app/common/type/338').then(res => { //订单状态通知
					if (res.code == 0) {
						if (res.data && res.data.value) {
							this.arr.push(res.data.value)
						}
					}
				})
				// #ifdef MP-WEIXIN
				if (this.showModal) {
					this.openMsg()
				}
				// #endif
			} else {
				that.chatList = []
				that.msgList = []
			}
		},
		onHide() {
			clearInterval(this.time)
		},
		methods: {
			//把时间转换为月日
			getMonthOrDay(time) {
				let date = new Date(time) // 获取时间
				// var year = date.getFullYear() // 获取年
				let month = date.getMonth() + 1 // 获取月
				let strDate = date.getDate() // 获取日
				return month + '月' + strDate + '日'
			},
			// 开启订阅消息
			openMsg() {
				console.log('订阅消息')
				var that = this
				uni.getSetting({
					withSubscriptions: true, //是否获取用户订阅消息的订阅状态，默认false不返回
					success(ret) {
						console.log(ret.subscriptionsSetting.itemSettings, '*************************************')
						// if (ret.subscriptionsSetting.itemSettings && Object.keys(ret.subscriptionsSetting.itemSettings).length == 2) {
						if (ret.subscriptionsSetting.itemSettings) {
							uni.setStorageSync('sendMsg', true)
							uni.openSetting({ // 打开设置页 
								success(rea) {
									console.log(rea.authSetting)
								}
							});
						} else { // 用户没有点击“总是保持以上，不再询问”则每次都会调起订阅消息
							uni.setStorageSync('sendMsg', false)
							uni.showModal({
								title: '提示',
								content: '为了更好的体验,请绑定消息推送',
								confirmText: '确定',
								cancelText: '取消',
								confirmColor: '#016BF6',
								success: function(res) {
									if (res.confirm) {
										wx.requestSubscribeMessage({
											tmplIds: that.arr,
											success(re) {
												console.log(JSON.stringify(re),
													'++++++++++++++')
												var datas = JSON.stringify(re);
												if (datas.indexOf("accept") != -1) {
													console.log(re)
													// uni.setStorageSync('sendMsg', true)
												}
											},
											fail: (res) => {
												console.log(res)
											}
										})
										// uni.setStorageSync('sendMsg', true)
										console.log('确认')
										that.showModal = false
									} else if (res.cancel) {
										console.log('取消')
										// uni.setStorageSync('sendMsg', false)
										that.showModal = true
									}
								}
							})
						}
					}
				})
			},
			getweiduMsg() {
				this.$Request.get("/app/chats/userCount").then(res => {
					uni.stopPullDownRefresh()
					if (res.code == 0) {
						this.userCount = res.data
					}
				});
			},
			//在线客服
			goChat() {
				// uni.navigateTo({
				// 	url:'/my/setting/chat'
				// })
				// #ifdef MP-WEIXIN
				if (uni.getStorageSync('sendMsg')) {
					// console.log('授权+1')
					wx.requestSubscribeMessage({
						tmplIds: this.arr,
						success(re) {
							// console.log(JSON.stringify(re), 111111111111)
							var datas = JSON.stringify(re);
							if (datas.indexOf("accept") != -1) {
								// console.log(re)
							}
						},
						fail: (res) => {
							// console.log(res)
						}
					})
				}
				// #endif
				let that = this
				if (uni.getStorageSync('userType') == 1) { //用户端
					// #ifdef MP-WEIXIN
					wx.openCustomerServiceChat({
						extInfo: {
							url: that.$queue.getData('kefu')
						},
						corpId: that.$queue.getData('kefuAppid'),
						success(res) {
							console.log(res)
						},
					})
					// #endif
					// #ifdef H5
					window.location.href = that.$queue.getData('kefu');
					// #endif
					// #ifdef APP
					let kefu = that.$queue.getData('kefu')
					console.log(kefu)
					plus.runtime.openURL(kefu, function(res) {});
					// #endif
				} else { //企业端
					// #ifdef MP-WEIXIN
					wx.openCustomerServiceChat({
						extInfo: {
							url: that.$queue.getData('kefuq')
						},
						corpId: that.$queue.getData('kefuAppidq'),
						success(res) {
							console.log(res)
						},
					})
					// #endif
					// #ifdef H5
					window.location.href = that.$queue.getData('kefuq');
					// #endif
					// #ifdef APP
					let kefu = that.$queue.getData('kefuq')
					console.log(kefu)
					plus.runtime.openURL(kefu, function(res) {});
					// #endif
				}

			},
			getChatList() {
				this.$Request.get("/app/chat/selectChatConversationPage", {
					page: this.page,
					limit: this.limit
				}).then(res => {
					uni.stopPullDownRefresh()
					if (res.code == 0) {
						this.chatList = res.data.list
					}
				});
			},
			getMsgList() {
				this.$Request.get("/app/message/selectMessageByUserIdLimit1").then(res => {
					uni.stopPullDownRefresh()
					if (res.code == 0) {
						this.msgList = res.data.list
					}
				});
			},
			goIM(e) {
				// #ifdef MP-WEIXIN
				if (uni.getStorageSync('sendMsg')) {
					// console.log('授权+1')
					wx.requestSubscribeMessage({
						tmplIds: this.arr,
						success(re) {
							// console.log(JSON.stringify(re), 111111111111)
							var datas = JSON.stringify(re);
							if (datas.indexOf("accept") != -1) {
								// console.log(re)
							}
						},
						fail: (res) => {
							// console.log(res)
						}
					})
				}
				// #endif
				let userId = '';
				let userType = uni.getStorageSync('userType')
				console.log(e, 'aaaaaaaaa')
				if (userType == 2) { //当前登录用户为企业
					userId = e.userId
				} else { //当前登录用户为用户
					userId = e.focusedUserId
				}
				if (uni.getStorageSync('userType') == 1) {
					uni.navigateTo({
						url: '/pages/msg/im?chatConversationId=' + e.chatConversationId + '&byUserId=' + userId +
							'&postPushId=' + e.postPushId + '&resumesId=' + e.resumesId
					})
				} else {
					uni.navigateTo({
						url: '/pages/msg/im?chatConversationId=' + e.chatConversationId + '&byUserId=' + userId +
							'&resumesId=' + e.resumesId + '&postPushId=' + e.postPushId
					})
				}

			},
			goMsg() {
				// #ifdef MP-WEIXIN
				if (uni.getStorageSync('sendMsg')) {
					// console.log('授权+1')
					wx.requestSubscribeMessage({
						tmplIds: this.arr,
						success(re) {
							// console.log(JSON.stringify(re), 111111111111)
							var datas = JSON.stringify(re);
							if (datas.indexOf("accept") != -1) {
								// console.log(re)
							}
						},
						fail: (res) => {
							// console.log(res)
						}
					})
				}
				// #endif
				uni.navigateTo({
					url: '/pages/msg/message'
				})
			},
			
			// 显示设置弹窗
			showSettingsModal() {
				this.showSettings = true
			},
			
			// 切换通知开关
			toggleNotification() {
				// 开关状态已经通过v-model自动更新，这里可以添加其他逻辑
				console.log('通知开关状态:', this.notificationEnabled)
			},
			
			// 招呼语设置
			goGreetingSettings() {
				uni.navigateTo({
					url: '/pages/msg/addmsg'
				})
			},
			
			// 常用语设置
			goCommonPhrases() {
				uni.navigateTo({
					url: '/pages/msg/addmsg'
				})
			},
			// 搜索功能
			goSearch() {
				uni.navigateTo({
					url: '/pages/msg/search'
				})
			}
		}
	}
</script>

<style lang="scss">
	.msg-box {
		padding-top: 80rpx;

		.chat-title {
			background: linear-gradient(180deg, rgba(13, 39, 247, 1) 0%, rgb(191, 194, 201) 100%);
			-webkit-background-clip: text;
			background-clip: text;
			-webkit-text-fill-color: transparent;
			color: transparent;
			font-family: DM Sans;
			font-size: 42rpx;
			font-weight: 500;
			line-height: 28px;
			letter-spacing: 0%;
			text-align: left;
			margin: 20rpx 0 20rpx 20rpx;
		}
		
		.margin-top-sm {
			margin-top: 0 !important;
		}

		.nav-header {
			height: 80rpx;
			display: flex;
			align-items: center;
			justify-content: space-between;
			padding: 0 20rpx;
		}

		.nav-left {
			width: 60rpx;
			display: flex;
			justify-content: flex-start;
		}

		.nav-center {
			flex: 1;
			display: flex;
			justify-content: center;
		}

		.nav-title {
			font-size: 36rpx;
			font-weight: 600;
			color: #333333;
		}

		.nav-right {
			width: 60rpx;
			display: flex;
			justify-content: flex-end;
			align-items: center;
		}

		.bg {
			background: #FFFFFF;
		}

		.userNameleng {
			width: 80%;
			overflow: hidden;
			white-space: nowrap;
			text-overflow: ellipsis;
			-o-text-overflow: ellipsis;
		}

		.avatar-container {
			position: relative;
			display: inline-block;
		}

		.online-dot {
			position: absolute;
			bottom: 2rpx;
			right: 2rpx;
			width: 20rpx;
			height: 20rpx;
			background-color: #00FF00;
			border-radius: 50%;
			border: 2rpx solid #FFFFFF;
		}
	}
	
	// 设置弹窗样式
	.settings-modal {
		background: #FFFFFF;
		border-radius: 20rpx 20rpx 0 0;
		padding: 0 30rpx 40rpx 30rpx;
		min-width: 100%;
		
		.modal-drag-bar {
			width: 60rpx;
			height: 8rpx;
			background: #E5E5E5;
			border-radius: 4rpx;
			margin: 20rpx auto 30rpx auto;
		}
		
		.modal-title {
			margin: 0 auto;
			color: rgba(34, 37, 42, 1);
			font-family: DM Sans;
			font-size: 36rpx;
			font-weight: 500;
			line-height: 23px;
			letter-spacing: 0px;
			text-align: center;
			padding-bottom: 20rpx;
			border-bottom: 1rpx solid rgba(219, 218, 218, 1);
		}
		
		.setting-item {
			display: flex;
			align-items: center;
			justify-content: space-between;
			padding: 12rpx 32rpx;
			margin-bottom: 30rpx;
			border: 1px solid rgba(227, 231, 236, 1);
			border-radius: 6px;
			
			
			&:active {
				background-color: #F8F8F8;
			}
			
			&.setting-item-first {
				border: none;
				padding: 40rpx 32rpx;
			}
			
			.setting-left {
				display: flex;
				flex-direction: column;
				align-items: flex-start;
				flex: 1;
				
				.setting-title-row {
					display: flex;
					align-items: center;
					justify-content: flex-start;
					width: 100%;
					margin-bottom: 16rpx;
					
					.setting-label {
						color: rgba(21, 22, 26, 1);
						font-family: DM Sans;
						font-size: 32rpx;
						font-weight: 600;
						line-height: 26px;
						letter-spacing: 0%;
						text-align: left;
						margin-right: 16rpx;
					}
					
					.setting-desc {
						color: rgba(153, 153, 153, 1);
						font-family: DM Sans;
						font-size: 22rpx;
						font-weight: 400;
						line-height: 13px;
						letter-spacing: 0%;
						text-align: left;
					}
				}
				
				.switch-status {
					font-size: 32rpx;
					
					&.status-on {
						color: #007AFF;
					}
					
					&.status-off {
						color: #999999;
					}
				}
			}
			
				.setting-right {
					display: flex;
					align-items: center;
					justify-content: flex-end;
					
					.u-switch {
						margin-top: 20rpx;
						transform: scale(1.2); // 放大开关到1.5倍
					}

				.setting-desc {
					color: rgba(153, 153, 153, 1);
					font-family: DM Sans;
					font-size: 22rpx;
					font-weight: 400;
					line-height: 13px;
					letter-spacing: 0%;
					text-align: left;
					margin-right: 16rpx;
				}
			}
		}
	}

	
</style>