<template>
  <div class="voiceChatBox" :class="{'active': drawer}" :style="{'bottom':bottom+'px'}">
    <div class="menuTrainListBtn" @click="clickBtn">
      <div>
        <div id="voiceName" />
        <div class="teleNameIn">语音</div>
      </div>
    </div>
    <div class="chat-box-main">
      <div class="chat-box-header">
        <div class="chat-setting" @click="handleSetting()">
          <i class="el-icon-s-tools" />
        </div>
      </div>
      <div class="chat-box-content1">
        <chat-content
          ref="chatContent"
          :project="project"
          :is-answering="IsAnswering"
          :conversition-id="conversitionId"
          :conversition-member-list="conversitionMemberList"
          :message-list="messageList"
          :my-member-id="myMemberId"
          :simulation-users="simulationUsers"
          :conversition-state-map="conversitionStateMap"
          :common-conversation="commonConversation"
          :user-role="userRole"
          @changeMessageList="changeMessageList"
        />
      </div>
      <div class="chat-box-footer">
        <el-input v-model="textContent" size="small" placeholder="请输入会话文字，点击T发送" style="flex: 1; margin-left: 5px;" :rows="1" />
        <el-button :id="sendTextId" size="mini" class="chat-box-footer-create" :disabled="contentSend" @click="sendText">T</el-button>
        <el-button v-if="!$route.query.record" class="chat-box-footer-create chat-box-footer-send" :class="{'active': recordSending}" :disabled="audioPlay" size="mini" type="primary" @click="startRecording()">
          <el-progress id="voice_progress_bar" type="circle" :show-text="false" :percentage="100/60*seconds" :width="40" :stroke-width="2" status="success" />
          <i v-if="recordSending" class="el-icon-close close_icon" @click.stop="cancleRecording()" />
          <span class="iconfont icon-yuyin">&#xe62b;</span>
        </el-button>
      </div>
      <div v-if="maskShow&&drawer" class="mask" />
    </div>
    <audio id="teleRing" :src="teleRing" preload loop />
    <chat-setting ref="chatSetting" :form="form" @setSetting="setSetting" />
  </div>
