<template>
	<div class="customerBox">
		<el-image class="img" @click="openCustomer" src="/img/CustomerService.svg"></el-image>
		<div class="customerView" v-if="customerShow">
			<span class="arrow"></span>
			<div class="viewBody">
				<div class="title">智能客服
					<el-icon class="close" size="18" @click.stop="closeCustomer"><el-icon-Close/></el-icon>
				</div>
				<div class="bodyMain affix-container">
					<el-scrollbar ref="scrollbar" height="100%" @scroll="scroll">
						<div class="innerRefCom">
							<div class="tagRow" ref="tagList">
								<el-scrollbar height="100%">
									<div class="tagList">
										<div class="tagItem" v-for="(item,index) in tagList" :key="index" @click="typeActive(item)">{{item.label}}</div>
									</div>
								</el-scrollbar>
							</div>
							<div class="msgList">
								<div class="msgItem" :class="user_id != item.to_user_id?'msgRightItem':''" v-for="(item,index) in msgList" :key="index">
									<div class="avatar" v-if="user_id === item.to_user_id">
										<el-avatar :size="36" :src="item.from_user.avatar" fit="cover">
											<img src="https://cube.elemecdn.com/e/fd/0fc7d20532fdaf769a25683617711png.png"/>
										</el-avatar>
									</div>
									<div class="msgText">
										<div class="msgTitle">
											<span class="leftTime" v-if="user_id != item.to_user_id">{{item.created_at}}</span>
											{{item.from_user && item.from_user.name?item.from_user.name:'匿名'}}
											<span class="time" v-if="user_id === item.to_user_id">{{item.created_at}}</span>
										</div>
										<div class="textCom" v-if="item.send_message_type === 1">
											<div v-html="item.to_message"></div>
										</div>
										<div class="textCom textComNoneBack" v-if="item.send_message_type === 2">
											<div :class="user_id != item.to_user_id?'fileRightItem':'fileLeftItem'" v-for="(em,ind) in item.to_message_list" :key="ind">
												<span class="imgView" :class="user_id != item.to_user_id?'imgViewRight':''" v-if="['png','jpg','gif','jpeg'].indexOf(em.file_type || em.extension) !=-1">
													<el-icon class="loadingIcon" size="30" v-if="user_id != item.to_user_id && em.showLoading" style="color:#333;padding: 4px;"><el-icon-Loading/></el-icon>
													<el-image style="width: 140px;height: 100px;" fit="contain" lazy :src="em.file?em.file:em" preview-teleported :preview-src-list="[em.file?em.file:em]"></el-image>
													<el-icon class="loadingIcon" size="30" v-if="user_id === item.to_user_id && em.showLoading" style="color:#333;padding: 4px;"><el-icon-Loading/></el-icon>
												</span>
												<span class="fileView" v-if="['png','jpg','gif','jpeg'].indexOf(em.file_type || em.extension) ===-1" @click="linkFile(em)">
													<fileType size="26px" :fileType="em.extension || em.file_type" />
													<span class="fileName">{{em.client_file_name?em.client_file_name:'未命名'}}</span>
												</span>
												<span class="progressLine" v-if="['png','jpg','gif','jpeg'].indexOf(em.file_type || em.extension) ===-1 && em.showLoading">
												<el-progress class="exportPopover" :text-inside="true" :show-text="false" :stroke-width="4" :percentage="em.rate" />
												</span>
											</div>
										</div>
									</div>
									<div class="avatar" v-if="user_id != item.to_user_id">
										<el-avatar :size="36" :src="item.from_user.avatar" fit="cover">
											<img src="https://cube.elemecdn.com/e/fd/0fc7d20532fdaf769a25683617711png.png"/>
										</el-avatar>
									</div>
								</div>
							</div>
						</div>
					</el-scrollbar>
				</div>
				<div class="footer">
					<div class="tagList">
						<div class="tagItem" @click="uploadFile">
							<uploadFile ref="uploadFile" @uploadFileSuccess="uploadFileSuccess" title="上传附件"></uploadFile>
						</div>
						<div class="tagItem" @click="recordsShow"><el-icon size="18"><sc-icon-Record/></el-icon></div>
						<el-dropdown trigger="click" placement="top" ref="dropdownDown">
							<div class="tagItem"><el-icon size="18"><sc-icon-Expression/></el-icon></div>
							<template #dropdown>
								<el-scrollbar height="180">
									<ul class="emojiView">
										<li class="emojiCol" v-for="(item,index) in emojiJson" :key="index" @click.stop="emojiChange(item)">{{item}}</li>
									</ul>
								</el-scrollbar>
							</template>
						</el-dropdown>
					</div>
					<div class="sendView">
						<el-input class="customTextarea" v-model="params.to_message" @keydown="handleKeydown" autofocus ref="messageInput" resize="none" type="textarea" :rows="3" placeholder="Shift+Enter换行 请简短描述您的问题"></el-input>
						<div class="saveBtn" :class="params.to_message!==''?'saveActive':''" @click="sendCustomer">发 送</div>
					</div>
				</div>
			</div>
		</div>
	</div>

	<customer-records-dialog v-if="dialog.show" ref="recordsMsgDialog" @closed="dialog.show=false"></customer-records-dialog>
