<template>
  <div class="box">
    <!-- 点击播放audio -->
    <audio ref="audio" style="display: none;" />
    <!-- 单人自动播放 audio -->
    <audio ref="audioAuto" style="display: none;" />
    <div v-show="!chatShow" class="hello content">
      <div ref="content" class="chatContent">
        <ul class="newsList">
          <div v-for="(nor, index) in textList" :key="index" style="margin-top: 5px;">
            <li v-if="nor.self" style="position: relative">
              <div class="userName" style="position: absolute; right: 4px; top: 4px; font-size: 14px;">
                {{ `${ChatFomat.formatTime(nor.chatTime)} ${ChatFomat.formatName(nor.member)}` }}
              </div>
              <div class="news">
                <span>{{ ChatFomat.formatSay(nor) }}</span>
              </div>
              <div v-if="nor.voice" class="yuyin" @click="playAudio(nor)">
                <i class="el-icon-caret-right" />
              </div>
            </li>
            <li v-if="nor.other" style="position: relative">
              <div class="userName" style="position: absolute; left: 12px; top: 4px; font-size: 14px;">
                {{ `${ChatFomat.formatName(nor.member)} ${ChatFomat.formatTime(nor.chatTime)}` }}
              </div>
              <div class="answers">
                <span>{{ ChatFomat.formatSay(nor) }}</span>
              </div>
              <div v-if="nor.voice" class="yuyin1" @click="playAudio(nor)">
                <i class="el-icon-caret-right" />
              </div>
            </li>
            <li v-if="nor.join" style="font-size: 12px; text-align: center;">{{ nor.simulationTip }}</li>
          </div>
        </ul>
      </div>
      <div class="footChat">
        <div class="inputBox">
          <div
            class="sendBtn zIndex1"
            :style="{background: background, color: color,}"
            :disabled="true"
            @mousedown="startRecording()"
            @mouseup="stopRecording()"
          >{{ speak }}</div>
          <div v-show="sending" class="sendBtn zIndex2" :style="{background: background}">发送中...</div>
        </div>
        <div v-if="isShowAuto" class="switch-box">
          <span style="font-size: 12px;">自动播放</span>
          <el-switch v-model="isAutoPlay" active-color="#13ce66" inactive-color="#d6d6d6" />
        </div>
      </div>
    </div>
    <!-- 待播放列表 audio list-->
    <audio ref="autoPlay" src="" />
    <!-- 遮罩空白 -->
    <div v-show="chatShow" class="hello content" />
  </div>
</template>

<script>
// import Vue from 'vue';
import HZRecorder from '@/utils/HZRecorder';
import ChatFomat from '@/utils/chatFomat';
// import StompClient from '@/utils/sock';
import { postDataBd, getConversation } from '@/api/chat';
// import { handleToken } from '@/utils/auth';
import { displayTopic, clearSubscribe } from '@/utils/stomp';
import { sendCommand } from '@/api/jmap/training';
import EventBus from '@/scripts/event-bus';