</template>
<script>
import teleRing from '@/assets/teleRing.mp3';
import ChatSetting from './chatSetting';
import ChatContent from './chatContent';
import RecordRTC from 'recordrtc';
import {sendChatAudioBase64, overSimulationConversition, getAllConversition, acceptConversitionInvite, sendChatText} from '@/api/chat';
import { getSessionStorage } from '@/utils/auth';
import { getSimulationMemberList} from '@/api/simulation';
import { getUserListCommon } from '@/api/rtSimulation';
import { OperationEvent } from '@/scripts/cmdPlugin/OperationHandler';
import {menuOperate, commitOperate} from '@/jmapNew/theme/components/utils/menuOperate';
export default {
    name: 'NewChatBox',
    components:{
        ChatSetting,
        ChatContent
    },
    props: {
        group: {
            type: String,
            required: true
        },
        userRole: {
            type: String,
            required: true
        },
        isReplaceBg: {
            type: Boolean,
            default: false
        }
    },
    data() {
        return {
            drawer: false,
            bottom:15,
            recordSending:false,
            commonConversation: false,
            seconds:0,
            inter:null,
            connectSuccess:false,
            teleRing:teleRing,
            recorders: null,
            microphone:null,
            createLoading:false,
            form:{
                language:'zh',
                sex:'1'
            },
            treeData: [],
            defaultProps: {
                children: 'children',
                label: 'label'
            },
            // queryMember: '',
            activeTrains: [],
            firstClick: true,
            memberData: {},
            simulationUsers: {},
            userString: '',
            memberIdList: [],
            memberObject: '',
            quitLoading: false,
            conversitionMemberList: [],
            commonMemberList: [],
            messageList: [], // 消息列表
            commonMessageList: [],
            conversitionStateMap:{},
            myMemberId: '',
            audioPlay:false,
            textContent: ''
        };
    },
    computed:{
        contentSend() {
            return !this.textContent;
        },
        project() {
            return getSessionStorage('project');
        },
        IsAnswering() {
            return !(this.$route.path.includes('refereeJsxtDisplay'));
        },
        maskShow() {
            return this.isReplaceBg;
        },
        userId() {
            return this.$store.state.user.id;
        },
        conversitionId() {
            return (this.conversitionStateMap[this.myMemberId] || {conversitionId:''}).conversitionId;
        },
        connect() {
            return (this.conversitionStateMap[this.myMemberId] || {connect:false}).connect;
        },
        privateMemberList() {
            return (this.conversitionStateMap[this.myMemberId] || {privateMemberList: []}).privateMemberList;
        },
        privateMessageList() {
            if (this.conversitionStateMap[this.myMemberId] && this.conversitionStateMap[this.myMemberId].connect) {
                return (this.conversitionStateMap[this.myMemberId] || {privateMessageList: []}).privateMessageList;
            } else {
                return [];
            }
        },
        sendTextId() {
            return OperationEvent.Conversation.Chat.menu.domId;
        }
    },
    watch:{
        connect(val) {
            if (val) {
                this.conversitionMemberList = this.privateMemberList;
                this.messageList = [...this.privateMessageList];
            }
        },
        // userRole(val) {
        //     if (val == 'AUDIENCE') {
        //         this.goCommonConversation();
        //         this.myMemberId = '';
        //     } else {
        //         this.myMemberId = (this.simulationUsers[this.userId] || {}).memberId;
        //         this.cancelCommonConversation();
        //     }
        // },
        '$store.state.map.mapViewLoadedCount': function(val) {
            const object = document.querySelector('.menuButton');
            if (object) {
                const objectBottom = object.offsetHeight || 0;
                this.bottom = objectBottom + 15;
            } else {
                this.bottom = 15;
            }
            this.isAudienceInitData();
            getSimulationMemberList(this.group).then(resp => {
                this.$store.dispatch('training/setMemberList', {memberList:resp.data, userId:this.$store.state.user.id});
            }).catch(() => {
                this.$messageBox('获取仿真成员列表失败！');
            });
            getUserListCommon(this.$route.query.group).then(res => {
                this.$store.dispatch('training/setSimulationUserList', res.data);
            }).catch(() => {
                this.$messageBox('获取所有仿真用户失败！');
            });
        },
        '$store.state.training.prdType': function(val) {
            this.$nextTick(() => {
                const object = document.querySelector('.menuButton');
                if (object) {
                    const objectBottom = object.offsetHeight || 0;
                    this.bottom = objectBottom + 15;
                } else {
                    this.bottom = 15;
                }
            });
        },
        '$store.state.socket.createConversition':function(val) {
            val.memberList.forEach(member => {
                // if (val.creatorId == member.memberId) {
                this.$set(this.conversitionStateMap, member.memberId, {conversitionId: val.id, privateMemberList: val.memberList, privateMessageList: [], connect:member.connect});
                // }
            });
        },
        '$store.state.socket.inviteSimulationConversition':function(val) {
            this.treeData.forEach(item => {
                if (item.children) {
                    const memberList = Object.values(item.children);
                    memberList.forEach(data =>{
                        data.disabled = true;
                    });
                    if (item.children[val.creatorId]) {
                        item.children[val.creatorId].isInviting = true;
                        // const offsetTop = document.getElementById('proper_content_box' + val.creatorId).parentNode.offsetTop;
                        // document.querySelector('.chat-box-content').scrollTop = (offsetTop - 40) > 0 ? (offsetTop - 80) : 0;
                        if (!document.querySelector('#voiceName').classList.contains('flash')) {
                            document.querySelector('#voiceName').classList.add('flash');
                            document.querySelector('#teleRing').play();
                        }
                    }

                }
            });
        },
        '$store.state.map.activeTrainListChange': function (val) { // 按计划行车的列车列表更新标识
            this.activeTrains = [];
            const activeTrainList = this.$store.state.map.activeTrainList;
            if (activeTrainList && activeTrainList.length) {
                activeTrainList.forEach(groupNumber => {
                    this.activeTrains.push(groupNumber);
                });
            }
            this.filterNode();
            if (activeTrainList.length <= 0) {
                this.resetCoversition();
            }
        },
        '$store.state.training.simulationUserList': {
            handler(val, o) {
                this.simulationUsers = {};
                if (val && val.length) {
                    val.forEach(user => {
                        if (!user.userId) {
                            user.userId = user.id;
                        }
                        if (!user.nickName) {
                            user.nickName = user.name;
                        }
                        this.simulationUsers[user.userId] = user;
                    });
                    this.myMemberId = this.simulationUsers[this.userId].memberId;
                }
            },
            deep: true
        },
        '$store.state.socket.exitConversition': function (val) {
            for (const memberId in this.conversitionStateMap) {
                if (memberId == val.memberId) {
                    this.conversitionStateMap[memberId].connect = false;
                    this.conversitionStateMap[memberId].conversitionId = '';
                    this.conversitionStateMap[memberId].privateMemberList = [];
                    this.conversitionStateMap[memberId].privateMessageList = [];
                } else if ( this.conversitionStateMap[memberId].conversitionId == val.id ) {
                    const mList = [];
                    this.conversitionStateMap[memberId].privateMemberList.forEach(member => {
                        if (member.memberId != val.memberId) {
                            mList.push(member);
                        }
                    });
                    this.conversitionStateMap[memberId].privateMemberList = mList;
                }
            }
            // 有人退出会话更新人员列表
            this.treeData.forEach(item => {
                if (item.children && item.children[val.memberId]) {
                    const member = item.children[val.memberId];
                    member.active = false;
                    member.isConnect = false;
                    member.disabled = false;
                }
            });
        },
        '$store.state.training.memberList': function (val) {
            if (val && val.length) {
                this.memberData = this.$store.state.training.memberData;
                const dispatcherList = {};
                const electricDispatcherList = {};
                const depotDispatcherList = {};
                const stationSupervisorList = {};
                const driverList = {};
                const maintainerList = {};
                const parentDepartmentList = {};
                const parkingLotSignalBuilding = {};
                const stationAssistant = {};
                const stationMaster = {};
                const stationSignaler = {};
                const stationPassenger = {};
                const stationSwitchMan = {};
                const stationFacilitator = {};
                const stationWorker = {};
                const deviceManager = {};
                const trainMaster = {};
                val.forEach(item => {
                    const device = this.$store.getters['map/getDeviceByCode'](item.deviceCode);
                    this.memberData[item.id]['active'] = false;
                    this.memberData[item.id]['loading'] = false;
                    this.memberData[item.id]['isInviting'] = false;
                    switch (item.type) {
                    case 'DISPATCHER':
                        this.memberData[item.id].label = '行调' + (item.name || '');
                        this.memberData[item.id].labelName = '行调' + (item.name || '');
                        dispatcherList[item.id] = this.memberData[item.id];
                        break;
                    case 'ELECTRIC_DISPATCHER':
                        this.memberData[item.id].label = '电力调度' + (item.name || '');
                        this.memberData[item.id].labelName = '电力调度' + (item.name || '');
                        electricDispatcherList[item.id] = this.memberData[item.id];
                        break;
                    case 'DEPOT_DISPATCHER':
                        this.memberData[item.id].label = '车辆段信号楼';
                        this.memberData[item.id].labelName = '车辆段信号楼' + (item.name || '');
                        depotDispatcherList[item.id] = this.memberData[item.id];
                        break;
                    case 'STATION_SUPERVISOR':
                        this.memberData[item.id].label = device.name;
                        this.memberData[item.id].labelName = '值班员-' + device.name;
                        // this.memberData[item.id].label = '值班员-' + device.name;
                        stationSupervisorList[item.id] = this.memberData[item.id];
                        break;
                    case 'DRIVER':
                        this.memberData[item.id]['show'] = false;
                        this.memberData[item.id].label = item.deviceCode;
                        this.memberData[item.id].labelName = '司机-' + item.deviceCode;
                        driverList[item.id] = this.memberData[item.id];
                        break;
                    case 'MAINTAINER':
                        this.memberData[item.id].label = '通号' + (item.name || '');
                        this.memberData[item.id].labelName = '通号' + (item.name || '');
                        maintainerList[item.id] = this.memberData[item.id];
                        break;
                    case 'PARENT_DEPARTMENT':
                        this.memberData[item.id].label = '上级部门' + (item.name || '');
                        this.memberData[item.id].labelName = '上级部门' + (item.name || '');
                        parentDepartmentList[item.id] = this.memberData[item.id];
                        break;
                    case 'PARKING_LOT_SIGNAL_BUILDING':
                        this.memberData[item.id].label = '停车场信号楼' + (item.name || '');
                        this.memberData[item.id].labelName = '停车场信号楼' + (item.name || '');
                        parkingLotSignalBuilding[item.id] = this.memberData[item.id];
                        break;
                    case 'STATION_ASSISTANT':
                        this.memberData[item.id].label = '车站助理-' + device.name + (item.name || '');
                        this.memberData[item.id].labelName = '车站助理-' + device.name + ( item.name || '');
                        stationAssistant[item.id] = this.memberData[item.id];
                        break;
                    case 'STATION_MASTER':
                        this.memberData[item.id].label = '车站站长-' + device.name + (item.name || '');
                        this.memberData[item.id].labelName = '车站站长-' + device.name + (item.name || '');
                        stationMaster[item.id] = this.memberData[item.id];
                        break;
                    case 'STATION_SIGNALER':
                        this.memberData[item.id].label = '车站信号员-' + device.name + (item.name || '');
                        this.memberData[item.id].labelName = '车站信号员-' + device.name + (item.name || '');
                        stationSignaler[item.id] = this.memberData[item.id];
                        break;
                    case 'STATION_PASSENGER':
                        this.memberData[item.id].label = '车站客运员-' + device.name + (item.name || '');
                        this.memberData[item.id].labelName = '车站客运员-' + device.name + (item.name || '');
                        stationPassenger[item.id] = this.memberData[item.id];
                        break;
                    case 'STATION_SWITCH_MAN':
                        this.memberData[item.id].label = '车站扳道员-' + device.name + (item.name || '');
                        this.memberData[item.id].labelName = '车站扳道员-' + device.name + (item.name || '');
                        stationSwitchMan[item.id] = this.memberData[item.id];
                        break;
                    case 'STATION_FACILITATOR':
                        this.memberData[item.id].label = '车站引导员-' + device.name + (item.name || '');
                        this.memberData[item.id].labelName = '车站引导员-' + device.name + (item.name || '');
                        stationFacilitator[item.id] = this.memberData[item.id];
                        break;
                    case 'STATION_WORKER':
                        this.memberData[item.id].label = '车站工务工-' + device.name + (item.name || '');
                        this.memberData[item.id].labelName = '车站工务工-' + device.name + (item.name || '');
                        stationWorker[item.id] = this.memberData[item.id];
                        break;
                    case 'DEVICE_MANAGER':
                        this.memberData[item.id].label = '设备管理员-' + device.name + (item.name || '');
                        this.memberData[item.id].labelName = '设备管理员-' + device.name + (item.name || '');
                        deviceManager[item.id] = this.memberData[item.id];
                        break;
                    case 'TRAIN_MASTER':
                        // + device.name
                        // + device.name
                        this.memberData[item.id].label = '车务段段长-' + (item.name || '');
                        this.memberData[item.id].labelName = '车务段段长-' + (item.name || '');
                        trainMaster[item.id] = this.memberData[item.id];
                        break;
                    }
                });
                // { label: '全部集中站', value: 'allConcentrateStation', active: false, sign: 'DEVICE_STATION' },
                if (this.$store.state.training.prdType == '02') {
                    stationSupervisorList['ALL_STATION'] = { label: '所有车站', value: 'allStation', active: false, sign: 'ALL_STATION' };
                }
                driverList['ALL_TRAIN'] = { label: '所有司机', value: 'allTrain', show: false, active: false, sign: 'ALL_TRAIN' };
                this.treeData = [{
                    label: '行调',
                    id: 'dispatcher',
                    type: 'role',
                    children: dispatcherList
                }, {
                    label: '车站值班员',
                    id: 'stationSupervisor',
                    type: 'role',
                    children: stationSupervisorList
                }, {
                    label: '司机',
                    id: 'driver',
                    type: 'role',
                    children: driverList
                }, {
                    label: '通号',
                    id: 'maintainer',
                    type: 'role',
                    children: maintainerList
                }, {
                    label: '车辆段信号楼',
                    id: 'depotDispatcher',
                    type: 'role',
                    children: depotDispatcherList
                }, {
                    label: '上级部门',
                    id: 'parentDepartment',
                    type: 'role',
                    children: parentDepartmentList
                }, {

                    label: '电力调度',
                    id: 'electricDispatcher',
                    type: 'role',
                    children: electricDispatcherList
                }, {
                    label: '停车场信号楼',
                    id: 'parkingLotSignalBuilding',
                    type: 'role',
                    children: parkingLotSignalBuilding
                },
                {
                    label: '车站助理',
                    id: 'stationAssistant',
                    type: 'role',
                    children: stationAssistant
                },
                {
                    label: '车站站长',
                    id: 'stationMaster',
                    type: 'role',
                    children: stationMaster
                },
                {
                    label: '车站信号员',
                    id: 'stationSignaler',
                    type: 'role',
                    children: stationSignaler
                },
                {
                    label: '车站客运员',
                    id: 'stationPassenger',
                    type: 'role',
                    children: stationPassenger
                },
                {
                    label: '车站扳道员',
                    id: 'stationSwitchMan',
                    type: 'role',
                    children: stationSwitchMan
                },
                {
                    label: '车站引导员',
                    id: 'stationFacilitator',
                    type: 'role',
                    children: stationFacilitator
                },
                {
                    label: '车站工务工',
                    id: 'stationWorker',
                    type: 'role',
                    children: stationWorker
                },
                {
                    label: '设备管理员',
                    id: 'deviceManager',
                    type: 'role',
                    children: deviceManager
                },
                {
                    label: '车务段段长',
                    id: 'trainMaster',
                    type: 'role',
                    children: trainMaster
                }
                ];
                this.initCommonMemberList();
                this.filterNode();
                // this.$nextTick(() => {
                //     if (this.$refs.tree) {
                //         this.$refs.tree.filter(this.queryMember);
                //     }
                // });
            }
        },
        '$store.state.socket.simulationReset': function () { // 仿真重置
            this.conversitionStateMap = {};
            this.commonMessageList = [];
            this.messageList = [];
            const voiceName = document.querySelector('#voiceName');
            if (voiceName) {
                voiceName.classList.remove('flash');
            }
            document.querySelector('#teleRing').pause();
        },
        '$store.state.socket.acceptConversionInvite':function(val) {
            this.conversitionStateMap[val.memberId].connect = true;
            this.conversitionStateMap[val.memberId].conversitionId = val.id;
            if (this.conversitionId == val.id) {
                this.treeData.forEach(data => {
                    if (data.children && val.memberId != this.myMemberId) {
                        const member = data.children[val.memberId];
                        if (member) {
                            member.isConnect = true;
                            member.active ? member.loading = false : member.active = true;
                        }
                    }
                });
            }
            if (this.myMemberId == val.memberId) {
                this.connectSuccess = true;
                document.querySelector('#voiceName').classList.remove('flash');
                document.querySelector('#teleRing').pause();
                this.treeData.forEach(data => {
                    if (data.children) {
                        const member = data.children[val.creatorId];
                        if (member) {
                            member.active = true;
                            member.isConnect = true;
                            member.isInviting = false;
                        }
                    }
                });
            }
        },
        '$store.state.scriptRecord.audioPlay':function(val) {
            this.audioPlay = val;
        },
        '$store.state.scriptRecord.updateRoleId':function(val) {
            if (this.conversitionStateMap[val]) {
                this.treeData.forEach(item => {
                    if (item.children) {
                        const memberList = Object.values(item.children);
                        memberList.forEach(data =>{
                            const member = this.conversitionStateMap[val];
                            // && privateMem.connect;
                            const memberInfo = member.privateMemberList.find(privateMem=>{ return privateMem.memberId == data.id; });
                            // member.connect
                            if (member && data.id != val && memberInfo) {
                                data.isConnect = true;
                                data.active = true;
                                this.connectSuccess = true;
                            } else {
                                data.active = false;
                                data.isConnect = false;
                                this.connectSuccess = false;
                            }
                            data.loading = false;
                            data.disabled = false;
                            data.isInviting = false;
                        });
                    }
                });
                if (!this.connect) {
                    this.memberIdList = [];
                    this.memberObject = '';
                }
            } else {
                this.memberIdList = [];
                this.memberObject = '';
                this.connectSuccess = false;
                this.treeData.forEach(item => {
                    if (item.children) {
                        const memberList = Object.values(item.children);
                        memberList.forEach(data =>{
                            data.active = false;
                            data.isConnect = false;
                            data.loading = false;
                            data.disabled = false;
                            data.isInviting = false;
                        });
                    }
                });
            }

        }
    },
    beforeDestroy() {
        this.$store.dispatch('scriptRecord/updateAudioPlay', false);
    },
    mounted() {
        this.firstClick = true;
        this.$nextTick(() => {
            this.filterNode();
        });
    },
    methods:{
        getUserRole() {
            if (this.userRole === 'AUDIENCE') {
                this.goCommonConversation();
                this.myMemberId = '';
            } else {
                this.myMemberId = (this.simulationUsers[this.userId] || {}).memberId;
                this.cancelCommonConversation();
            }
        },
        clickBtn() {
            this.drawer = !this.drawer;
        },
        acceptUser() {
            acceptConversitionInvite(this.group, this.conversitionId).then(res=>{
                this.connectSuccess = true;
                document.querySelector('#voiceName').classList.remove('flash');
                document.querySelector('#teleRing').pause();
                this.treeData.forEach(data => {
                    if (data.children) {
                        const member = data.children[res.data.creatorId];
                        if (member) {
                            member.active = true;
                            member.isConnect = true;
                            member.isInviting = false;
                        }
                    }
                });
            });

        },
        setSetting(data) {
            this.form = data;
        },
        coverName(inviteUser) {
            const member = this.$store.state.training.memberData[inviteUser.creatorId];
            if (member.userId) {
                const user = this.simulationUsers[member.userId];
                return member.label + '(' + user.nickName + ')';
            } else {
                return member.label;
            }
        },
        // 语音录制开始
        startRecording() {
            this.audioPlay = true;
            const that = this;
            if (!this.recordSending) {
                if (!this.recordSending && !this.recorders && !this.microphone) {
                    this.$refs.chatSetting.doClose();
                    const StereoAudioRecorder = RecordRTC.StereoAudioRecorder;
                    navigator.getUserMedia(
                        { audio: true } // 只启用音频
                        , function (stream) {
                            that.microphone = stream;
                            that.recorders = new RecordRTC(that.microphone, {
                                type: 'audio',
                                recorderType: StereoAudioRecorder,
                                numberOfAudioChannels: 1,
                                bitsPerSecond:256000,
                                desiredSampRate: 16000
                            });
                            that.recorders.startRecording();
                            that.recordSending = true;
                            that.audioPlay = false;
                            that.inter = setInterval(() => {
                                if (that.seconds < 60) {
                                    that.seconds++;
                                } else {
                                    clearInterval(that.inter);
                                    that.stopRecording();
                                }
                            }, 1000);
                        }, function (error) {
                            that.audioPlay = false;
                            switch (error.code || error.name) {
                            case 'PERMISSION_DENIED':
                            case 'PermissionDeniedError':
                                that.$message({
                                    showClose: true,
                                    message: '用户拒绝提供信息',
                                    type: 'error'
                                });
                                break;
                            case 'NOT_SUPPORTED_ERROR':
                            case 'NotSupportedError':
                                that.$message({
                                    showClose: true,
                                    message: '浏览器不支持硬件设备',
                                    type: 'error'
                                });
                                break;
                            case 'MANDATORY_UNSATISFIED_ERROR':
                            case 'MandatoryUnsatisfiedError':
                                that.$message({
                                    showClose: true,
                                    message: '无法发现指定的硬件设备',
                                    type: 'error'
                                });
                                break;
                            default:
                                that.$message({
                                    showClose: true,
                                    message: '无法打开麦克风',
                                    type: 'error'
                                });
                                break;
                            }
                        }
                    );
                }
            } else {
                this.stopRecording(); // 发送语音
            }
        },
        cancleRecording() {
            if (this.microphone) {
                clearInterval(this.inter);
                this.seconds = 0;
                this.microphone.stop();
                this.microphone = null;
                this.recordSending = false;
                this.recorders = null;
            }
        },
        // 停止录制 发送语音
        stopRecording() {
            this.audioPlay = true;
            clearInterval(this.inter);
            this.seconds = 0;
            const that = this;
            this.recorders.stopRecording(function(blobURL) {
                that.recorders.getDataURL(function(BaseURL) {
                    // const blob = that.recorders.getBlob();
                    // const fd = new FormData();
                    // fd.append('file', blob);
                    sendChatAudioBase64(that.group, {fileBase64Str: BaseURL})
                        .then((data) => {
                            that.textContent = '';
                            that.audioPlay = false;
                        })
                        .catch(error => {
                            console.log(error);
                            that.$message.error('语音发送失败: ' + error.message);
                            that.audioPlay = false;
                        });
                    if (that.microphone) {
                        that.microphone.stop();
                        that.microphone = null;
                        that.recordSending = false;
                        that.recorders = null;
                    }
                });
            });
        },
        sendText() {
            // sendChatText(this.group, {content: this.textContent}).then(resp => {
            //     this.textContent = '';
            // }).catch((error) => {
            //     this.$message.error('发送会话文字失败：' + error.message);
            // });
            commitOperate(menuOperate.Conversation.Chat, {content: this.textContent}, 3).then(({valid})=>{
                if (valid) {
                    this.textContent = '';
                }
            }).catch((error) => {
                this.$message.error('发送会话文字失败：' + error.message);
            });
        },
        handleSetting() {
            this.$refs.chatSetting.doShow();
        },
        // 过滤全部列车 显示正在运行的列车
        filterNode() {
            if (this.treeData[2]) {
                const trainList = Object.values(this.treeData[2]['children']);
                trainList.forEach(train => {
                    train.show = false;
                    if (this.activeTrains.includes(train.deviceCode)) {
                        train.show = true;
                    }
                });
                const member = this.treeData[2]['children']['ALL_TRAIN'];
                if (this.activeTrains.length > 0) {
                    member.show = true;
                } else {
                    this.memberObject = '';
                    const trainList = Object.values(this.treeData[2].children);
                    trainList.forEach(train=>{
                        if (train.active) {
                            train.active = false;
                            const memberId = train.id;
                            this.memberIdList.splice(this.memberIdList.indexOf(memberId), 1);
                        }
                    });
                }
            }
        },
        // 退出会话
        quitConversition() {
            this.quitLoading = true;
            this.userString = '';
            overSimulationConversition(this.group, this.conversitionId).then(resp => {
                if (this.recordSending) {
                    this.cancleRecording();
                }
                this.connectSuccess = false;
                this.conversitionMemberList = [];
                this.messageList = [];
                this.quitLoading = false;
                this.conversitionStateMap[this.myMemberId].connect = false;
                // this.$nextTick(() => {
                //     this.$refs.tree && this.$refs.tree.filter(this.queryMember);
                // });
                this.treeData.forEach(item => {
                    if (item.children) {
                        const memberList = Object.values(item.children);
                        memberList.forEach(data =>{
                            data.active = false;
                            data.isConnect = false;
                            data.loading = false;
                            data.disabled = false;
                        });
                    }
                });
            }).catch(() => {
                this.$message.error('退出会话失败！');
                this.quitLoading = false;
            });
        },
        sortByMessageTime(message1, message2) {
            const time1 = new Date(message1.time).valueOf();
            const time2 = new Date(message2.time).valueOf();
            return time1 - time2;
        },
        // 获取历史消息
        isAudienceInitData() {
            getAllConversition(this.group).then(resp => {
                const messages = [];
                if (resp.data && resp.data.length) {
                    resp.data.forEach(conversation => {
                        (conversation.messageList || []).forEach(message => {
                            const member = this.memberData[message.memberId];
                            message.src = `${message.audioPath}`;
                            message.members = conversation.memberList;
                            if (member) {
                                message.self = this.$store.state.userId == member.userId;
                            }
                            messages.push(message);
                        });
                        const tempMessageList = [];
                        !conversation.over && conversation.messageList.forEach(message => {
                            message.src = `${message.audioPath}`;
                            tempMessageList.push(message);
                        });
                        !conversation.over && conversation.memberList.forEach(member => {
                            const param = {
                                conversitionId: conversation.id,
                                privateMemberList: conversation.memberList,
                                privateMessageList: tempMessageList
                            };
                            this.$set(this.conversitionStateMap, member.memberId, param);
                        });
                    });
                    this.getUserRole();
                }
                this.commonMessageList = messages.sort(this.sortByMessageTime);
                this.initCommonMemberList();
            });
        },
        // 初始化人员列表
        initCommonMemberList() {
            const temDispatcherList = [];
            const temStationSupervisorList = [];
            const temMaintainerList = [];
            const temDriverList = [];
            const temDepotDispatcherList = [];
            const temStationAssistList = [];
            const temStationMasterList = [];
            const temStationSignalerList = [];
            const temStationPassengerList = [];
            const temStationSwitchManList = [];
            const temStationFacilitatorList = [];
            const temStationWorkerList = [];
            const temDeviceManagerList = [];
            const temTrainMasterList = [];
            this.$store.state.training.memberList.forEach(item =>{
                switch (item.type) {
                case 'DISPATCHER':
                    temDispatcherList.push({memberId: item.id, connect:true });
                    break;
                case 'STATION_SUPERVISOR':
                    temStationSupervisorList.push({memberId: item.id, connect:true });
                    break;
                case 'MAINTAINER':
                    temMaintainerList.push({memberId: item.id, connect:true });
                    break;
                case 'DRIVER':
                    temDriverList.push({memberId: item.id, connect:true });
                    break;
                case 'DEPOT_DISPATCHER':
                    temDepotDispatcherList.push({memberId: item.id, connect:true });
                    break;
                case 'STATION_ASSISTANT':
                    temStationAssistList.push({memberId: item.id, connect:true });
                    break;
                case 'STATION_MASTER':
                    temStationMasterList.push({memberId: item.id, connect:true });
                    break;
                case 'STATION_SIGNALER':
                    temStationSignalerList.push({memberId: item.id, connect:true });
                    break;
                case 'STATION_PASSENGER':
                    temStationPassengerList.push({memberId: item.id, connect:true });
                    break;
                case 'STATION_SWITCH_MAN':
                    temStationSwitchManList.push({memberId: item.id, connect:true });
                    break;
                case 'STATION_FACILITATOR':
                    temStationFacilitatorList.push({memberId: item.id, connect:true });
                    break;
                case 'STATION_WORKER':
                    temStationWorkerList.push({memberId: item.id, connect:true });
                    break;
                case 'DEVICE_MANAGER':
                    temDeviceManagerList.push({memberId: item.id, connect:true });
                    break;
                case 'TRAIN_MASTER':
                    temTrainMasterList.push({memberId: item.id, connect:true });
                    break;
                }
            });
            this.commonMemberList = [...temDispatcherList, ...temStationSupervisorList, ...temMaintainerList, ...temDriverList, ...temDepotDispatcherList,
                ...temStationAssistList, ...temStationMasterList, ...temStationSignalerList, ...temStationPassengerList, ...temStationSwitchManList,
                ...temStationFacilitatorList, ...temStationWorkerList, ...temDeviceManagerList, ...temTrainMasterList];
            if (this.userRole == 'AUDIENCE' || this.commonConversation) {
                this.conversitionMemberList = [];
                this.messageList = [...this.commonMessageList];
                this.conversitionMemberList = this.commonMemberList;
            }
        },
        changeMessageList(data) {
            this.commonMessageList.push(data.message);
            if (this.conversitionStateMap[data.message.memberId]) {
                (this.conversitionStateMap[data.message.memberId].privateMemberList || []).forEach(member => {
                    this.conversitionStateMap[member.memberId] && this.conversitionStateMap[member.memberId].privateMessageList.push(data.message);
                });
            }
            // if (this.commonConversation) {
            //     this.messageList.push(data.message);
            // } else if (!this.commonConversation && this.conversitionId === data.id && this.conversitionStateMap[this.myMemberId] && this.conversitionStateMap[this.myMemberId].connect) {
            //     this.messageList.push(data.message);
            // }
            this.messageList.push(data.message);
        },
        goCommonConversation() {
            !this.commonConversation && this.$refs.chatContent && this.$refs.chatContent.conversationChange();
            this.commonConversation = true;
            this.conversitionMemberList = this.commonMemberList;
            this.messageList = [...this.commonMessageList];
        },
        cancelCommonConversation() {
            this.commonConversation && this.$refs.chatContent && this.$refs.chatContent.conversationChange();
            this.commonConversation = false;
            this.conversitionMemberList = this.privateMemberList;
            this.messageList = [...this.privateMessageList];
            this.$nextTick(() => {
                // this.$refs.tree && this.$refs.tree.filter(this.queryMember);
                this.filterNode();
            });
        },
        clearAllData() {
            this.recordSending = false;
            this.inter = null;
            this.recorders = null;
            this.microphone = null;
            this.treeData = [];
            this.conversitionMemberList = [];
            this.messageList = [];
        },
        // 剧本重置清空公有会话
        resetCoversition() {
            this.commonMessageList = [];
            this.conversitionStateMap = {};
            this.messageList = [];
            this.connectSuccess = false;
            this.$store.dispatch('scriptRecord/updateAudioPlay', false);
            this.treeData.forEach(item => {
                if (item.children) {
                    const memberList = Object.values(item.children);
                    memberList.forEach(data =>{
                        data.active = false;
                        data.isConnect = false;
                        data.loading = false;
                        data.disabled = false;
                        data.isInviting = false;
                    });
                }
            });
        }
    }
};
</script>
<style lang="scss" scoped>
.voiceChatBox {
	position: absolute;
    left: 0;
	top: calc((100% - 600px) / 2);
    height: 600px;
	width: 503px;
	transform: translateX(-503px);
	transition: all 0.4s;
	z-index: 35;
	&.active{
		transform: translateX(0px);
	}
}
.menuTrainListBtn {
    background: #fff;
    text-align: center;
    border-radius: 0px 6px 6px 0px;
    position: absolute;
    top: 40%;
    z-index: 2;
	transform: translateX(502px);
    cursor: pointer;
	z-index: 9;
	display: flex;
    flex-direction: column;
    align-items: center;
    text-align: center;
    justify-content: center;
    padding: 7px 4px;
	.el-icon-more{
		font-size: 20px;
		margin-top: 9px;
		transform-origin: 50% 50%;
		transform: rotate(90deg);
		margin-left:0px;
	}
}
.chat-box-header{
    width: 100%;
    height: 40px;
    border-bottom: 1px #dedede solid;
	.chat-box-header-title{
		font-size: 15px;
		margin-left: 15px;
		display: inline-block;
		margin-top: 5px;
		width: 70%;
		overflow: hidden;
		white-space: nowrap;
		text-overflow: ellipsis;
	}
}
.chat-box-content1{
	height: 500px;
	position: relative;
	border-top: 1px #9a9a9a solid;
	margin-top: 8px;
}