</template>

<script>
import {eventBus} from "@/utils/eventBus";
import uploadFile from "@/views/service/components/attachmentUpload";
import customerRecordsDialog from "@/views/service/components/customerRecords"
import fileType from "@/views/docsManager/fileType"
import emoji from "@/views/service/components/emoji.json";
export default {
	name: "index",
	components:{
		uploadFile,
		customerRecordsDialog,
		fileType
	},
	data(){
		return{
			dialog:{
				show:false
			},
			customerShow:false,
			user_info:{
				name:"随机客服"
			},
			page:1,
			params:{
				client:2,
				type:"",
				to_user_id:"",
				to_message:"",
			},
			emojiJson:[],
			tagList:[],
			msgList:[],
			user_id:0,
		}
	},
	computed: {

	},
	mounted() {
		let token = this.$TOOL.cookie.get('TOKEN');
		if (token && token != null) {
			// 登录成功连接ws
			// let global_callback = function () {};
			// this.$socketApi.createWebSocket(global_callback);

			// 获取新消息
			eventBus.$on('sockBack', this.getWsResult);

			const userInfo = this.$TOOL.data.get("USER_INFO");
			if(userInfo && userInfo.id){
				this.user_id = userInfo.id;
			}
		}

		this.emojiJson = emoji.data.split(',');
		document.addEventListener('click', this.closeDropdown);
	},
	unmounted() {
		eventBus.$off('sockBack', this.getWsResult);
		document.removeEventListener('click', this.closeDropdown);
	},
	methods:{
		getWsResult(res){
			if(res.data && (res.data.type == 12 || res.data.type == 35 || res.data.type == 36 || res.data.type == 37)){
				switch(res.data.type) {
					case 12:  // 接收进度
						this.msgList.forEach(item=>{
							if(item.to_message_list && item.to_message_list.length>0){
								item.to_message_list.forEach(em=>{
									if(em.uuid && em.uuid === res.data.file_unique_id){
										em.showLoading = res.data.rate !== 100;
										em.rate = res.data.rate;
									}
								})
							}
						})
						break;
					case 35:  // 接收消息
						if(res.data.send_message_type === 2 && res.data.data.to_message){
							res.data.data.to_message_list = JSON.parse(res.data.data.to_message);
						}
						if(res.data.data){
							let obj = {
								created_at: res.data.from_time,
								send_message_type: res.data.send_message_type ? res.data.send_message_type : 1,
								to_user_id: res.data.to_user_id,
								to_message: res.data.data.to_message,
								to_message_list: res.data.data.to_message_list,
								from_user: {
									avatar: res.data.from_avatar,
									name: res.data.from_user,
								}
							};
							this.msgList.push(obj);
							setTimeout(()=>{
								this.scrollDown();
							},100);
						}
						break;
					case 36:  // 系统记录
						res.data.rows.forEach((item)=>{
							if(item.send_message_type == 2){
								item.to_message_list = JSON.parse(item.to_message);
							}
						})
						this.msgList = res.data.rows.concat(this.msgList);
						this.page = res.data.page;
						setTimeout(()=>{
							if(res.data.page === res.data.pageSize){
								this.scrollDown();
							}
						},100);
						break;
					case 37:  // 随机客服
						this.user_info = res.data.user.user_info;
						this.params.to_user_id = res.data.user.uid;
						this.msgList.push({
							to_user_id:this.user_id,
							send_message_type:1,
							created_at:this.$TOOL.dateFormat(new Date()),
							from_user:{
								name:res.data.user.user_info.name,
								avatar:res.data.user.user_info.avatar
							},
							to_message:res.data.to_message
						})
						setTimeout(()=>{
							this.scrollDown();
						},100);
						break;
					default:
						break;
				}
			}
		},
		openCustomer(){
			this.customerShow = !this.customerShow;
			if(this.customerShow){
				this.customerType();
				this.getRecordList();

				this.getAssign();

				// 控制条控制在底部
				this.scrollDown();
			}
		},
		closeCustomer(){
			this.customerShow = false;
		},

		async getAssign() {
			await this.$API.customer.customer.post();
		},
		async getRecordList(isPage=false) {
			let params = {}
			if(!isPage){
				params = {
					to_user_id:'',
					pageSize:30
				}
			}else{
				params = {
					to_user_id:'',
					page:this.page,
					pageSize:30
				}
			}
			await this.$API.customer.list.post(params);
		},
		async customerType() {
			const res = await this.$API.customer.typeList.post();
			if (res.code == 200) {
				this.tagList = res.data;
			}
		},
		typeActive(item){
			this.params.type = item.value;
		},

		handleKeydown(event){
			if(event.key === 'Enter' && !event.shiftKey){
				event.preventDefault(); // 阻止输入框的默认行为
				this.sendCustomer();
			}else if(event.key === 'Enter' && event.shiftKey){
				this.params.to_message += '';
			}
		},
		async sendCustomer() {
			if(this.params.to_message =="") return
			const res = await this.$API.customer.send.post(this.params);
			if(res.code == 200){
				const userInfo = this.$TOOL.data.get("USER_INFO");
				this.msgList.push({
					to_user_id:-1,
					send_message_type:1,
					created_at:this.$TOOL.dateFormat(new Date()),
					from_user:{
						name:userInfo.name,
						avatar:userInfo.avatar
					},
					to_message:this.params.to_message
				});
				this.params.to_message = "";
				this.scrollDown();
			}
		},

		emojiChange(item){
			let text = this.$TOOL.objCopy(this.params.to_message);
			this.params.to_message = text + item;
		},
		closeDropdown(event){
			if(this.$refs.dropdownDown && this.$refs.dropdownDown.$el){
				const dropdownElement = this.$refs.dropdownDown.$el;
				if (!dropdownElement.contains(event.target)) {
					this.$refs.dropdownDown.handleClose();
				}
			}
			setTimeout(()=>{
				this.$nextTick(()=>{
					if(this.$refs.messageInput){
						this.$refs.messageInput.focus();
					}
				})
			},10)
		},

		// 上传附件
		uploadFile(){
			this.$nextTick(()=>{
				this.$refs.uploadFile.importFile(this.params);
			})
		},
		uploadFileSuccess(data){
			const userInfo = this.$TOOL.data.get("USER_INFO");
			this.msgList.push({
				to_user_id:-1,
				send_message_type:2,
				created_at:this.$TOOL.dateFormat(new Date()),
				from_user:{
					name:userInfo.name,
					avatar:userInfo.avatar
				},
				to_message_list:data,
				to_message:''
			});

			setTimeout(()=>{
				this.scrollDown();
			},100)
		},

		recordsShow(){
			this.dialog.show = true;
			this.$nextTick(() => {
				let params = {
					from_user_id:this.params.to_user_id,
					from_user:{
						name:this.user_info.name
					}
				}
				this.$refs.recordsMsgDialog.open('show').setData(params);
			})
		},
		linkFile(em){
			window.location.href = em.file;
		},

		scroll(e){
			let {scrollTop} = e;
			if(!scrollTop) {return false}
			if(scrollTop>10){
				this.$refs.tagList.style.position = "absolute";
				this.$refs.tagList.style.background = "#fff";
			}else{
				this.$refs.tagList.style.position = "relative";
				this.$refs.tagList.style.background = "";
			}
			if(scrollTop === 0 && this.msgList.length>0 && this.page >1){
				this.page = this.page -1;
				this.getRecordList(true)
			}
		},
		scrollDown() {
			this.$nextTick(() => {
				const wrap = this.$refs.scrollbar;
				if(wrap){
					const e = wrap.$el.querySelector('.el-scrollbar__wrap')
					if(e){
						e.scrollTop = e.scrollHeight;
					}
				}
			})
		},
	}
}
</script>