export default {
	name: 'ChartWindow',
	props: {
		group: {
			type: String
		},
		chatShow: {
			type: Boolean
		},
		speaking: {
			type: Boolean
		},
		isShowAuto: {
			type: Boolean
		}
	},
	data() {
		return {
			userId: '',
			topic: '/user/topic/simulation/chat',
			recorders: null,
			textList: [],
			background: '#edf2fc',
			color: '#c6c6c6',
			label: '',
			message: {},
			sending: false,
			speak: '按住说话',
			targetId: '',
			conversationId: '',
			allConversationId: '', //  所有人会话id
			isAutoPlay: false, // 是否自动播放
			audioList: [],
			playIndex: 0,
			playAudioSet: null,
			speakOf: false, // 说话中 true  不说话状态 false
			isAllSpeakOf: false, // 群聊标志,
			ChatFomat: ChatFomat
		};
	},
	watch: {
		speaking: function (val) {
			if (!val) {
				this.background = '#edf2fc';
				this.color = '#c6c6c6';
			} else {
				this.background = '';
				this.color = '';
			}
		},
		conversationId(val) {
			this.refreshList(val);
		},
		'$store.state.socket.simulationText': function (val) { //  仿真聊天
			if (val.conversationId) {
				this.handleSimulationText(val);
			}
		},
		'$store.state.socket.jointRoomInfo': function (val) { //  综合演练房间信息
			if (val.creatorId) {
				this.handleRoomInfo(val);
			}
		},
		'$store.state.socket.chatContentSimuList': function (val) { //  进入、离开仿真信息
			if (val.id) {
				this.handelTextList(val);
			}
		}
	},
	async mounted() {
		this.userId = this.$store.state.user.id;
		if (this.speaking) {
			this.background = '';
			this.color = '';
		}
		this.allConversationId = await this.getChathistory('', '');
		EventBus.$on('chatSubscribeStop', () => {
			this.clearSubscribe();
		});
		this.playSetInterval();
	},
	beforeDestroy() {
		EventBus.$off('chatSubscribeStop');
		clearInterval(this.playAudioSet);
		this.playAudioSet = null;
	},
	methods: {
		clearSubscribe() {
			clearSubscribe(displayTopic);
		},
		// 人员状态 设置到对话框内容
		handelTextList(params) {
			if (params.inRoom) {
				if (this.conversationId) {
					const paramState = {
						key: this.conversationIde,
						value: params
					};
					this.$store.dispatch('socket/setMessage', paramState);
				}
				if (params.session == 'session') {
					this.textList.push(params);
				}

				this.$nextTick(() => {
					this.$refs.content.scrollTop = this.$refs.content.scrollHeight;
				});
			}
		},
		// 语音录制开始
		startRecording() {
			if (this.speaking && this.conversationId) {
				this.background = '#ccc';
				this.speak = '录音中...';
				this.sending = false;
				this.speakOf = true;
				HZRecorder.init.get(rec => {
					if (typeof rec == 'object') {
						this.recorders = rec;
						this.recorders.start();
					} else {
						this.background = '';
						this.speak = '按住说话';
					}
				});
			}
		},
		// 停止录制
		async stopRecording() {
			if (this.speaking && this.conversationId) {
				this.background = '';
				this.speak = '按住说话';
				this.sending = true;
				if (this.recorders) {
					this.recorders.stop();
					var fd = new FormData();
					fd.append('file', this.recorders.getBlob());
					const param = {
						file: fd,
						group: this.group,
						conversationId: this.conversationId
					};

					await postDataBd(param).catch(error => {
						this.sending = false;
						this.speakOf = false;
						const message = JSON.parse(error.message);
						if (message.err_no == 3301) {
							this.$message({
								showClose: true,
								message: '音频质量有问题',
								type: 'error'
							});
						} else if (message.err_no == 3308) {
							this.$message({
								showClose: true,
								message: '音频过长,建议60s以下',
								type: 'error'
							});
						} else if (message.err_no == 3314) {
							this.$message({
								showClose: true,
								message: '音频太短,建议重录',
								type: 'error'
							});
						} else {
							this.$message({
								showClose: true,
								message: '网络问题，请重试',
								type: 'error'
							});
						}
					});
					this.recorders = null;
				} else {
					this.sending = false;
					this.speakOf = false;
					this.$message({
						showClose: true,
						message: '音频太短,建议重录',
						type: 'error'
					});
				}
			}
		},
		playAudio(nor) {
			this.$refs.audio.src = nor.src;
			this.$refs.audio.play();
		},
		handleRoomInfo(data) {
			if (data.state == '03') { // 退出房间
				this.$router.push({ path: `/` });
				this.clearSubscribe();
			} else if (data.state == '01') { // 进入准备中
				const query = { group: this.group };
				this.$router.push({ path: `/trainroom`, query: query });
				this.clearSubscribe();
			}
			this.$store.dispatch('socket/setJointRoomInfo'); // 清空房间信息
		},
		// 获取历史记录list
		async getChathistory(code, userId) {
			this.targetId = userId;
			this.conversationId = '';
			this.textList = [];
			this.$store.dispatch('socket/setSimulationTextList');
			try {
				// 获取历史记录
				const params = {
					code: code || '',
					userId: this.targetId || '',
					group: this.group
				};

				const res = await getConversation(params);
				this.conversationId = res.data.id;
				this.isAllSpeakOf = false;
				if (res.data.group) {
					this.isAllSpeakOf = true;
				}

				// 临时历史记录表
				const list = this.$store.state.socket.message[this.conversationId];
				if (list && list.length) {
					this.textList = list.slice();
					this.textList.sort((a, b) => {
						return a.date - b.date;
					});

					this.$nextTick(() => {
						if (this.$refs.content) {
							this.$refs.content.scrollTop = this.$refs.content.scrollHeight;
						}
					});
				}
				return res.data;
			} catch (error) {
				this.conversationId = '';
			}
		},
		handleSimulationText(data) {
			if (data.conversationId == this.conversationId && data.date) {
				this.textList.push(data);
				this.textList.sort((a, b) => {
					return a.date - b.date;
				});
			}
			if (data.conversationId && data.date) { // 保存历史记录表
				const paramState = {
					key: data.conversationId,
					value: data
				};
				this.$store.dispatch('socket/setMessage', paramState);
			}
			// 对用户说话 有返回 判断
			if (data.targetMember && data.targetMember.userId && data.member && data.member.userId == this.userId && !data.group && this.speakOf && !this.$refs.audioAuto.currentTime) {
				// 判断自身对用户说话收到自己信息的时候
				this.speakOf = false;
			}
			// 当在所有人是自动跳转 说完话 有自己信息返回时 可自动跳转
			if (this.isAllSpeakOf && data.member && data.member.userId == this.userId) {
				this.speakOf = false;
			}
			if (data.targetMember && data.targetMember.userId == this.userId && data.member && data.member.userId == this.targetId && !data.group && this.speakOf && !this.$refs.audioAuto.currentTime) {
				// 判断自己与用户对话 且 用户先返回内容时
				this.speakOf = false;
			}
			if (data.targetMember && data.targetMember.userId == this.userId && !data.group && data.id && !this.speakOf) {
				// 他人定位到对自己说话判断
				this.$emit('handleChatShow', data);
			} else if (data.targetMember && data.targetMember.userId == this.userId && !data.group && data.id && this.speakOf) {
				//  他人对自己说话 并且 自己在语音中 判断
				this.$emit('handleChatList', data);
			}

			let operate = {};
			if (data.changeVO && data.changeVO.code) {
				operate = {
					val: data.changeVO.val || '',
					code: data.changeVO.code,
					type: data.changeVO.type,
					operation: data.changeVO.operation
				};
			}

			this.sending = false;
			this.$store.dispatch('socket/setSimulationTextList');
			this.$nextTick(() => {
				this.$refs.content.scrollTop = this.$refs.content.scrollHeight;
				if (data.id != this.userId && data.conversationId == this.conversationId && !data.group && data.targetMember && data.targetMember.userId == this.userId) {
					// 自己与机器对话机器返回 并播放且单对单语音
					this.$refs.audioAuto.src = '';
					this.$refs.audioAuto.src = data.src;
					this.$refs.audioAuto.load();
					this.$refs.audioAuto.play();
					const that = this;
					this.$refs.audioAuto.onended = function () {
						that.speakOf = false;
						that.$refs.audioAuto.currentTime = null;
						if (data.changeVO && data.changeVO.code) {
							sendCommand(that.$route.query.group, operate);
						}
					};
				}
				if (this.isAutoPlay && data.id != this.userId && data.group && this.isShowAuto &&
                        (!data.targetMember || data.targetMember.userId != this.userId)) {
					this.autoPlay(data.src, data.value);
				}
			});
		},
		refreshList(conversationId) {
			this.textList = [];
			this.conversationId = conversationId;
			const list = this.$store.state.socket.message[conversationId];
			if (list && list.length) {
				this.textList = list.slice();
				this.textList.sort((a, b) => {
					return a.date - b.date;
				});
			}
		},
		// 未读消息并说话
		handleTextList(conversationId) {
			this.refreshList(conversationId);
			this.$nextTick(() => {
				this.$refs.content.scrollTop = this.$refs.content.scrollHeight;
				if (this.textList.length && this.textList[this.textList.length - 1].userId != this.userId) {
					this.$refs.audioAuto.src = this.textList[this.textList.length - 1].src;
					this.$refs.audioAuto.play();
				}
			});
		},
		autoPlay(src, name) {
			const param = {
				src: src,
				name: name
			};
			this.audioList.push(param);
		},
		playSetInterval() {
			const that = this;
			this.playAudioSet = setInterval(() => {
				if (this.isAutoPlay && this.audioList && this.audioList.length && !this.$refs.autoPlay.currentTime) {
					const data = this.audioList.shift();
					if (data) {
						this.$refs.autoPlay.src = data.src;
						this.$refs.autoPlay.play();
					}
				}
			}, 2000);

			this.$nextTick(() => {
				if (this.$refs.autoPlay) {
					this.$refs.autoPlay.onended = function () {
						const data = that.audioList.shift();
						if (data) {
							if (that.isAutoPlay) {
								that.$refs.autoPlay.src = data.src;
								that.$refs.autoPlay.play();
							} else {
								that.audioList = [];
								that.$refs.autoPlay.currentTime = null;
							}
						} else {
							that.$refs.autoPlay.currentTime = null;
						}
					};
				}
			});
		},
		clearPlay() {
			this.conversationId = ''; // 会话id
			this.audioList = []; // 播放列表
		}
	}
};
</script>
<style>
    .el-tree {
        overflow-x: hidden;
    }

    .el-tree-node.is-current>.el-tree-node__content {
        background-color: #e4e3e3 !important;
    }