.chat-box-footer{
    display: flex;
	align-items: center;
    width: 100%;
	height: 55px;
	border-top: 1px solid #afafaf;
}
.chat-setting{
    float: right;
    line-height: 40px;
    margin-right: 10px;
    cursor: pointer;
    font-size: 16px;
}
.chat-box-main{
    position: absolute;
    width: 100%;
    left: 0;
    height: 100%;
    top: 0;
    border-right: 1px #dedede solid;
    z-index: 4;
    background: #fff;
    border-radius: 5px;
    left: 0;
    // font-size:0;
}
.chat-box-footer-create{
    font-size: 16px;
    color: #fff;
	margin-left: 5px;
	margin-right: 5px;
    cursor: pointer;
	width: 40px;
	height: 40px;
	border-radius: 50%;
	background: green;
	border: none;
	display: flex;
    justify-content: center;
    align-items: center;
}
.chat-box-footer-send{
	position: relative;
    background: #F2F2F2;
	cursor: pointer;
	.icon-yuyin{
		color: #333;
		font-size: 24px;
		margin: 0;
	}
	&.active{
		.icon-yuyin{
			color: green;
		}
	}
	.close_icon{
		position: absolute;
		top: -15px;
		left: 11px;
		font-size: 16px;
		color: #333;
		font-weight: 600;
	}
}
#voice_progress_bar{
    width: 40px;
    height: 40px;
    position: absolute;
    left: 0;
    top: 0;
    border-radius: 50%;
}
.chat-box-footer-send.disbled{
    cursor: no-drop;
}
.connectSuccess{
    position:absolute;
    width:100%;
    height:100%;
    left:0;
    top:0;
    z-index:2;
}
.proper_content_box_text{
    position: absolute;
}
.flash{
    opacity: 1;
    animation: isInviting infinite 1s;
    -moz-animation: isInviting infinite 1s;	/* Firefox */
    -webkit-animation: isInviting infinite 1s;	/* Safari 和 Chrome */
    -o-animation: isInviting infinite 1s;	/* Opera */
}

