<template>
  <div>
    <div v-show="showChat && !minimize" class="reminder-drag">
      <div class="tabs-roles">
        <div class="roles roles-first">聊天窗口</div>
        <div class="minimality" @click="handleMinimality('min')">
          <i class="el-icon-remove" />
        </div>
      </div>
      <div class="reminder-content">
        <div class="tabs-content">
          <div class="relation">
            <el-scrollbar wrap-class="scrollbar-wrapper" :style="{ height: '290px' }">
              <el-tree
                ref="personTree"
                :data="treeData"
                :props="defaultProps"
                node-key="nodeId"
                @node-click="chatClick"
              >
                <span slot-scope="{ node, data }">
                  <span
                    style="font-size: 14px; padding-left: 12px; color: #606266; cursor: pointer;"
                  >{{ data.name ? data.name : data.groupNumber }}</span>
                </span>
              </el-tree>
            </el-scrollbar>
          </div>
          <div class="box">
            <audio ref="audio" style="display: none;" />
            <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>
                  </div>
                </ul>
              </div>
              <div class="footChat">
                <div class="inputBox">
                  <div
                    class="sendBtn zIndex1"
                    :style="{background: background}"
                    @mousedown="startRecording()"
                    @mouseup="stopRecording()"
                  >{{ speak }}</div>
                  <div v-show="sending" class="sendBtn zIndex2" :style="{background: background}">
                    发送中...
                  </div>
                </div>
              </div>
            </div>
            <!-- 遮罩层 -->
            <div v-show="chatShow" class="hello content" />
          </div>
        </div>
      </div>
    </div>
    <div v-show="showChat && minimize" class="reminder-drag minimize-box">
      <div class="chat-title">聊天窗口</div>
      <div class="minimality" @click="handleMinimality('max')">
        <i class="el-icon-circle-plus" />
      </div>
    </div>
  </div>
</template>

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