</style>
<style rel="stylesheet/scss" lang="scss" scoped>
    /deep/ {
        .el-tabs__nav {
            margin-left: 18px;
        }
    }

    #nav {
        padding: 30px;
        text-align: center;
    }

    #nav a {
        font-weight: bold;
        color: #2c3e50;
    }

    #nav a.router-link-exact-active {
        color: #42b983;
    }

    ::-webkit-scrollbar {
        width: 3px;
    }

    ::-webkit-scrollbar-thumb {
        background-color: #c7c7c7;
    }

    .box {
        /* display: flex; */
        /* justify-content: center; */
        z-index: 10;
    }

    .audio-boxs {
        display: none;
    }

    .content {
        -webkit-box-orient: vertical;
        height: 300px;
        width: 100%;
        border: 1px solid #ccc;
        border-top: none;

        .chatContent {
            -webkit-box-flex: 1;
            overflow-y: scroll;
            padding-right: 8px;
            height: 268px;

            .newsList {
                list-style: none;
                margin: 0;
                padding: 10px 0;

                li {
                    width: 100%;
                    overflow: hidden;
                    padding-top: 8px;
                }
            }
        }

        .yuyin {
            width: 20px;
            height: 20px;
            cursor: pointer;
            margin-top: 21px;
            margin-right: 3px;
            float: right;
            border: 1px solid #ccc;
            border-radius: 50%;
        }

        .yuyin1 {
            width: 20px;
            height: 20px;
            cursor: pointer;
            margin-top: 21px;
            margin-left: 3px;
            float: left;
            border: 1px solid #ccc;
            border-radius: 50%;
        }

        .nesHead {
            width: 44px;
            height: 44px;
            border-radius: 50%;
            margin-left: 15px;
            float: right;
            display: flex;
            align-items: center;
        }

        .news {
            max-width: 55%;
            width: auto;
            height: auto;
            background: #2683f5;
            padding: 6px 10px;
            margin-top: 15px;
            line-height: 20px;
            font-size: 14px;
            border-radius: 4px;
            position: relative;
            float: right;
            color: #fff;
            text-align: left;

            .jiao {
                position: absolute;
                right: -8px;
                top: 10px;
            }
        }

        .nesHead img {
            width: 44px;
        }

        .answerHead img {
            width: 44px;
        }

        .answerHead {
            width: 44px;
            height: 44px;
            border-radius: 50%;
            margin-left: 15px;
            float: left;
            display: flex;
            align-items: center;
        }

        .answers {
            max-width: 55%;
            width: auto;
            height: auto;
            background: #eee;
            padding: 5px 10px;
            margin-top: 15px;
            line-height: 22px;
            font-size: 14px;
            border-radius: 5px;
            margin-left: 10px;
            position: relative;
            float: left;
            text-align: left;

            .jiao {
                position: absolute;
                left: -8px;
                top: 10px;
            }
        }
    }

    .footChat {
        width: 100%;
        height: 30px;
        border-top: 1px solid #ccc;
        position: relative;

        .inputBox {
            position: relative;
            height: 30px;
            width: 100%;
            float: left;

            textarea {
                width: 99%;
                height: 75px;
                border: none;
                outline: none;
                resize: none;
                font-size: 16px;
            }
        }

        .switch-box {
            position: absolute;
            right: 10px;
            top: 0;
            width: 100px;
            height: 30px;
            line-height: 30px;
            z-index: 3;
        }

        .sendBtn {
            background: #fff;
            width: 100%;
            height: 30px;
            line-height: 30px;
            text-align: center;
            /* background: #0188fb; */
            border: 0;
            /* position: absolute;
                bottom: 10px;
                right: 10px; */
            color: #000;
            cursor: pointer;
            font-size: 12px;
            position: absolute;
            left: 0;
            top: 0;
        }

        .zIndex1 {
            z-index: 1;
        }

        .zIndex2 {
            z-index: 2;
            background: #ccc;
        }
    }
</style>