.mask {
	position: absolute;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	opacity: 0.7;
	z-index: 2000;
	&::before{
		content: '';
		position: absolute;
		top:0;
		right:0;
		bottom:0;
		left:0;
		background: #aaa;
		filter: blur(20px);
	}
}

#voiceName{
    background: #6BBE16;
    position: absolute;
    width: 100%;
    height: 100%;
    left: 0;
    top: 0;
    border-radius: 0px 5px 5px 0px;
    z-index: -1;
    opacity: 0;
}
</style>
<style lang="scss">
.isInviting::before{
    content: '';
    position: absolute;
    width: 100%;
    height: 100%;
    border-radius: 5px;
    background:#6BBE16;
    animation: isInviting infinite 1s;
    -moz-animation: isInviting infinite 1s;	/* Firefox */
    -webkit-animation: isInviting infinite 1s;	/* Safari 和 Chrome */
    -o-animation: isInviting infinite 1s;	/* Opera */
}
@keyframes isInviting
{
    0% {opacity:1;}
    50%{opacity:0;}
    100% {opacity: 1;}
}
@-webkit-keyframes isInviting /* Safari 和 Chrome */
{
    0% {opacity:1;}
    50%{opacity:0;}
    100% {opacity: 1;}
}
.teleNameIn{
    width: 16px;
    white-space: pre-wrap;
    font-size:16px;
}
</style>