export default {
	name: 'ChartView',
	props: {
		group: {
			type: String,
			required: true
		}
	},
	data() {
		return {
			userId: '',
			ws: null,
			flag: false,
			recorders: null,
			text: '',
			textList: [],
			personList: [],
			showChat: false,
			background: '',
			activeName: 'first',
			chatShow: true,
			code: '',
			label: '',
			message: {},
			sending: false,
			speak: '按住说话',
			conversationId: '',
			treeData: [
				{
					children: [],
					name: '集中站'
				},
				{
					children: [],
					name: '列车'
				}
			],
			defaultProps: {
				children: 'children'
			},
			minimize: false,
			ChatFomat: ChatFomat
		};
	},
	watch: {
		'$store.state.map.map.stationList': function (val) { // 执行一次 以后不会有变化
			if (val.length) {
				this.initMenu(val);
			}
		},
		'$store.state.socket.simulationText': function (val) { //  仿真聊天
			if (val.conversationId) {
				this.handleSimulationText(val);
			}
		},
		'$store.state.training.switchcount': function () {
			this.$nextTick(() => {
				const started = this.$store.state.training.started;
				if (started) {
					this.showChat = true;
				} else {
					EventBus.$emit('trainView');
					this.showChat = false;
					this.chatShow = true;
					if (this.$refs.personTree) {
						this.$refs.personTree.setCurrentKey(null);
					}
				}
			});
		}
	},
	async mounted() {
		EventBus.$on('trainView', () => {
			this.$nextTick(() => {
				const list = this.$store.getters['training/viewTrainList'];
				list.sort((a, b) => {
					return Number(a.groupNumber) - Number(b.groupNumber);
				});

				this.treeData[1].children = [];
				list.forEach(item => {
					item.nodeId = item._code;
					this.treeData[1].children.push(item);
				});
			});
		});

		EventBus.$on('chatSubscribeStop', () => {
			this.clearSubscribe();
		});

		this.userId = this.$store.state.user.id;
	},
	beforeDestroy() {
		EventBus.$off('trainView');
		EventBus.$off('chatSubscribeStop');
	},
	methods: {
		handleMinimality(data) {
			if (data == 'min') {
				this.minimize = true;
			} else {
				this.minimize = false;
			}
		},
		// 获取设备集中站
		initMenu(stationList) {
			this.treeData[0].children = [];
			stationList.forEach(station => {
				if (station.centralized) {
					const node = {
						name: station.name,
						code: station.code,
						nodeId: station.code
					};
					this.treeData[0].children.push(node);
				}
			});
		},
		// 发送文字
		sendText() {
			if (!this.text.trim()) {
				alert('内容为空，不可发送！');
				this.text = '';
			} else {
				this.stomp.send('/app/chatroom', this.text);
				this.text = '';
			}
		},
		// 语音录制开始
		async startRecording() {
			if (this.conversationId) {
				this.background = '#ccc';
				this.speak = '录音中...';
				this.sending = false;
				HZRecorder.init.get(rec => {
					if (typeof rec == 'object') {
						this.recorders = rec;
						this.recorders.start();
					}
				});
			} else {
				const params = {
					group: this.group,
					code: this.code || '',
					userId: ''
				};
				const res = await getConversation(params);
				this.conversationId = res.data.id;
			}
		},
		// 停止录制
		async stopRecording() {
			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;
					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.$message({
					showClose: true,
					message: '音频太短,建议重录',
					type: 'error'
				});
			}
		},
		playAudio(nor) {
			this.$refs.audio.src = nor.src;
			this.$refs.audio.play();
		},
		back() {
			this.stomp.send('/app/chatroom', '断开连接');
			this.clearSubscribe();
		},
		clearSubscribe() {
			clearSubscribe(displayTopic);
		},
		async chatClick(obj) {
			if (!obj.children) {
				this.textList = [];
				if (obj.code) {
					this.code = obj.code;
				} else {
					this.code = obj._code;
				}
				this.chatShow = false;
				// 获取历史记录
				const params = {
					group: this.group,
					code: this.code || '',
					userId: ''
				};
				const res = await getConversation(params);
				this.conversationId = res.data.id;
				// 临时历史记录表
				const list = this.message[this.conversationId];
				if (list && list.length) {
					list.sort((a, b) => {
						return a.date - b.date;
					});
					this.textList = [...list];
					this.$nextTick(() => {
						this.$refs.content.scrollTop = this.$refs.content.scrollHeight;
					});
				}
			}
		},
		handleSimulationText(data) {
			if (data.conversationId == this.conversationId) {
				this.textList.push(data);
				this.textList.sort((a, b) => {
					return a.date - b.date;
				});
			}
			if (data.changeVO && data.changeVO.code) {
				const operate = {
					val: data.changeVO.val || '',
					code: data.changeVO.code,
					type: data.changeVO.type,
					operation: data.changeVO.operation
				};
				this.$refs.audioAuto.onended = () => {
					sendCommand(this.group, operate);
				};
			}
			if (data.conversationId) {
				if (!this.message[data.conversationId]) {
					this.message[data.conversationId] = [];
				}
				this.message[data.conversationId].push(data);
			}
			this.$store.dispatch('socket/setSimulationTextList');
			this.sending = false;
			this.$nextTick(() => {
				this.$refs.content.scrollTop = this.$refs.content.scrollHeight;
				if (data.id != this.userId && !data.group) {
					this.$refs.audioAuto.src = data.src;
					this.$refs.audioAuto.play();
				}
			});
		}
	}
};
</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;
        }
    }

    .reminder-drag {
        position: absolute;
        float: left;
        left: 10px;
        bottom: 10px;
        width: 500px;
        height: 340px;
        background-color: #fff;
        border-radius: 5px;
        overflow: hidden;
        z-index: 2;
        font-size: 18px;

        .reminder-content {}
    }

    #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 {
        flex-grow: 1;
    }

    .tabs-roles {
        overflow: hidden;
        height: 40px;
        line-height: 40px;
        -webkit-box-sizing: border-box;
        box-sizing: border-box;

        .roles {
            padding: 0 20px;
            height: 41px;
            list-style: none;
            font-size: 14px;
            font-weight: 500;
            color: #303133;
            cursor: pointer;
            border-left: 1px solid #e4e7ed;
            border-right: 1px solid #e4e7ed;
            float: left;
        }

        .roles-first {
            border-right: none;
        }

        .minimality {
            float: right;
            line-height: 40px;
            margin-right: 10px;
            cursor: pointer;
        }
    }

    .tabs-content {
        height: 300px;
        width: 100%;
        display: flex;
    }

    .content {
        -webkit-box-orient: vertical;
        height: 300px;
        /* width: 500px; */
        border: 1px solid #ccc;

        .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;

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

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

        .zIndex1 {
            z-index: 1;
        }

        .zIndex2 {
            z-index: 2;
            background: #ccc;
        }
    }

    .minimize-box {
        bottom: 10px;
        width: 300px;
        height: 40px;

        .chat-title {
            float: left;
            font-size: 16px;
            margin-left: 10px;
            line-height: 40px;
        }

        .minimality {
            float: right;
            height: 40px;
            line-height: 40px;
            margin-right: 10px;
            cursor: pointer;
        }
    }

    .relation {
        width: 170px;
        float: left;
        height: 300px;
        border: 1px solid #ccc;
        border-left: none;
        border-right: none;
        padding-top: 5px;
        /* padding: 10px 8px; */

        .personnel {
            width: 100%;
            /* height: 20px; */
            font-size: 16px;
            line-height: 20px;
            padding-left: 5px;
            cursor: pointer;
            padding: 3px 8px;

            &:hover {
                background-color: #e6e6e6;
            }
        }
    }
</style>