<style scoped lang="scss">
.customerBox{
	position: absolute;
	right: 40px;
	bottom: 80px;
	z-index: 1000;
	.img{
		width: 56px;
		height: 56px;
		cursor: pointer;
	}
	.customerView{
		width: 380px;
		height: 600px;
		position: absolute;
		right: 0;
		bottom: 70px;
		background: #fff;
		box-shadow: 0 4px 4px rgba(19,103,193,0.3);
		border: 1px solid #B7D7F9;
		border-radius: 8px;
		.viewBody{
			display: flex;
			flex-direction: column;
			height: 100%;
			.title{
				padding: 15px 10px;
				border-bottom: 1px solid #F6F6F6;
				font-size: 14px;
				font-weight: 500;
				display: flex;
				align-items: center;
				justify-content: space-between;
				.close{
					cursor: pointer;
				}
			}
			.affix-container {
				position: relative;
			}
			.bodyMain{
				flex: 1;
				overflow: hidden;
				.tagRow{
					position: relative;
					left: 0;
					z-index: 200;
					height: 100px;
				}
				.tagList{
					display: flex;
					flex-wrap: wrap;
					padding: 0 10px 10px 10px;
					.tagItem{
						background: #F4F4F4;
						padding: 10px;
						border-radius: 4px;
						margin: 10px 10px 0 0;
						color: #555;
						cursor: pointer;
					}
				}
				.msgList{
					padding: 10px;
					.msgItem{
						display: flex;
						margin-bottom: 12px;
						.avatar{
							padding-right: 10px;
						}
						.msgText{
							flex: 1;
							overflow: hidden;
							.msgTitle{
								padding: 0 0 8px 0;
								color: #555;
								.time{
									margin-left: 8px;
									font-size: 12px;
									color: #888;
								}
								.leftTime{
									margin-right: 8px;
									font-size: 12px;
									color: #888;
								}
							}
							.textCom{
								background: #f5f5f5;
								border-radius: 4px;
								padding: 10px;
								display: inline-block;
								text-align: left;
								max-width: 100%;
								.imgView{
									height: 100%;
									display: flex;
									align-items: center;
									justify-content: flex-start;
									margin-bottom: 5px;
									.loadingIcon{
										animation: rotate 1s linear infinite;
									}
									@keyframes rotate {
										0% {
											transform: rotate(0deg);
										}
										100% {
											transform: rotate(360deg);
										}
									}
								}
								.imgViewRight{
									justify-content: flex-end;
								}
								.fileView{
									cursor: pointer;
									color: var(--el-color-primary);
									display: flex;
									align-items: center;
									border: 1px solid #f4f4f4;
									padding: 10px;
									border-radius: 4px;
									background: #f8f6f6;
									margin-bottom: 5px;
									overflow: hidden;
									.fileName{
										flex: 1;
										white-space: pre-wrap;
										overflow-wrap: break-word;
										display: inline-block;
										word-break:break-all;
									}
								}
							}
							.el-image{
								border-radius: 4px;
							}
							.textComNoneBack{
								background: none;
								padding: 10px 0;
								.fileLeftItem{
									padding-right: 48px;
								}
								.fileRightItem{
									text-align: right;
									padding-left: 48px;
								}
							}
						}
					}
					.msgRightItem{
						justify-content: flex-end;
						.avatar{
							padding-left: 10px;
							padding-right: 0;
						}
						.msgText{
							text-align: right;
							.msgTitle{
								text-align: right;
							}
							.textCom{
								background: var(--el-color-primary);
								color: var(--el-color-white);
								text-align: left;
							}
							.textComNoneBack{
								background: none;
								.el-image{
									border-radius: 4px;
								}
							}
						}
					}
				}
			}
			.footer{
				padding: 10px 0;
				border-top: 1px solid #F6F6F6;
				position: relative;
				.tagList{
					display: flex;
					align-items: center;
					border-bottom: 1px solid #F6F6F6;
					padding-bottom: 10px;
					.tagItem{
						display: flex;
						align-items: center;
						justify-content: center;
						margin-left: 15px;
						cursor: pointer;
					}
				}
				.customTextarea{
					font-size:13px;
					::v-deep .el-textarea__inner{
						box-shadow: none;
						border: 0;
						padding-right: 60px;
					}
					::v-deep .el-textarea__inner::-webkit-scrollbar{
						width: 0;
					}
				}
				.saveBtn{
					position: absolute;
					bottom:22px;
					right: 10px;
					z-index: 10;
					padding: 7px 15px;
					background: #f4f4f5;
					color: #A8ABB2;
					border-radius: 3px;
					cursor: not-allowed;
				}
				.saveActive{
					cursor: pointer;
					background: var(--el-color-primary);
					color: var(--el-color-white);
				}
			}
		}
	}
	.arrow{
		position: absolute;
		bottom: -5px;
		right: 12px;
		z-index: 1;
	}
	.arrow:before{
		content: "";
		position: absolute;
		bottom: 0;
		right: 12px;
		z-index:1;
		width: 8px;
		height: 8px;
		border: 1px solid #B7D7F9;
		border-left-color:transparent;
		border-top-color:transparent;
		transform:rotate(45deg);
		background: #fff;
	}
}

.emojiView{
	width: 380px;
	padding: 10px;
	display: flex;
	flex-wrap: wrap;
	.emojiCol{
		padding: 5px;
		cursor: pointer;
		font-size: 16px;
		list-style: none;
	}
}
</style>
